作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个 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")
我使用的是 Java 8 和 Spring boot 1.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);
}
}
}
}
}
}
}
关于java - 如何将两个java对象合并为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41602260/
我是一名优秀的程序员,十分优秀!