0
나는 리플렉션을 사용하여 개인 중첩 필드 (본질적으로 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'에 저장된 인스턴스로 설정하려고합니다. –