简体   繁体   中英

Set value for object field by reflection in java

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:

    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.

If you want to go the reflection route, then why not use Field.set(Object, Object) and its more type-safe siblings (see doc)

f.set(myEntity, obj);

Note. You may need to make the field accessibl e 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 eg

myEntity.populateFromMap(myMap);

and do the hard(ish) work within your class.

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