Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Merge Java Objects Dynamically

Tags:

java

dynamic

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?

like image 539
metdos Avatar asked Oct 06 '11 11:10

metdos


People also ask

How do you combine properties of two objects?

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.

How can I merge properties of two JavaScript objects dynamically?

The two most common ways of doing this are: Using the spread operator ( ... ) Using the Object. assign() method.


1 Answers

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.

like image 196
Erhan Bagdemir Avatar answered Oct 13 '22 21:10

Erhan Bagdemir