BeanUtils属性复制的用法

1.对于类型为Boolean/Short/Integer/Float/Double的属性,它会转换为0:

需求1:如果B中某字段有值(不为null),则该字段不复制;也就是B中该字段没值时,才进行复制,适合于对B进行补充值的情况。 import org.apache.commons.beanutils.BeanUtilsBean;

import org.apache.commons.beanutils.PropertyUtils;

public class CopyWhenNullBeanUtilsBean extends BeanUtilsBean{

@Override

public void copyProperty(Object bean, String name, Object value)

throws IllegalAccessException, InvocationTargetException {

try {

Object destValue = PropertyUtils.getSimpleProperty(bean, name);

if (destValue == null) {

super.copyProperty(bean, name, value);

}

} catch (NoSuchMethodException e) {

throw new RuntimeException(e);

}

}

}

import org.apache.commons.beanutils.BeanUtilsBean;

public class CopyFromNotNullBeanUtilsBean extends BeanUtilsBean {

@Override

public void copyProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException {

if (value == null) {

return;

}

super.copyProperty(bean, name, value);

}

}

特殊用法:

经验分享 程序员 微信小程序 职场和发展