Having this:
public class Parent {
private String name;
private int age;
private Date birthDate;
private Work work;
static class Work{
private int years;
private String employer;
}
// getters and setters
public static void main(String[] args) {
Parent c = new Parent;
c.setAge(55)
Work work=new Parent.Work();
work.setEmployer("Example");
c.setWork(work);
//save c in a DB...
}
}
I want to copy only the no-null attributes using reflection. The approach described here with beanUtils works very well, but it copies all the no-null wrapped object, and not only the no-null field values:
//fetch c from the db...
Parent sameParent= new Parent;
sameParent.setWork(new Parent.Work());
//Directly from https://stackoverflow.com/questions/1301697/helper-in-order-to-copy-non-null-properties-from-object-to-another-java#answer-3521314
BeanUtilsBean notNull=new NullAwareBeanUtilsBean();
notNull.copyProperties(c, sameParent);
Now, Parent c
will have the field age=55
. The field work.employer
will be null because the object Work has been overridden. Is it possible to modify the @Override copyProperty
method from BeanUtilsBean
to recursively copy only the desired (not null) attributes also from the wrapped objects?
Otherwise, do you know some other way?