See the following class
public class Parent {
private String name;
private int age;
private Date birthDate;
// getters and setters
}
Suppose I have created a parent object as follows
Parent parent = new Parent();
parent.setName("A meaningful name");
parent.setAge(20);
Notice according to code above birthDate property is null. Now I want to copy only non-null properties from parent object to another. Something like
SomeHelper.copyNonNullProperties(parent, anotherParent);
I need it because I want to update anotherParent object without overwriting its non-null with null values.
Do you know some helper like this one?
I accept minimal code as answer whether no helper in mind
I supose you already have a solution, since a lot of time has happened since you asked. However, it is not marked as solved, and maybe I can help other users.
Have you tried by defining a subclass of the
BeanUtilsBeanof theorg.commons.beanutilspackage? Actually,BeanUtilsuses this class, so this is an improvement of the solution proposed by dfa.Checking at the source code of that class, I think you can overwrite the
copyPropertymethod, by checking for null values and doing nothing if the value is null.Something like this :
Then you can just instantiate a
NullAwareBeanUtilsBeanand use it to copy your beans, for example: