아래의 코드 예에서 accessUsingReflection
->theAnswer.get(outer)
은 IllegalAccessException
인데 반해 accessDirectly
은 42를 올바르게 인쇄합니까?리플렉션을 사용하여 외부 클래스의 private 멤버에 액세스하는 이유는 무엇입니까? IllegalAccessException?
Exception in thread "main" java.lang.IllegalAccessException: Class Outer$Inner can not access a member of class Outer with modifiers "private"
는 this SO answer에 따르면, 나는 "그것을 액세스 할 수있는 클래스에서 (...)"액세스가 발생합니까대로 일을 기대.
import java.lang.reflect.Field;
public class Outer
{
private int theAnswer = 42;
public static class Inner
{
public void accessDirectly(Outer outer)
{
System.out.println(outer.theAnswer);
}
public void accessUsingReflection(Outer outer) throws NoSuchFieldException,
SecurityException,
IllegalArgumentException,
IllegalAccessException
{
Field theAnswer = Outer.class.getDeclaredField("theAnswer");
// Of course, uncommenting the next line will make the access using reflection work.
// field.setAccessible(true);
System.out.println(theAnswer.get(outer));
}
}
public static void main(String[] args) throws NoSuchFieldException,
SecurityException,
IllegalArgumentException,
IllegalAccessException
{
Outer outer = new Outer();
Inner inner = new Inner();
inner.accessDirectly(outer);
inner.accessUsingReflection(outer);
}
}
맞습니다. 저는 그 질문에 기술적 측면과 개념적 측면이있을 수 있다는 사실을 알고있었습니다. 그러나 당신의 포괄적 인 대답은 정확하게 내가 한 것입니다. –