Thursday, May 30, 2013

Copying properties from one object to another

There is always a need to copy the properties from one object to another if they have the same property names. There are available apis like Dozer which facilitates the same, but we need to add the dozer.jar in the classpath which may not always be the right approach and for certain clients can be a lengthy process to get permission.

There are alternative good ways of doing this, if you are using the Spring framework or already use the apache projects. Mentioning below few of the steps how we can do this

Using Apache BeanUtils

BeanUtils.copyProperties(targetObject, sourceObject);

this copies the values of the properties with the same name from the sourceObject  to targetObject. The problem with simply this step is that it will throw and exception if any of the values is null. To avoid the exception we can add the following lines before the copy

BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0); //This will work with apache-beanutils version 1.8 and above.

Using Springs WrapperImpl

  final PropertyDescriptor[] propertyDescriptors =
        BeanUtils.getPropertyDescriptors(source.getClass());
  final BeanWrapper src = new BeanWrapperImpl(source);
  final BeanWrapper trg = new BeanWrapperImpl(target); 
  for(final PropertyDescriptor propertyDescriptor : propertyDescriptors){
        String propName = propertyDescriptor.getName();
         trg.setPropertyValue(
            propName,
            src.getPropertyValue(propName)
        );
    } 
 
The above steps copies all properties from source to target. If needed we can also remove some properties from the propertyDescriptors if not to be copied 

No comments:

Post a Comment