Java对象合并,org.springframework.beans.BeanUtils

问题场景:

  在实际开发中可能存在将两个对象合并为一个对象的需求,传统的方法当然是一个个get和set但是这样的代码很不整洁,我们可以基于反射去实现这一需求。所幸apache和spring都提供的有该方法。

Spring:

public static void copyProperties(Object source, Object target) throws BeansException {
		copyProperties(source, target, null, (String[]) null);
}

该方法以target对象为主体,将source对象的值赋给target。默认是直接覆盖相同字段的全部值。

实际需求中只需要复制部分属性,我们可以使用该方法,忽略部分字段

public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
		copyProperties(source, target, null, ignoreProperties);
	}

如:忽略已经有值的字段,

public static String[] getValuePropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set emptyNames = new HashSet<>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (null != srcValue) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

该方法为获取所有有值的方法。当然也可以直接指定具体字段。

 

 

apache:

该方法为将orig方法的值赋给dest,但是不提供忽略覆盖的方法

public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException {
        BeanUtilsBean.getInstance().copyProperties(dest, orig);
    }

 

你可能感兴趣的:(JAVA,spring)