1

I'm trying to find a way to merge different instances of the same object. So that Object2 overwrites Object1 but where Object2 has null values leave the Object1 values as they are. Imagine that there is an Object1 that contains the below.

------
public class Object1 {
    private List<A> listOfTwoStrings;
    private List<B> classBContainsTwoStrings;
}
------
public class A {
    private String name;
    private String age;
}
------
public class B {
    private String name;
    private List<Attribute> attributes;
}
------
public class Attribute {
    private String attributeName;
    private String attributeValue;
}
------

I believe the testing that I've been doing is only copying over one level deep so not quite there yet.

public Object1 mergeObjects(Object1 object1, Object1 object2) throws
        IllegalAccessException, NoSuchFieldException {
    for (Field field : object2.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        String name = field.getName();
        Object value = field.get(object2);

        //If it is a non null value copy to destination
        if (null != value) {

            Field destField = object1.getClass().getDeclaredField(name);
            destField.setAccessible(true);

            destField.set(object1, value);
        }
    }
    return object1;
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Stephen
  • 11
  • 2

1 Answers1

0

you could write a method in the class Object1 which does the merge

public Object1 mergeObject( Object1 object2){
    if(object2.listOfTwoStrings != null){
       this.listOfTwoStrings = object2.listOfTwoStrings
    }
    ....
}

and then call it by object_1.merge(object_2).

I would not change the accessibility of a variable. Private fields should stay private, for security reasons, but the management which value are stored in this variable can be done by the class.