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;
}