【发布时间】:2016-10-18 14:00:44
【问题描述】:
我正在尝试使用反射设置一个私有嵌套字段(本质上是 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
【问题讨论】:
-
f2.set(f.get(foo), "hello world");?您正在尝试将其设置在存储在Foo.bar中的实例上,而不是类上。
标签: java reflection