title: Class can't access its own protected member variable using reflection from different package
body: <p>I have  three classes: one base class <code>A</code> and two classes <code>B</code> and <code>C</code> that both extend <code>A</code>. <code>A</code> and <code>B</code> are in the same package and <code>C</code> is in a different package.</p>
  
  <p>Both, <code>B</code> and <code>C</code> have a protected member variable. <code>A</code> has a method (lets call it <code>reflect</code>) that uses reflection and a string input to accesses a field with this name of a subclass via the <code>this</code> pointer.</p>
  
  <p>Calling <code>reflect</code> from a <code>B</code> object is fine, but calling it from a <code>C</code> object results in an IllegalAccessException. I can not understand this exception, because this means that <code>C</code> has no access rights to access its own member variable. Why doesn't java allow this reflection?</p>
  
  <p>Here is a MWE to clarify what I mean:</p>
  
  <p>In <code>parent/A.java</code>:</p>
  
  <pre><code>package Parent;
  public abstract class A {
      public Object reflect(String parameter) throws NoSuchFieldException, IllegalAccessException{
          Class cl = getClass();
          return cl.getDeclaredField(parameter).get(this);
      }
  }
  </code></pre>
  
  <p>In <code>parent/B.java</code>:</p>
  
  <pre><code>package Parent;
  public class B extends A{
      protected Integer b;
      public B(Integer b){
          this.b = b;
      }
  }
  </code></pre>
  
  <p>In <code>parent/child/C.java</code>:</p>
  
  <pre><code>package Parent.Child;
  import Parent.A;
  public class C extends A{
      protected Integer c;
      public C(Integer c){
          this.c = c;
      }
  }
  </code></pre>
  
  <p>and a small main:</p>
  
  <pre><code>import Parent.A;
  import Parent.B;
  import Parent.Child.C;
  public class test {
      public static void main(String args[]) {
          B j1 = new B(10);
          C j2 = new C(20);
          try{
              Integer b_copy = (Integer)j1.reflect("b");
              System.out.println(b_copy); // prints "10"
  
              Integer c_copy = (Integer)j2.reflect("c"); // throws java.lang.IllegalAccessException: Class Parent.A can not access a member of class Parent.Child.C with modifiers "protected"
              System.out.println(c_copy);
          } catch (NoSuchFieldException | IllegalAccessException e) {
              System.out.println(e);
          }
      }
  }
  </code></pre>
  
  <p>Thank you very much!</p>