2016-10-18 3 views
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 
+1

'f2.set (f.get (foo), "hello world");'? 당신은 클래스가 아닌'Foo.bar'에 저장된 인스턴스로 설정하려고합니다. –

답변

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

문제는 fField 아닌 Bar 것입니다.

foo으로 시작하고 값 을 추출한 다음 해당 개체 참조를 사용해야합니다. 예 : 이 같은 것

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"); 
관련 문제