常用于拷贝DTO对象属性到实体类,实体类中部分字段有设置默认值,即可以不将DTO中的空值拷贝过来,保持原有默认值
BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
可以将下面的方法做成一个Util使用, source会忽略null值复制到target中
public static String[] getNullPropertyNames(Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set emptyNames = new HashSet();
for(java.beans.PropertyDescriptor pd : pds) {
//check if value of this property is null then add it to the collection
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) {
emptyNames.add(pd.getName());
}
}
String[] result = new String[emptyNames.size()];
return (String[]) emptyNames.toArray(result);
}