主要的解决方法是:BeanUtils工具类中有一个方法可以将一个对象属性的值拷贝到另一个对象对应同名属性中,且可以指定忽略的属性。
/** * Copy the property values of the given source bean into the given target bean, * ignoring the given "ignoreProperties". * <p>Note: The source and target classes do not have to match or even be derived * from each other, as long as the properties match. Any bean properties that the * source bean exposes but the target bean does not will silently be ignored. * <p>This is just a convenience method. For more complex transfer needs, * consider using a full BeanWrapper. 这是告诉我们可以使用BeanWrapper * @param source the source bean 资源对象,它的属性值会被拷到目标对象 * @param target the target bean 目标对象 * @param ignoreProperties array of property names to ignore 忽略拷贝的属性的属性名数组 * @throws BeansException if the copying failed * @see BeanWrapper */ public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException { copyProperties(source, target, null, ignoreProperties); }知道有这么一个方法,那就好办了,那现在我们要做的就是将一个对象中属性值为null的属性找出来。
下面是自己写一个工具类,获取null的属性集合
public class BeanWrapperUtil { /** * 获取对象中属性值为null的属性名集合 * @param object * @return */ public static String[] getNullFieldNames(Object object){ //使用beanwrapper操作对象 final BeanWrapperImpl beanWrapper = new BeanWrapperImpl(object); //获取对象属性详细信息的集合 PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors(); //声明一个set集合用来保存空属性值的属性名 Set<String> emptyNames=new HashSet<String>(); //遍历所有属性 for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { //获取属性名 String name = propertyDescriptor.getName(); //通过属性名获取属性值 Object value = beanWrapper.getPropertyValue(name); //值为null,就加入set集合中 if (value==null){ emptyNames.add(name); } } //set集合转化为string数组 String[] result = emptyNames.toArray(new String[0]); return result; } }