How to Construct Clones of Non-Clonable Objects Or Construct Domain Objects Dynamically from Struts Forms

To Construct Domain Objects Dynamically from Struts Forms was a problem in the project I was working in. This is an extension in making Clones of non-Clonable Objects. So, we did a little bit of research and found a way to do this,

In Apache Commons BeanUtils, there exists the class BeanUtilsBean. Check the following method,

org.apache.commons.beanutils.BeanUtilsBean#copyProperties(destBean, origBean)
As per the official documentation,

Copy property values from the origin bean to the destination bean for all cases where the property names are the same. For each property, a conversion is attempted as necessary. All combinations of standard JavaBeans and DynaBeans as origin and destination are supported. Properties that exist in the origin bean, but do not exist in the destination bean (or are read-only in the destination bean) are silently ignored.


Which is pretty ideal for the job.

The other day, I found the Official Struts option for this while I was browsing through the Struts 1.x documentation for ActionForm. It talks about this method which does pretty much the same,

org.apache.commons.beanutils.PropertyUtils.copyProperties(actionForm, businessObject);
They are in the Same BeanUtils project and internally calls the following method,

org.apache.commons.beanutils.PropertyUtilsBean.copyProperties(java.lang.Object, java.lang.Object)
I tried understanding the differences between these 2 types of methods (BeanUtilsBean vs PropertyUtilsBen). I haven't tried the PropertyUtils way, but the BeanUtilsBean works like a charm :-D

Categories: Java, Struts
Written on November 27, 2010