java反射嵌套对象设置私有字段

时间:2016-10-18 14:00:44

标签: java reflection

我尝试使用反射设置私有嵌套字段(实际上是Bar.name),但我得到的异常我无法弄清楚。

import java.lang.reflect.Field;

public class Test {
public static void main(String[] args) throws Exception {
    Foo foo = new Foo();
    Field f = foo.getClass().getDeclaredField("bar");
    Field f2 = f.getType().getDeclaredField("name");
    f2.setAccessible(true);
    f2.set(f, "hello world"); // <-- error here!! what should the first parameter be?
}

public static class Foo {
    private Bar bar;
}

public class Bar {
    private String name = "test"; // <-- trying to change this value via reflection
}

}

我得到的例外是:

Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.lang.String field com.lmco.f35.decoder.Test$Bar.name to java.lang.reflect.Field

1 个答案:

答案 0 :(得分:2)

f2.set(f, "hello world");

问题是fField而不是Bar

您需要从foo开始,提取foo.bar,然后使用该对象引用;例如像这样的东西

Foo foo = new Foo();
Field f = foo.getClass().getDeclaredField("bar");
f.setAccessible(true);
Bar bar = (Bar) f.get(foo);
// or 'Object bar = f.get(foo);'
Field f2 = f.getType().getDeclaredField("name");
f2.setAccessible(true);
f2.set(bar, "hello world");