我有两个相同类型的对象。
Class A {
String a;
List b;
int c;
}
A obj1 = new A();
A obj2 = new A();
obj1 => {a = "hello"; b = null; c = 10}
obj2 => {a = null; b = new ArrayList(); c = default value}
能否请您告诉我将这些对象组合成单个对象的最佳方法是什么?
obj3 = {a = "hello"; b = (same arraylist from obj2); c = 10}
最佳答案
只要您拥有带有自己的 getter 和 setter 的 POJO,它就可以工作。该方法使用来自 update 的非空值更新 obj。它在 obj 上调用 setParameter(),在 update 上返回 getParameter() 的返回值:
public void merge(Object obj, Object update){
if(!obj.getClass().isAssignableFrom(update.getClass())){
return;
}
Method[] methods = obj.getClass().getMethods();
for(Method fromMethod: methods){
if(fromMethod.getDeclaringClass().equals(obj.getClass())
&& fromMethod.getName().startsWith("get")){
String fromName = fromMethod.getName();
String toName = fromName.replace("get", "set");
try {
Method toMetod = obj.getClass().getMethod(toName, fromMethod.getReturnType());
Object value = fromMethod.invoke(update, (Object[])null);
if(value != null){
toMetod.invoke(obj, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
关于java - 在 Java 中合并两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6591665/