如何将两个java对象合并为一个?
我有两个java对象实例,我想将它们的值合并到一个实例中。当两个对象实例都包含字段值时,我需要选择哪个对象实例优先。我也不想用空值覆盖值 例如:如何将两个java对象合并为一个?,java,spring,reflection,Java,Spring,Reflection,我有两个java对象实例,我想将它们的值合并到一个实例中。当两个对象实例都包含字段值时,我需要选择哪个对象实例优先。我也不想用空值覆盖值 例如: MyClass source = new MyClass("source", 1, null); MyClass target = new MyClass("target", 2, "b"); merge(source, target); // target now has values ("source", 1, "b") 我正在使用Java8和S
MyClass source = new MyClass("source", 1, null);
MyClass target = new MyClass("target", 2, "b");
merge(source, target);
// target now has values ("source", 1, "b")
我正在使用Java8和SpringBoot1.4.1
编辑:看起来我不清楚,所以我添加了更多描述。此外,我已经提供了自己的解决方案。其目的是在其他人有相同问题时提供此解决方案。我在这里发现其他线程也在问同样或类似的问题,但它们没有我在下面发布的完整解决方案。Spring的Spring beans库有一个
org.springframework.beans.BeanUtils
类,它提供了一个copyProperties
方法将源对象实例复制到目标对象实例中。但是,它仅对对象的第一级字段执行此操作。下面是我的解决方案,它基于BeanUtils.copyProperties
,递归地为每个子对象执行复制,包括集合和映射
package my.utility;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* Created by cdebergh on 1/6/17.
*/
public class BeanUtils extends org.springframework.beans.BeanUtils {
/**
* Copy the not null property values of the given source bean into the target bean.
* <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.
* @param source the source bean
* @param target the target bean
* @throws BeansException if the copying failed
* @see BeanWrapper
*/
public static void copyPropertiesNotNull(Object source, Object target) throws BeansException {
copyPropertiesNotNull(source, target, null, (String[]) null);
}
private static void setAccessible(Method method) {
if (!Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
method.setAccessible(true);
}
}
/**
* Copy the not null property values of the given source bean into the given target bean.
* <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.
* @param source the source bean
* @param target the target bean
* @param editable the class (or interface) to restrict property setting to
* @param ignoreProperties array of property names to ignore
* @throws BeansException if the copying failed
* @see BeanWrapper
*/
private static void copyPropertiesNotNull(Object source, Object target, Class<?> editable, String... ignoreProperties)
throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
if (editable != null) {
if (!editable.isInstance(target)) {
throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
"] not assignable to Editable class [" + editable.getName() + "]");
}
actualEditable = editable;
}
PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
for (PropertyDescriptor targetPropertyDescriptor : targetPds) {
Method targetWriteMethod = targetPropertyDescriptor.getWriteMethod();
if (targetWriteMethod != null
&& (ignoreList == null || !ignoreList.contains(targetPropertyDescriptor.getName()))) {
PropertyDescriptor sourcePropertyDescriptor =
getPropertyDescriptor(source.getClass(), targetPropertyDescriptor.getName());
if (sourcePropertyDescriptor != null) {
Method sourceReadMethod = sourcePropertyDescriptor.getReadMethod();
if (sourceReadMethod != null &&
ClassUtils.isAssignable(
targetWriteMethod.getParameterTypes()[0], sourceReadMethod.getReturnType())) {
try {
Method targetReadMethod = targetPropertyDescriptor.getReadMethod();
setAccessible(sourceReadMethod);
setAccessible(targetWriteMethod);
Object sourceValue = sourceReadMethod.invoke(source);
if (sourceValue != null && targetReadMethod != null) {
setAccessible(targetReadMethod);
Object targetValue = targetReadMethod.invoke(target);
if (targetValue == null) {
targetWriteMethod.invoke(target, sourceValue);
} else if(targetValue instanceof Collection<?>) {
((Collection) targetValue).addAll((Collection) sourceValue);
} else if (targetValue instanceof Map<?,?>) {
((Map) targetValue).putAll((Map) sourceValue);
} else {
copyPropertiesNotNull(sourceValue, targetValue, editable, ignoreProperties);
}
}
}
catch (Throwable ex) {
throw new FatalBeanException(
"Could not copy property '" + targetPropertyDescriptor.getName() +
"' from source to target", ex);
}
}
}
}
}
}
}
包my.utility;
导入org.springframework.beans.BeanWrapper;
导入org.springframework.beans.BeansException;
导入org.springframework.beans.FatalBeanException;
导入org.springframework.util.Assert;
导入org.springframework.util.ClassUtils;
导入java.beans.PropertyDescriptor;
导入java.lang.reflect.Method;
导入java.lang.reflect.Modifier;
导入java.util.array;
导入java.util.Collection;
导入java.util.List;
导入java.util.Map;
/**
*cdebergh于2017年1月6日创建。
*/
公共类BeanUtils扩展org.springframework.beans.BeanUtils{
/**
*将给定源bean的NOTNULL属性值复制到目标bean中。
*注意:源类和目标类不必匹配,甚至不必派生
*只要属性匹配,就可以相互访问
*源bean公开,但目标bean不公开,将被忽略。
*这只是一种方便的方法。对于更复杂的传输需求,
*考虑使用完整的BeNeWrPress。
*@param source源bean
*@param target目标bean
*如果复制失败,@将引发BeansException
*@see BeanWrapper
*/
公共静态void copyPropertiesNotNull(对象源、对象目标)引发BeansException{
copyPropertiesNotNull(源、目标、null,(字符串[])null);
}
私有静态void setAccessible(方法){
如果(!Modifier.isPublic(method.getDeclaringClass().getModifiers())){
方法setAccessible(true);
}
}
/**
*将给定源bean的NOTNULL属性值复制到给定目标bean中。
*注意:源类和目标类不必匹配,甚至不必派生
*只要属性匹配,就可以相互访问
*源bean公开,但目标bean不公开,将被忽略。
*@param source源bean
*@param target目标bean
*@param可编辑类(或接口),以将属性设置限制为
*@param ignoreProperties要忽略的属性名称数组
*如果复制失败,@将引发BeansException
*@see BeanWrapper
*/
私有静态void copyPropertiesNotNull(对象源、对象目标、类可编辑、字符串…ignoreProperties)
抛出BeansException{
Assert.notNull(source,“source不能为null”);
Assert.notNull(target,“target不能为null”);
类actualEditable=target.getClass();
如果(可编辑!=null){
如果(!editable.isInstance(目标)){
抛出新的IllegalArgumentException(“目标类[”+Target.getClass().getName())+
“]不可分配给可编辑类[“+Editable.getName()+”]”;
}
actualEditable=可编辑;
}
PropertyDescriptor[]targetPds=getPropertyDescriptors(actualEditable);
List ignoreList=(ignoreProperties!=null?数组.asList(ignoreProperties):null);
对于(PropertyDescriptor targetPropertyDescriptor:targetPds){
方法targetWriteMethod=targetPropertyDescriptor.getWriteMethod();
if(targetWriteMethod!=null
&&(ignoreList==null | |!ignoreList.contains(targetPropertyDescriptor.getName())){
PropertyDescriptor源PropertyDescriptor=
getPropertyDescriptor(source.getClass(),targetPropertyDescriptor.getName());
if(sourcePropertyDescriptor!=null){
方法sourceReadMethod=sourcePropertyDescriptor.getReadMethod();
if(sourceReadMethod!=null&&
ClassUtils.isAssignable(
targetWriteMethod.getParameterTypes()[0],sourceReadMethod.getReturnType()){
试一试{
方法targetReadMethod=targetPropertyDescriptor.getReadMethod();
setAccessible(sourceReadMethod);
setAccessible(targetWriteMethod);
Object sourceValue=sourceReadMethod.invoke(source);
if(sourceValue!=null&&targetReadMethod!=null){
setAccessible(targetReadMethod);
对象targetValue=targetReadMethod.invoke(目标);
如果(targetValue==null){
targetWriteMethod.invoke(目标,sourceValue);
}else if(集合的targetValue实例){
((集合)targetValue).addAll((集合)sourceValue);
}else if(映射的targetValue实例){