java 在java中通过反射设置对象字段的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12857425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set value for object field by reflection in java
提问by R4j
First, I have an object like that:
首先,我有一个这样的对象:
public class Entity {
public int data1;
public String data2;
public float data3;
public SubEntity data4;
}
public class SubEntity{
public int id;
public SubEntity(int id){
tis.id = id;
}
}
And a HashMap:
和一个哈希映射:
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("data1", 1);
map.put("data2", "name");
map.put("data3", 1.7);
map.put("data4", new SubEntity(11));
I need the right way to set value for all field of entity dynamic by use reflect from hashmap. Something like this:
我需要正确的方法通过使用reflect from hashmap为实体动态的所有字段设置值。像这样的东西:
for (Field f : entity.getClass().getDeclaredFields()) {
String name = f.getName();
Object obj = map.get("name");
// Need set value field base on its name and type.
}
How can I achieve that? Assume I have many sub classes in entity.
我怎样才能做到这一点?假设我在实体中有很多子类。
回答by Brian Agnew
If you want to go the reflection route, then why not use Field.set(Object, Object)and its more type-safe siblings (see doc)
如果你想走反射路线,那么为什么不使用Field.set(Object, Object)及其更多类型安全的兄弟(参见文档)
f.set(myEntity, obj);
Note. You may need to make the field accessible first if it's private/protected.
笔记。如果该字段是私有/受保护的,您可能需要首先使该字段可访问。
However if you can I would perhaps delegate to the object and it could populate itself via the map e.g.
但是,如果可以的话,我可能会委托给对象,它可以通过地图填充自己,例如
myEntity.populateFromMap(myMap);
and do the hard(ish) work within your class.
并在班级内完成艰苦的(ish)工作。