- java bean的拷贝一般采用两种办法
1.Spring里面的方法, org.springframework.beans.BeanUtils.copyProperties
2.Apache里面的方法,org.apache.commons.beanutils.BeanUtils.copyProperties
但是有需要注意的地方,Spring中BeanUtils.copyProperties(A,B)是将A赋值给B
Apache中BeanUtils.copyProperties(A,B)是将B赋值给A.
对于拷贝时空属性的处理,下面是我的方法,采用了Spring的方法
public static Object copyBeanIgnoreNullProperties(Object sourceObj, Object destObj) {
if (sourceObj == null || destObj == null) {
log.error("copyBean参数缺失!原参数为空?{},目标参数为空?{}", sourceObj == null, destObj == null);
return destObj;
}
try {
BeanUtils.copyProperties(sourceObj,destObj,getNoValuePropertyNames(sourceObj));
} catch (Exception e) {
e.printStackTrace();
}
return destObj;
}
private static String[] getNoValuePropertyNames (Object source) {
Assert.notNull(source, "传递的参数对象不能为空");
final BeanWrapper beanWrapper = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = beanWrapper.getPropertyDescriptors();
Set<String> noValuePropertySet = new HashSet<>();
Arrays.stream(pds).forEach(pd -> {
Object propertyValue = beanWrapper.getPropertyValue(pd.getName());
if (StringUtils.isEmpty(propertyValue)) {
noValuePropertySet.add(pd.getName());
} else {
if (Iterable.class.isAssignableFrom(propertyValue.getClass())) {
Iterable iterable = (Iterable) propertyValue;
Iterator iterator = iterable.iterator();
if (!iterator.hasNext()) noValuePropertySet.add(pd.getName());
}
if (Map.class.isAssignableFrom(propertyValue.getClass())) {
Map map = (Map) propertyValue;
if (map.isEmpty()) noValuePropertySet.add(pd.getName());
}
}
});
String[] result = new String[noValuePropertySet.size()];
return noValuePropertySet.toArray(result);
}