在BeanUtils.copyProperties(Object source, Object target, String... ignoreProperties)中,可以传入属性为null的属性名来提高效率。下面我们来写个工具类获取实体类为null的属性数组:
//忽略null值
public static String[] getNullpropertyName(Object source) {
//使用BeanWrapper封装传入的类
BeanWrapper beanWrapper = new BeanWrapperImpl(source);
//获取bean类所有的属性定义
PropertyDescriptor[] pds = beanWrapper.getPropertyDescriptor();
Set<String> emptyNames = new HashSet<>();
for(PropertyDescriptor pd : pds) {
//获取属性值
Object beanValue = beanWrapper.getPropertyValue(pd.getName());
if(beanValue == null)
empryNames.add(pd.getName());
}
String [] results = new String[emptyNames.size()];
return emptyNames.toArray(results);
}