Issue
I am trying to copy one object's property values to another object. Below mentioned sample works good. But when tried with child level properties copy it is not ignoring null values. I would like to ignore null values in parent and child as well.
How can I ignore child level null values while copying object from one to another ?
I am using Spring Bean utils. If the solution available in Apache utils also fine.
public static String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
// then use Spring BeanUtils to copy and ignore null using our function
public static void myCopyProperties(Object src, Object target) {
BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}
class Person {
private String name;
private Address address;
public static class Address {
private String apt;
private String state;
private ContactInfo contactInfo;
public static class ContactInfo {
private String primaryEmail;
private String secEmail;
}
}
}
Solution
com.demo.test is my project package. if any object belongs to my package , I am doing regression to copy the value. it works.
public static String[] getNullPropertyNames (Object source, Object target) {
final BeanWrapper src = new BeanWrapperImpl(source);
final BeanWrapper targetBean = new BeanWrapperImpl(target);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) {
emptyNames.add(pd.getName());
}else {
Class<?> accessor = src.getPropertyType(pd.getName());
String cname = accessor.getCanonicalName();
if(cname.contains("com.demo.test")) {
Object targetVal = targetBean.getPropertyValue(pd.getName());
if(targetVal != null) {
BeanUtils.copyProperties(srcValue,targetVal , getNullPropertyNames(srcValue,targetVal));
emptyNames.add(pd.getName());
}
}
}
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
Answered By - Gnana
Answer Checked By - Mary Flores (JavaFixing Volunteer)