BeanUtils过滤掉空属性
时间: 2023-10-16 20:08:27 浏览: 70
BeanUtils不提供过滤空属性的方法,但可以通过编写自定义的BeanUtils.copyProperties方法来实现。
以下是一个示例:
```
public static void copyPropertiesIgnoreNull(Object source, Object target) {
BeanUtilsBean beanUtils = new BeanUtilsBean(new ConvertUtils() {
@Override
public Object convert(String value, Class clazz) {
if (clazz.isEnum()) {
return Enum.valueOf(clazz, value.toString());
} else {
return super.convert(value, clazz);
}
}
});
PropertyUtilsBean propertyUtils = beanUtils.getPropertyUtils();
PropertyDescriptor[] descriptors = propertyUtils.getPropertyDescriptors(target);
List<String> ignoreProperties = new ArrayList<>();
for (PropertyDescriptor propertyDescriptor : descriptors) {
String name = propertyDescriptor.getName();
Object value;
try {
value = propertyUtils.getSimpleProperty(target, name);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (value == null) {
ignoreProperties.add(name);
}
}
ignoreProperties.add("class");
String[] ignoreArray = ignoreProperties.toArray(new String[ignoreProperties.size()]);
try {
BeanUtils.copyProperties(target, source, ignoreArray);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
```
该方法会将目标对象中值为null的属性过滤掉,从而避免将null值赋给目标对象的属性。
阅读全文