BeanUtils的常用方法
常用BeanUtils类由两个包提供 org.apache.commons.beanutils.BeanUtils、org.springframework.beans.BeanUtils,我们使用的是后者即Spring提供的,如果使用Apache要注意拷贝对象参数位置
copy方法
BeanUtils.copyProperties(source, target);
忽略某些字段拷贝
#忽略表字段id,name的copy
BeanUtils.copyProperties(source, target, "id", "name");
忽略空值(或特定字符)拷贝
常用于拷贝DTO对象属性到实体类,实体类中部分字段有设置默认值,即可以不将DTO中的空值拷贝过来,保持原有默认值(原理就是将源目标中不需要copy的字段收集起来,然后如上过滤即可)
demo代码如下:
1.copy方式
BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
2.收集不需要copy字段方法
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) {//特定字符写在此处过滤,收集不需要copy的字段列表。此处过滤null为例
emptyNames.add(pd.getName());
}
}
String[] result = new String[emptyNames.size()];
return (String[]) emptyNames.toArray(result);
}