BeanUtils的忽略字段工具类
使用BeanUtils.copyProperties的时候有些字段为null,但是仍然把目标对象的对应value给复制成了null,解决办法忽略那些为null的字段
方案1,指定那些需要忽略的字段
这里网上找了一通,都是大致的思路
利用copyProperties(Object source, Object target, String... ignoreProperties)
这个方法,把需要忽略的字段传入进去
附上获取对应需要的属性名的数组的方法
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.beans.PropertyDescriptor;
import java.util.*;
public String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
在使用的时候把需要忽略的字段传入进去就ok了