Given the code example below, why is accessUsingReflection→ theAnswer.get( outer )throwing out IllegalAccessExceptionwhile accessDirectlytyping 42 is just fine?
Exception in thread "main" java.lang.IllegalAccessException: Class Outer$Inner can not access a member of class Outer with modifiers "private"
According to this SO answer , I expect it to work, since the access is really "(...) from the class that is allowed to access it."
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" );
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 );
}
}
source
share