Merging two objects in Java

前端 未结 8 806
离开以前
离开以前 2020-12-15 23:25

I have two objects of same type.

Class A {
  String a;
  List b;
  int c;
}

A obj1 = new A();
A obj2 = new A();

obj1 => {a = \"hello\"; b = null; c = 10         


        
8条回答
  •  没有蜡笔的小新
    2020-12-16 00:10

    There is a dynamic solution to merge any two objects which require Reflection and Recursion.

    public  T merge(T local, T remote, ArrayList listOfClass)
            throws IllegalAccessException, InstantiationException {
        Class clazz = local.getClass();
        Object merged = clazz.newInstance();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            Object localValue = field.get(local);
            Object remoteValue = field.get(remote);
            if (localValue != null) {
                if (listOfClass.contains(localValue.getClass().getSimpleName())) {
                    field.set(merged, this.merge(localValue, remoteValue, listOfClass));
                } else {
                    field.set(merged, (remoteValue != null) ? remoteValue : localValue);
                }
            } else if (remoteValue != null) {
                field.set(merged, remoteValue);
            }
        }
        return (T) merged;
    }
    

    Variable Description:

    • local: The object on to which the other will be merged
    • remote: The object which will be merged to the local object
    • listOfClass: The ArrayList of custom classes in the given object

    The function returns a merged object which is good to go.

    Kudos! :)

提交回复
热议问题