2

I am using the Apache Commons BeanUtils for copying some properties from a Source Bean to a Destination Bean. In this, I do NOT want to set null values in my destination bean which are coming from the source bean.

Like for example:

Person sourcePerson = new Person();
sourcePerson.setHomePhone("123");
sourcePerson.setOfficePhone(null);

Person destPerson = new Person();
destPerson.setOfficePhone("456");

BeanUtils.copyProperties(destPerson, sourcePerson);
System.out.println(destPerson.getOffcePhone());

//Here destPerson officePhone gets set to null

How do I avoid this? I tried even putting the below statement: BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);

which doesn't seem to help.

Any way we can exclude nulls in Apache Commons BeanUtils?

Ram Gaddam
  • 151
  • 1
  • 10
  • http://stackoverflow.com/questions/17417345/beanutils-copyproperties-api-to-ignore-null-and-specific-propertie – StanislavL May 05 '17 at 08:12
  • You can use PropertyUtils which will not try to convert the property...Otherwise you need to register the ConvertUtils.register for a default value... – VelNaga May 05 '17 at 08:18
  • I don't want any default value, I simply dont want to override existing values with null. I still didnt get how PropertyUtils excludes nulls. – Ram Gaddam May 05 '17 at 09:10
  • 1
    @StanislavL ignoreProperties option doesn't solve this problem, and neither did ConvertUtils, as stated in the question. – Ram Gaddam May 05 '17 at 09:12

3 Answers3

1

Apache Commons BeanUtils do not support this situation. So you should do this by your self:

public class BeanUtils {

    public static void copyPropertiesIgnoreNull(Object source, Object dest) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
        for(java.beans.PropertyDescriptor pd : pds) {
            if(!src.isReadableProperty(pd.getName()) || pd.getWriteMethod() == null){
                continue;
            }
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                continue;
            }
            BeanUtils.copyProperties(dest, pd.getName(), srcValue);
        }
    }
}
xierui
  • 1,047
  • 1
  • 9
  • 22
1

BeanUtils does not work when properties are nested such as contact.businessName.firstname where firstName is the string and others are user defined class.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Ash
  • 2,095
  • 1
  • 19
  • 17
0

Extend 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);
  }
}
BeanUtilsBean notNull = new NullAwareBeanUtilsBean();
notNull.copyProperties(target, source);

That should do it.

Nodoze
  • 680
  • 5
  • 4