How to combine Java objects dynamically

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
.....

I want something like

object1.merge(object2);

where it will dynamically move across all MyClass members and run them on each member

if(object1.elem != object2.elem && object2.elem!=null)
 object1.elem=object2.elem;

Is such a mechanism in Java?

+5
source share
5 answers

use reflection. navigate the class fields. Pseudo Users:

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 are different, then update the value.

+8
source

An option that is more effective than Reflection is to save the fields on the map:

Map<String, Object> fields;

void merge(MyClass other){
    for (String fieldName : fields.keys()){
        Object thisValue = this.fields.get(key);
        Object otherValue = other.fields.get(key);
        if (thisValue != otherValue && otherValue != null){

                this.fields.put(fieldName, otherValue);
        }
    }
}

This will make merging more efficient, but make sharing fields less efficient.

+2
source

, ( Class.getFields()), , API.

+1

Yes, this is possible and is called Reflection .

0
source

There is nothing built in. However, you can watch Dozer . Perhaps with some tweaking, he will be able to do this.

You can also do this with reflection (which is what Dozer does).

0
source

All Articles