public class MyClass{
public String elem1;
public int elem2;
public MyType elem3;
.................
}
MyClass object1=new MyClass();
MyClass object2=new MyClass();
object1.elem1=...
object1.elem2=...
...
object2.elem1=...
object2.elem2=null
.....
What I want is something like
object1.merge(object2);
where it will dynamically traverse all members on MyClass and run this on every member
if(object1.elem != object2.elem && object2.elem!=null)
object1.elem=object2.elem;
Is such a mechanism exist in Java?
In the above example, two objects are merged into one using the Object. assign() method. The Object. assign() method returns an object by copying the values of all enumerable properties from one or more source objects.
The two most common ways of doing this are: Using the spread operator ( ... ) Using the Object. assign() method.
use reflection. go over fields of class. Psuedo:
Field[] fields = aClass.getFields();
for (Field field : fields) {
// get value
Object value = field.get(objectInstance);
// check the values are different, then update
field.set(objetInstance, value);
}
and match the values. if they differ, then update the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With