相信很多人用BeanUtils.copyProperties复制属性都遇到过这种情况,我直接长话短说节约大家时间。
首先创建一个BeanCopyUtils类,然后复制下面的代码
/**
* copy bean 过滤掉空字段
* @param src
* @param target
*/
public static void copyPropertiesIgnoreNull(Object src, Object target){
BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}
private static 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);
}
然后直接调用 copyPropertiesIgnoreNull()方法即可,这样复制属性就再也不会报空指针异常了