在java中通过反射设置对象字段的值 [英] Set value for object field by reflection in java

查看:33
本文介绍了在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;
    }
}

还有一个 HashMap:

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.

推荐答案

如果你想走反射路线,那为什么不使用 Field.set(Object, Object) 及其更多类型安全的兄弟(见文档)

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);

注意.您可能需要 使如果字段是私有/受保护的,则首先访问该字段.

但是,如果可以的话,我可能会委托给对象,它可以通过地图填充自己,例如

However if you can I would perhaps delegate to the object and it could populate itself via the map e.g.

myEntity.populateFromMap(myMap);

并在班级中完成艰苦的(ish)工作.

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

这篇关于在java中通过反射设置对象字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆