假设是从A复制到B:
需求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);
}
}
}
需求2:如果A中某字段没值(为null),则该字段不复制,也就是不要把null复制到B当中。
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);
}
}