Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4158470

access incorrectly denied to private variable thru java.lang.reflect.Field

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 1.1.6
    • core-libs
    • None

      Say you have:
      class a { void f() }
      and
      class b extends a { private int x }

      In normal static references there is no way for method f() to reference x in
      class b. However, with the reflect methods f() could be looking at x if f()
      was called on an object of type b. Shouldn't access to this private variable
      be allowed in this case??

      Here is some code which demonstrates this:
      import java.lang.reflect.*;
       
      public class test
      {
        public static void main(String argv[])
        {
          test2 t2 = new test2("hello", "goodbye");
          t2.seeFields();
        }
       
        public void seeFields()
        {
          Object obj;
          Field[] fields = getClass().getDeclaredFields();
          for (int i=0; i < fields.length; i++)
          {
              String field = fields[i].getName();
              System.out.println("getting " + field);
              try
              {
                  obj = fields[i].get(this);
              }
              catch (Exception ex)
              {
                  ex.printStackTrace();
                  continue;
              }
              System.out.println(field + ": " + obj.toString());
          }
        }
       
      }
       
      class test2 extends test
      {
          protected String prot;
          private String priv;
       
          public test2(String x, String y) { prot = x; priv = y; }
      }

      The output here is:
      getting prot
      prot: hello
      getting priv
      java.lang.IllegalAccessException: test2
              at test.seeFields(test.java:22)
              at test.main(test.java:9)

            apalanissunw Anand Palaniswamy (Inactive)
            duke J. Duke
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: