版权声明:转载请注明出处 https://blog.csdn.net/YoshinoNanjo/article/details/82735826
参考文章:https://segmentfault.com/a/1190000002739424
今天在写项目接口的时候需要把DTO类中的值更新到Bean中,发现DTO类中有一个集合属性children的大小是0,而我从数据库中查询出来的Bean,children属性是有值的。使用的是Spring提供的复制方法BeanUtils.copyProperties(Object source, Object target, String... ignoreProperties),第三个参数用的方法是上文链接的方法。这个方法在我这个需求里有一个问题,DTO类中的值覆盖更新到Bean的话,将会覆盖Bean中的集合属性变为empty,这可就出大事了……因此我扩展了这个方法,需要忽略null值和empty集合,这样DTO类覆盖更新Bean就正常了。
public static String[] getNoValuePropertyNames (Object source) {
// assert CommonUtils.isNotNull(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 (CommonUtils.isNull(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);
}