最近在寫一個小玩意的時候,需要在兩個對象之間拷貝屬性
使用的是
BeanUtils.copyProperties
可是,有一個問題
就是當src對象的鍵值爲Null時
就會把target對象的對應鍵值覆蓋成空了
這不科學
所以找了下面的這個方式來解決
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));
}