简体   繁体   中英

How to Merge 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
.....

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?

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.

An option that is more efficient than Reflection would be to store the fields in a 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 would make the merge more efficient but would make general field access less efficient.

您可以使用反射自己编写这样的方法(从Class.getFields()开始),但是没有工具在标准API中执行此操作。

是的,它是可能的,它被称为反射

There is nothing built in. However you might want to have a look at Dozer . Maybe with some tweaking it will be capable of doing this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM