How do I copy properties from one bean to another?
Author: Deron Eriksson
Description: This Java tutorial describes how to copy properties from one JavaBean to another.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1
(Continued from page 1)
If we run BeanUtilsCopyProperties Test, we observe the following output:
The console output is shown here:
test.FromBean@1c9b9ca[name=fromBean,aProp=fromBeanAProp,bProp=fromBeanBProp] test.ToBean@6025e7[name=toBean,bProp=toBeanBProp,cProp=toBeanCProp] Copying properties from fromBean to toBean test.FromBean@1c9b9ca[name=fromBean,aProp=fromBeanAProp,bProp=fromBeanBProp] test.ToBean@6025e7[name=fromBean,bProp=fromBeanBProp,cProp=toBeanCProp]
After the call to BeanUtils.copyProperties, notice that the value of the name property and bProp property have been copied from fromBean to toBean. Also, notice that aProp was not copied to toBean since toBean doesn't have an aProp field, and notice that cProp was not altered in toBean since no corresponding property exists in fromBean. As you can see, BeanUtiles.copyProperties copies the properties from one bean to another if the property has the same name. This sure beats writing lots of setter/getter lines in your code to manually copy fields from one bean to another!