Helper in order to copy non null properties from object to another

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 :

package foo.bar.copy;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtilsBean;

public class NullAwareBeanUtilsBean extends BeanUtilsBean{

    @Override
    public void copyProperty(Object dest, String name, Object value)
            throws IllegalAccessException, InvocationTargetException {
        if(value==null)return;
        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);

Leave a Comment