BeanUtils.copyProperties参数为null的时候不复制
程序员文章站
2024-01-04 11:23:34
...
BeanUtils.copyProperties()属性为null也会被复制,所以自己定义一个属性为null不复制的方法
public static String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(java.beans.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);
}
public static void copyPropertiesIgnoreNull(Object src, Object target){
BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}
T t1 = mongoRepository.findById((PK) field.get(t)).get();
copyPropertiesIgnoreNull(t,t1);