Arthur Ronald Arthur Ronald - 1 year ago 202
Java Question

Helper in order to copy non null properties from object to another ? (Java)

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");

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 overrides 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


Answer Source

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 BeanUtilsBean of the org.commons.beanutils package? Actually, BeanUtils uses 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 copyProperty method, by checking for null values and doing nothing if the value is null.

Something like this :

import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtilsBean;

public class NullAwareBeanUtilsBean extends BeanUtilsBean{

    public void copyProperty(Object dest, String name, Object value)
            throws IllegalAccessException, InvocationTargetException {
        super.copyProperty(dest, name, value);


Then you can just instantiate a NullAwareBeanUtilsBean and use it to copy your beans, for example:

BeanUtilsBean notNull=new NullAwareBeanUtilsBean();
notNull.copyProperties(dest, orig);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download