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

(reflect) Class.getFields returns fields which are not public

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Duplicate
    • Icon: P4 P4
    • None
    • 1.1.8
    • core-libs



      Name: dbT83986 Date: 05/13/99


      /*
      method check.showProblem raises IllegalAccessException
      even though getFields should only return "all the accessible public fields of the class"

      This is ambiguous for member notQuitePublic because it has
      default package access.

      I need a way to distinguish the member publicField
      from the member notQuitePublic.
      */



      // file packageAxs\PublicBase.java
      package packageAxs;
      public class PublicBase {
      public int publicField = 456;
      }

      // file packageAxs\Class1.java
      package packageAxs;
      import java.lang.reflect.*;
      import check;

      public class Class1
      {
      public static void main (String[] args) {
      check.showProblem(new packageDerived());
      }
      }
      // note this class is defined locally in file
      // packageAxs\Class1.java
      class packageDerived extends PublicBase {
      public int notQuitePublic = 123;
      }

      // file check.java
      import java.lang.reflect.*;

      public class check {
      public static void showProblem(Object o) {
      Class c = o.getClass();
      System.out.println("Class " + c + " " + Modifier.toString(c.getModifiers()));

      // when called with an object from packageDerived getModifiers tells
      // me it is not public. But I can access the field publicField because
      // it comes from a public base class.

      Field[] fa = c.getFields();
      for (int i = 0; i < fa.length; i++) {
      System.out.println("Field " + fa[i] + " is " + Modifier.toString(fa[i].getModifiers()));
      try {
      Object or = fa[i].get(o);
      System.out.println("Field named " + fa[i].getName() + " returned " + or);
      }
      catch (IllegalAccessException e) {
      // IllegalAccessException is raised even though the field
      // notQuitePublic appears in the list of public fields as returned
      // from c.getFields
      System.out.println("IllegalAccessException: How can i prevent this for " + fa[i].getName());
      }
      }
      }
      }
      (Review ID: 58102)
      ======================================================================

            iris Iris Clark
            dblairsunw Dave Blair (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: