Why does accessing a private member of an outer class using reflection raise an IllegalAccessException?

Given the code example below, why is accessUsingReflectiontheAnswer.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" );
         // 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 );
   }
}
+4
source share
2 answers

"" - "", , ? ? ?

, , .

Java (JVM, ..) . , , .

, , / , .

, accessDirectly . , theAnswer.

(theAnswer) - , () .

, , (-) Java-, , , .

+2

public static void main( String[] args ) private int theAnswer = 42 , - accessDirectly 42 ( ), , object Class Class Outer, private int theAnswer = 42 ( ). java.lang.IllegalAccessException , field.setAccessible( true ).

example , public static class Inner.

0

All Articles