[英]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 它将动态遍历MyClass上的所有成员并在每个成员上运行它
if(object1.elem != object2.elem && object2.elem!=null)
object1.elem=object2.elem;
Is such a mechanism exist in Java? 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: 比Reflection更有效的选项是将字段存储在地图中:
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中执行此操作。
是的,它是可能的,它被称为反射 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.