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