給出下面的代碼示例,爲什麼accessUsingReflection
- >theAnswer.get(outer)
會拋出IllegalAccessException
而accessDirectly
只打印42?爲什麼使用反射拋出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);
}
}
你是對的 - 我意識到這個問題可能存在技術和概念方面的事實。但你的全面答案正是我所追求的。 –