如何用反射更改List中对象的信息?

时间:2017-06-19 06:48:45

标签: java reflection

我想从List字段中读取和操作信息。更具体地说,我想访问嵌套的List对象的inInterClasses和hashMappedInnerClasses的getter和setter。我几乎没有影响我的observeAndReflect方法中给出的对象。我不知道将来会传入哪一堂课。

public class ReflectMe {

private int id;
private long speed = 10;
private SimpleInnerClass simpleInnerClass;
private List<ListedInnerClass> listedInnerClasses;
private HashMap<Long, HashMappedInnerClass> hashMappedInnerClass;
// ... getter and setter
}

public class ListedInnerClass {

private long id;
private String foo = "bar";
// ... getter and setter
}

我填写了一些东西进行测试:

private void start() {

    // reflectionTest
    ReflectMe me = new ReflectMe();
    List<ListedInnerClass> listedInnerClasses = new ArrayList<ListedInnerClass>();
    ListedInnerClass aClass1 = new ListedInnerClass();
    ListedInnerClass aClass2 = new ListedInnerClass();
    aClass2.setFoo("bla");
    listedInnerClasses.add(aClass1);
    listedInnerClasses.add(aClass2);
    me.setListedInnerClasses(listedInnerClasses);
    try {
        observeAndReflect(me);
    } catch(IllegalAccessException e) {
        logger.error(e);
    }
}

然后我试图获得访问权限。我从List开始:

private void observeAndReflect(Object o) throws IllegalAccessException {

    for (Field field : o.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        Class<?> fieldType = field.getType();

        logger.info("# Type: " + fieldType.getName() + " getName: " + field.getName() + " getValue " + field.get(o));

        if (fieldType == List.class) {
            // here I would like to change information of the lists objects
            logger.info("## My List: " + field.get(o));
            observeAndReflect(field.get(o));
        }
    }
}

我的logoutput给了我一些信息:

  

INFO [main](Runner.java:136) - #Type:int getName:id getValue 0
  INFO [main](Runner.java:136) - #Type:long getName:speed getValue 10
  INFO [main](Runner.java:136) - #Type:application.SimpleInnerClass getName:simpleInnerClass getValue null
  INFO [main](Runner.java:136) - #Type:java.util.List getName:listedInnerClasses getValue [application.ListedInnerClass@7bc1a03d,application.ListedInnerClass@70b0b186]
   INFO [main](Runner.java:139) - ##我的列表:[application.ListedInnerClass@7bc1a03d,application.ListedInnerClass@70b0b186]
  INFO [main](Runner.java:136) - #Type:long getName:serialVersionUID getValue 8683452581122892189
  ...

但我无法访问我的列表中的信息。

据我所知,由于类型擦除,List中类型参数的信息会丢失。所以编译器确实知道有一个List,但是忘记了有的ListedInterInClass类的对象。我试图重新转换该对象但总是遇到同样的问题:无法访问getter和setter。

还有办法获取信息吗?

提前致谢!

1 个答案:

答案 0 :(得分:1)

根据你的程序逻辑,你需要传递的不是列表,而是列表的项目:

if (fieldType == List.class) {
    // here I would like to change information of the lists objects
    logger.info("## My List: " + field.get(o));
    List items = (List) field.get(o)
    for(Object item : items) {
        observeAndReflect(item);
    }
}