在 Java 中合并两个对象

新手上路,请多包涵

我有两个相同类型的对象。

 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}

原文由 Ganesh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 687
2 个回答

也许像

class A {
    String a;
    List<..> b;
    int c;

    public void merge(A other) {
        this.a = other.a == null ? this.a : other.a;
        this.b.addAll(other.b);
        this.c = other.c == 0 ? this.c : other.c;
    }
}

A a1 = new A();
A a2 = new A();

a1.a = "a prop";
a2.c = 34;

a1.merge(a2);

A.merge 可能会返回一个新的 A 对象而不是修改当前对象。

原文由 Crozin 发布,翻译遵循 CC BY-SA 3.0 许可协议

只要您拥有带有自己的 getter 和 setter 的 POJO,这就可以工作。该方法使用 update 中的非空值 更新 obj 。它在 obj 上调用 setParameter() 并在 更新 时返回 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();
            }
        }
    }
}

原文由 Alex Martín Jiménez 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题