< prev index next >

src/java.base/share/classes/java/lang/reflect/AccessibleObject.java

Print this page


   1 /*
   2  * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.reflect;
  27 
  28 import java.lang.annotation.Annotation;
  29 import java.security.AccessController;
  30 
  31 import jdk.internal.misc.VM;
  32 import jdk.internal.reflect.CallerSensitive;
  33 import jdk.internal.reflect.Reflection;
  34 import jdk.internal.reflect.ReflectionFactory;
  35 import sun.security.action.GetPropertyAction;
  36 
  37 /**
  38  * The AccessibleObject class is the base class for Field, Method and
  39  * Constructor objects.  It provides the ability to flag a reflected
  40  * object as suppressing default Java language access control checks
  41  * when it is used. The access checks -- <em>module boundaries</em>,
  42  * public, default (package) access, protected, and private members --
  43  * are performed when Fields, Methods or Constructors are used to set
  44  * or get fields, to invoke methods or to create and initialize new
  45  * instances of classes, respectively. Unlike access control specified
  46  * in the <cite>The Java&trade; Language Specification</cite> and
  47  * <cite>The Java Virtual Machine Specification</cite>, access checks
  48  * with reflected objects assume {@link Module#canRead readability}.
  49  *
  50  * <p>Setting the {@code accessible} flag in a reflected object
  51  * permits sophisticated applications with sufficient privilege, such
  52  * as Java Object Serialization or other persistence mechanisms, to
  53  * manipulate objects in a manner that would normally be prohibited.
  54  *
  55  * <p>By default, a reflected object is <em>not</em> accessible.
  56  *
  57  * @see Field
  58  * @see Method
  59  * @see Constructor
  60  * @see ReflectPermission





  61  *

  62  * @since 1.2


  63  */
  64 public class AccessibleObject implements AnnotatedElement {
  65 
  66     /**
  67      * The Permission object that is used to check whether a client
  68      * has sufficient privilege to defeat Java language access
  69      * control checks.
  70      */
  71     private static final java.security.Permission ACCESS_PERMISSION =
  72         new ReflectPermission("suppressAccessChecks");
  73 
  74     static void checkPermission() {
  75         SecurityManager sm = System.getSecurityManager();
  76         if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
  77     }
  78 
  79     /**
  80      * Convenience method to set the {@code accessible} flag for an
  81      * array of objects with a single security check (for efficiency).
  82      *
  83      * <p>This method cannot be used to enable access to an object that is a
  84      * {@link Member member} of a class in a different module to the caller and
  85      * where the class is in a package that is not exported to the caller's
  86      * module. Additionally, if the member is non-public or its declaring
  87      * class is non-public, then this method can only be used to enable access
  88      * if the package is {@link Module#isOpen(String,Module) open} to at least
  89      * the caller's module.
  90      *
  91      * <p>If there is a security manager, its
  92      * {@code checkPermission} method is first called with a
  93      * {@code ReflectPermission("suppressAccessChecks")} permission.
  94      *
  95      * <p>A {@code SecurityException} is also thrown if any of the elements of
  96      * the input {@code array} is a {@link java.lang.reflect.Constructor}
  97      * object for the class {@code java.lang.Class} and {@code flag} is true.
  98      *
  99      * @param array the array of AccessibleObjects
 100      * @param flag  the new value for the {@code accessible} flag
 101      *              in each object
 102      * @throws InaccessibleObjectException if access cannot be enabled
 103      * @throws SecurityException if the request is denied.



 104      * @see SecurityManager#checkPermission
 105      * @see ReflectPermission


 106      */
 107     @CallerSensitive
 108     public static void setAccessible(AccessibleObject[] array, boolean flag) {
 109         checkPermission();
 110         if (flag) {
 111             Class<?> caller = Reflection.getCallerClass();
 112             array = array.clone();
 113             for (AccessibleObject ao : array) {
 114                 ao.checkCanSetAccessible(caller);
 115             }
 116         }
 117         for (AccessibleObject ao : array) {
 118             ao.setAccessible0(flag);
 119         }
 120     }
 121 
 122     /**
 123      * Set the {@code accessible} flag for this object to
 124      * the indicated boolean value.  A value of {@code true} indicates that
 125      * the reflected object should suppress Java language access
 126      * checking when it is used.  A value of {@code false} indicates
 127      * that the reflected object should enforce Java language access checks
 128      * while assuming readability (as noted in the class description).
 129      *
 130      * <p>This method cannot be used to enable access to an object that is a
 131      * {@link Member member} of a class in a different module to the caller and
 132      * where the class is in a package that is not exported to the caller's
 133      * module. Additionally, if the member is non-public or its declaring
 134      * class is non-public, then this method can only be used to enable access
 135      * if the package is {@link Module#isOpen(String,Module) open} to at least
 136      * the caller's module.























 137      *
 138      * <p>If there is a security manager, its
 139      * {@code checkPermission} method is first called with a
 140      * {@code ReflectPermission("suppressAccessChecks")} permission.
 141      *
 142      * @param flag the new value for the {@code accessible} flag
 143      * @throws InaccessibleObjectException if access cannot be enabled
 144      * @throws SecurityException if the request is denied
 145      * @see SecurityManager#checkPermission
 146      * @see ReflectPermission
 147      * @see java.lang.invoke.MethodHandles#privateLookupIn


 148      */
 149     public void setAccessible(boolean flag) {
 150         AccessibleObject.checkPermission();
 151         setAccessible0(flag);
 152     }
 153 
 154     void setAccessible0(boolean flag) {



 155         this.override = flag;










































































 156     }
 157 

 158    /**
 159     * If the given AccessibleObject is a {@code Constructor}, {@code Method}
 160     * or {@code Field} then checks that its declaring class is in a package
 161     * that can be accessed by the given caller of setAccessible.
 162     */
 163     void checkCanSetAccessible(Class<?> caller) {
 164         // do nothing, needs to be overridden by Constructor, Method, Field
 165     }
 166 

 167     void checkCanSetAccessible(Class<?> caller, Class<?> declaringClass) {






 168         Module callerModule = caller.getModule();
 169         Module declaringModule = declaringClass.getModule();
 170 
 171         if (callerModule == declaringModule) return;
 172         if (callerModule == Object.class.getModule()) return;
 173         if (!declaringModule.isNamed()) return;
 174 
 175         // package is open to caller
 176         String pn = packageName(declaringClass);
 177         if (declaringModule.isOpen(pn, callerModule)) {
 178             printStackTraceIfOpenedReflectively(declaringModule, pn, callerModule);
 179             return;
 180         }
 181 
 182         // package is exported to caller and class/member is public
 183         boolean isExported = declaringModule.isExported(pn, callerModule);
 184         boolean isClassPublic = Modifier.isPublic(declaringClass.getModifiers());
 185         int modifiers;
 186         if (this instanceof Executable) {
 187             modifiers = ((Executable) this).getModifiers();
 188         } else {
 189             modifiers = ((Field) this).getModifiers();
 190         }
 191         boolean isMemberPublic = Modifier.isPublic(modifiers);
 192         if (isExported && isClassPublic && isMemberPublic) {
 193             printStackTraceIfExportedReflectively(declaringModule, pn, callerModule);
 194             return;


 195         }
 196 










 197         // not accessible
 198         String msg = "Unable to make ";
 199         if (this instanceof Field)
 200             msg += "field ";
 201         msg += this + " accessible: " + declaringModule + " does not \"";
 202         if (isClassPublic && isMemberPublic)
 203             msg += "exports";
 204         else
 205             msg += "opens";
 206         msg += " " + pn + "\" to " + callerModule;
 207         InaccessibleObjectException e = new InaccessibleObjectException(msg);
 208         if (Reflection.printStackTraceWhenAccessFails()) {
 209             e.printStackTrace(System.err);
 210         }
 211         throw e;
 212     }












 213 
 214     private void printStackTraceIfOpenedReflectively(Module module,
 215                                                      String pn,
 216                                                      Module other) {
 217         printStackTraceIfExposedReflectively(module, pn, other, true);
 218     }
 219 
 220     private void printStackTraceIfExportedReflectively(Module module,
 221                                                        String pn,
 222                                                        Module other) {
 223         printStackTraceIfExposedReflectively(module, pn, other, false);
 224     }
 225 
 226     private void printStackTraceIfExposedReflectively(Module module,
 227                                                       String pn,
 228                                                       Module other,
 229                                                       boolean open)
 230     {
 231         if (Reflection.printStackTraceWhenAccessSucceeds()
 232             && !module.isStaticallyExportedOrOpen(pn, other, open))
 233         {
 234             String msg = other + " allowed to invoke setAccessible on ";
 235             if (this instanceof Field)
 236                 msg += "field ";
 237             msg += this;
 238             new Exception(msg) {
 239                 private static final long serialVersionUID = 42L;
 240                 public String toString() {
 241                     return "WARNING: " + getMessage();
 242                 }
 243             }.printStackTrace(System.err);
 244         }
 245     }
 246 
 247     /**
 248      * Returns the package name of the given class.
 249      */
 250     private static String packageName(Class<?> c) {
 251         while (c.isArray()) {
 252             c = c.getComponentType();
 253         }
 254         String pn = c.getPackageName();
 255         return (pn != null) ? pn : "";
 256     }
 257 
 258     /**
 259      * Get the value of the {@code accessible} flag for this object.
 260      *
 261      * @return the value of the object's {@code accessible} flag










 262      */

 263     public boolean isAccessible() {
 264         return override;
 265     }
 266 
 267     /**










































































 268      * Constructor: only used by the Java Virtual Machine.
 269      */
 270     protected AccessibleObject() {}
 271 
 272     // Indicates whether language-level access checks are overridden
 273     // by this object. Initializes to "false". This field is used by
 274     // Field, Method, and Constructor.
 275     //
 276     // NOTE: for security purposes, this field must not be visible
 277     // outside this package.
 278     boolean override;
 279 
 280     // Reflection factory used by subclasses for creating field,
 281     // method, and constructor accessors. Note that this is called
 282     // very early in the bootstrapping process.
 283     static final ReflectionFactory reflectionFactory =
 284         AccessController.doPrivileged(
 285             new ReflectionFactory.GetReflectionFactoryAction());
 286 
 287     /**


   1 /*
   2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.reflect;
  27 
  28 import java.lang.annotation.Annotation;
  29 import java.security.AccessController;
  30 

  31 import jdk.internal.reflect.CallerSensitive;
  32 import jdk.internal.reflect.Reflection;
  33 import jdk.internal.reflect.ReflectionFactory;

  34 
  35 /**
  36  * The {@code AccessibleObject} class is the base class for {@code Field},
  37  * {@code Method}, and {@code Constructor} objects (known as <em>reflected
  38  * objects</em>). It provides the ability to flag a reflected object as
  39  * suppressing checks for Java language access control when it is used. This
  40  * permits sophisticated applications with sufficient privilege, such as Java
  41  * Object Serialization or other persistence mechanisms, to manipulate objects
  42  * in a manner that would normally be prohibited.
  43  *
  44  * <p> Java language access control prevents use of private members outside
  45  * their class; package access members outside their package; protected members
  46  * outside their package or subclasses; and public members outside their
  47  * module unless they are declared in an {@link Module#isExported(String,Module)
  48  * exported} package and the user {@link Module#canRead reads} their module. By
  49  * default, Java language access control is enforced (with one variation) when
  50  * {@code Field}s, {@code Method}s, or {@code Constructor}s are used to get or
  51  * set fields, to invoke methods, or to create and initialize new instances of
  52  * classes, respectively. Every reflected object checks that the code using it
  53  * is in an appropriate class, package, or module. </p>
  54  *
  55  * <p> The one variation from Java language access control is that the checks
  56  * by reflected objects assume readability. That is, the module containing
  57  * the use of a reflected object is assumed to read the module in which
  58  * the underlying field, method, or constructor is declared. </p>
  59  *
  60  * <p> Whether the checks for Java language access control can be suppressed
  61  * (and thus, whether access can be enabled) depends on whether the reflected
  62  * object corresponds to a member in an exported or open package
  63  * (see {@link #setAccessible(boolean)}). </p>
  64  *
  65  * @jls 6.6
  66  * @since 1.2
  67  * @revised 9
  68  * @spec JPMS
  69  */
  70 public class AccessibleObject implements AnnotatedElement {
  71 
  72     /**
  73      * The Permission object that is used to check whether a client
  74      * has sufficient privilege to defeat Java language access
  75      * control checks.
  76      */
  77     private static final java.security.Permission ACCESS_PERMISSION =
  78         new ReflectPermission("suppressAccessChecks");
  79 
  80     static void checkPermission() {
  81         SecurityManager sm = System.getSecurityManager();
  82         if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
  83     }
  84 
  85     /**
  86      * Convenience method to set the {@code accessible} flag for an
  87      * array of reflected objects with a single security check (for efficiency).
  88      *
  89      * <p> This method may be used to enable access to all reflected objects in
  90      * the array when access to each reflected object can be enabled as
  91      * specified by {@link #setAccessible(boolean) setAccessible(boolean)}. </p>




  92      *
  93      * <p>If there is a security manager, its
  94      * {@code checkPermission} method is first called with a
  95      * {@code ReflectPermission("suppressAccessChecks")} permission.
  96      *
  97      * <p>A {@code SecurityException} is also thrown if any of the elements of
  98      * the input {@code array} is a {@link java.lang.reflect.Constructor}
  99      * object for the class {@code java.lang.Class} and {@code flag} is true.
 100      *
 101      * @param array the array of AccessibleObjects
 102      * @param flag  the new value for the {@code accessible} flag
 103      *              in each object
 104      * @throws InaccessibleObjectException if access cannot be enabled for all
 105      *         objects in the array
 106      * @throws SecurityException if the request is denied by the security manager
 107      *         or an element in the array is a constructor for {@code
 108      *         java.lang.Class}
 109      * @see SecurityManager#checkPermission
 110      * @see ReflectPermission
 111      * @revised 9
 112      * @spec JPMS
 113      */
 114     @CallerSensitive
 115     public static void setAccessible(AccessibleObject[] array, boolean flag) {
 116         checkPermission();
 117         if (flag) {
 118             Class<?> caller = Reflection.getCallerClass();
 119             array = array.clone();
 120             for (AccessibleObject ao : array) {
 121                 ao.checkCanSetAccessible(caller);
 122             }
 123         }
 124         for (AccessibleObject ao : array) {
 125             ao.setAccessible0(flag);
 126         }
 127     }
 128 
 129     /**
 130      * Set the {@code accessible} flag for this reflected object to
 131      * the indicated boolean value.  A value of {@code true} indicates that
 132      * the reflected object should suppress checks for Java language access
 133      * control when it is used. A value of {@code false} indicates that
 134      * the reflected object should enforce checks for Java language access
 135      * control when it is used, with the variation noted in the class description.
 136      *
 137      * <p> This method may be used by a caller in class {@code C} to enable
 138      * access to a {@link Member member} of {@link Member#getDeclaringClass()
 139      * declaring class} {@code D} if any of the following hold: </p>
 140      *
 141      * <ul>
 142      *     <li> {@code C} and {@code D} are in the same module. </li>
 143      *
 144      *     <li> The member is {@code public} and {@code D} is {@code public} in
 145      *     a package that the module containing {@code D} {@link
 146      *     Module#isExported(String,Module) exports} to at least the module
 147      *     containing {@code C}. </li>
 148      *
 149      *     <li> The member is {@code protected} {@code static}, {@code D} is
 150      *     {@code public} in a package that the module containing {@code D}
 151      *     exports to at least the module containing {@code C}, and {@code C}
 152      *     is a subclass of {@code D}. </li>
 153      *
 154      *     <li> {@code D} is in a package that the module containing {@code D}
 155      *     {@link Module#isOpen(String,Module) opens} to at least the module
 156      *     containing {@code C}.
 157      *     All packages in unnamed and open modules are open to all modules and
 158      *     so this method always succeeds when {@code D} is in an unnamed or
 159      *     open module. </li>
 160      * </ul>
 161      *
 162      * <p> This method cannot be used to enable access to private members,
 163      * members with default (package) access, protected instance members, or
 164      * protected constructors when the declaring class is in a different module
 165      * to the caller and the package containing the declaring class is not open
 166      * to the caller's module. </p>
 167      *
 168      * <p> If there is a security manager, its
 169      * {@code checkPermission} method is first called with a
 170      * {@code ReflectPermission("suppressAccessChecks")} permission.
 171      *
 172      * @param flag the new value for the {@code accessible} flag
 173      * @throws InaccessibleObjectException if access cannot be enabled
 174      * @throws SecurityException if the request is denied by the security manager
 175      * @see #trySetAccessible

 176      * @see java.lang.invoke.MethodHandles#privateLookupIn
 177      * @revised 9
 178      * @spec JPMS
 179      */
 180     public void setAccessible(boolean flag) {
 181         AccessibleObject.checkPermission();
 182         setAccessible0(flag);
 183     }
 184 
 185     /**
 186      * Sets the accessible flag and returns the new value
 187      */
 188     boolean setAccessible0(boolean flag) {
 189         this.override = flag;
 190         return flag;
 191     }
 192 
 193     /**
 194      * Set the {@code accessible} flag for this reflected object to {@code true}
 195      * if possible. This method sets the {@code accessible} flag, as if by
 196      * invoking {@link #setAccessible(boolean) setAccessible(true)}, and returns
 197      * the possibly-updated value for the {@code accessible} flag. If access
 198      * cannot be enabled, i.e. the checks or Java language access control cannot
 199      * be suppressed, this method returns {@code false} (as opposed to {@code
 200      * setAccessible(true)} throwing {@code InaccessibleObjectException} when
 201      * it fails).
 202      *
 203      * <p> This method is a no-op if the {@code accessible} flag for
 204      * this reflected object is {@code true}.
 205      *
 206      * <p> For example, a caller can invoke {@code trySetAccessible}
 207      * on a {@code Method} object for a private instance method
 208      * {@code p.T::privateMethod} to suppress the checks for Java language access
 209      * control when the {@code Method} is invoked.
 210      * If {@code p.T} class is in a different module to the caller and
 211      * package {@code p} is open to at least the caller's module,
 212      * the code below successfully sets the {@code accessible} flag
 213      * to {@code true}.
 214      *
 215      * <pre>
 216      * {@code
 217      *     p.T obj = ....;  // instance of p.T
 218      *     :
 219      *     Method m = p.T.class.getDeclaredMethod("privateMethod");
 220      *     if (m.trySetAccessible()) {
 221      *         m.invoke(obj);
 222      *     } else {
 223      *         // package p is not opened to the caller to access private member of T
 224      *         ...
 225      *     }
 226      * }</pre>
 227      *
 228      * <p> If there is a security manager, its {@code checkPermission} method
 229      * is first called with a {@code ReflectPermission("suppressAccessChecks")}
 230      * permission. </p>
 231      *
 232      * @return {@code true} if the {@code accessible} flag is set to {@code true};
 233      *         {@code false} if access cannot be enabled.
 234      * @throws SecurityException if the request is denied by the security manager
 235      *
 236      * @since 9
 237      * @spec JPMS
 238      * @see java.lang.invoke.MethodHandles#privateLookupIn
 239      */
 240     @CallerSensitive
 241     public final boolean trySetAccessible() {
 242         AccessibleObject.checkPermission();
 243 
 244         if (override == true) return true;
 245 
 246         // if it's not a Constructor, Method, Field then no access check
 247         if (!Member.class.isInstance(this)) {
 248             return setAccessible0(true);
 249         }
 250 
 251         // does not allow to suppress access check for Class's constructor
 252         Class<?> declaringClass = ((Member) this).getDeclaringClass();
 253         if (declaringClass == Class.class && this instanceof Constructor) {
 254             return false;
 255         }
 256 
 257         if (checkCanSetAccessible(Reflection.getCallerClass(),
 258                                   declaringClass,
 259                                   false)) {
 260             return setAccessible0(true);
 261         } else {
 262             return false;
 263         }
 264     }
 265 
 266 
 267    /**
 268     * If the given AccessibleObject is a {@code Constructor}, {@code Method}
 269     * or {@code Field} then checks that its declaring class is in a package
 270     * that can be accessed by the given caller of setAccessible.
 271     */
 272     void checkCanSetAccessible(Class<?> caller) {
 273         // do nothing, needs to be overridden by Constructor, Method, Field
 274     }
 275 
 276 
 277     void checkCanSetAccessible(Class<?> caller, Class<?> declaringClass) {
 278         checkCanSetAccessible(caller, declaringClass, true);
 279     }
 280 
 281     private boolean checkCanSetAccessible(Class<?> caller,
 282                                           Class<?> declaringClass,
 283                                           boolean throwExceptionIfDenied) {
 284         Module callerModule = caller.getModule();
 285         Module declaringModule = declaringClass.getModule();
 286 
 287         if (callerModule == declaringModule) return true;
 288         if (callerModule == Object.class.getModule()) return true;
 289         if (!declaringModule.isNamed()) return true;
 290 
 291         // package is open to caller
 292         String pn = packageName(declaringClass);
 293         if (declaringModule.isOpen(pn, callerModule)) {
 294             dumpStackIfOpenedReflectively(declaringModule, pn, callerModule);
 295             return true;
 296         }
 297 
 298         // package is exported to caller
 299         boolean isExported = declaringModule.isExported(pn, callerModule);
 300         boolean isClassPublic = Modifier.isPublic(declaringClass.getModifiers());
 301         int modifiers;
 302         if (this instanceof Executable) {
 303             modifiers = ((Executable) this).getModifiers();
 304         } else {
 305             modifiers = ((Field) this).getModifiers();
 306         }
 307         if (isExported && isClassPublic) {
 308 
 309             // member is public
 310             if (Modifier.isPublic(modifiers)) {
 311                 dumpStackIfExportedReflectively(declaringModule, pn, callerModule);
 312                 return true;
 313             }
 314 
 315             // member is protected-static
 316             if (Modifier.isProtected(modifiers)
 317                 && Modifier.isStatic(modifiers)
 318                 && isSubclassOf(caller, declaringClass)) {
 319                 dumpStackIfExportedReflectively(declaringModule, pn, callerModule);
 320                 return true;
 321             }
 322         }
 323 
 324         if (throwExceptionIfDenied) {
 325             // not accessible
 326             String msg = "Unable to make ";
 327             if (this instanceof Field)
 328                 msg += "field ";
 329             msg += this + " accessible: " + declaringModule + " does not \"";
 330             if (isClassPublic && Modifier.isPublic(modifiers))
 331                 msg += "exports";
 332             else
 333                 msg += "opens";
 334             msg += " " + pn + "\" to " + callerModule;
 335             InaccessibleObjectException e = new InaccessibleObjectException(msg);
 336             if (Reflection.printStackTraceWhenAccessFails()) {
 337                 e.printStackTrace(System.err);
 338             }
 339             throw e;
 340         }
 341         return false;
 342     }
 343 
 344     private boolean isSubclassOf(Class<?> queryClass, Class<?> ofClass) {
 345         while (queryClass != null) {
 346             if (queryClass == ofClass) {
 347                 return true;
 348             }
 349             queryClass = queryClass.getSuperclass();
 350         }
 351         return false;
 352     }
 353 
 354     private void dumpStackIfOpenedReflectively(Module module,
 355                                                String pn,
 356                                                Module other) {
 357         dumpStackIfExposedReflectively(module, pn, other, true);
 358     }
 359 
 360     private void dumpStackIfExportedReflectively(Module module,
 361                                                  String pn,
 362                                                  Module other) {
 363         dumpStackIfExposedReflectively(module, pn, other, false);
 364     }
 365 
 366     private void dumpStackIfExposedReflectively(Module module,
 367                                                 String pn,
 368                                                 Module other,
 369                                                 boolean open)
 370     {
 371         if (Reflection.printStackTraceWhenAccessSucceeds()
 372                 && !module.isStaticallyExportedOrOpen(pn, other, open))
 373         {
 374             String msg = other + " allowed to invoke setAccessible on ";
 375             if (this instanceof Field)
 376                 msg += "field ";
 377             msg += this;
 378             new Exception(msg) {
 379                 private static final long serialVersionUID = 42L;
 380                 public String toString() {
 381                     return "WARNING: " + getMessage();
 382                 }
 383             }.printStackTrace(System.err);
 384         }
 385     }
 386 
 387     /**
 388      * Returns the package name of the given class.
 389      */
 390     private static String packageName(Class<?> c) {
 391         while (c.isArray()) {
 392             c = c.getComponentType();
 393         }
 394         String pn = c.getPackageName();
 395         return (pn != null) ? pn : "";
 396     }
 397 
 398     /**
 399      * Get the value of the {@code accessible} flag for this reflected object.
 400      *
 401      * @return the value of the object's {@code accessible} flag
 402      *
 403      * @deprecated
 404      * This method is deprecated because its name hints that it checks
 405      * if the reflected object is accessible when it actually indicates
 406      * if the checks for Java language access control are suppressed.
 407      * This method may return {@code false} on a reflected object that is
 408      * accessible to the caller. To test if this reflected object is accessible,
 409      * it should use {@link #canAccess(Object)}.
 410      *
 411      * @revised 9
 412      */
 413     @Deprecated(since="9")
 414     public boolean isAccessible() {
 415         return override;
 416     }
 417 
 418     /**
 419      * Test if the caller can access this reflected object. If this reflected
 420      * object corresponds to an instance method or field then this method tests
 421      * if the caller can access the given {@code obj} with the reflected object.
 422      * For instance methods or fields then the {@code obj} argument must be an
 423      * instance of the {@link Member#getDeclaringClass() declaring class}. For
 424      * static members and constructors then {@code obj} must be {@code null}.
 425      *
 426      * <p> This method returns {@code true} if the {@code accessible} flag
 427      * is set to {@code true}, i.e. the checks for Java language access control
 428      * are suppressed, or if the caller can access the member as
 429      * specified in <cite>The Java&trade; Language Specification</cite>,
 430      * with the variation noted in the class description. </p>
 431      *
 432      * @param obj an instance object of the declaring class of this reflected
 433      *            object if it is an instance method or field
 434      *
 435      * @return {@code true} if the caller can access this reflected object.
 436      *
 437      * @throws IllegalArgumentException
 438      *         <ul>
 439      *         <li> if this reflected object is a static member or constructor and
 440      *              the given {@code obj} is non-{@code null}, or </li>
 441      *         <li> if this reflected object is an instance method or field
 442      *              and the given {@code obj} is {@code null} or of type
 443      *              that is not a subclass of the {@link Member#getDeclaringClass()
 444      *              declaring class} of the member.</li>
 445      *         </ul>
 446      *
 447      * @since 9
 448      * @spec JPMS
 449      *
 450      * @see #trySetAccessible
 451      * @see #setAccessible(boolean)
 452      */
 453     @CallerSensitive
 454     public final boolean canAccess(Object obj) {
 455         if (!Member.class.isInstance(this)) {
 456             return override;
 457         }
 458 
 459         Class<?> declaringClass = ((Member) this).getDeclaringClass();
 460         int modifiers = ((Member) this).getModifiers();
 461         if (!Modifier.isStatic(modifiers) &&
 462                 (this instanceof Method || this instanceof Field)) {
 463             if (obj == null) {
 464                 throw new IllegalArgumentException("null object for " + this);
 465             }
 466             // if this object is an instance member, the given object
 467             // must be a subclass of the declaring class of this reflected object
 468             if (!declaringClass.isAssignableFrom(obj.getClass())) {
 469                 throw new IllegalArgumentException("object is not an instance of "
 470                                                    + declaringClass.getName());
 471             }
 472         } else if (obj != null) {
 473             throw new IllegalArgumentException("non-null object for " + this);
 474         }
 475 
 476         // access check is suppressed
 477         if (override) return true;
 478 
 479         Class<?> caller = Reflection.getCallerClass();
 480         Class<?> targetClass;
 481         if (this instanceof Constructor) {
 482             targetClass = declaringClass;
 483         } else {
 484             targetClass = Modifier.isStatic(modifiers) ? null : obj.getClass();
 485         }
 486         return Reflection.verifyMemberAccess(caller,
 487                                              declaringClass,
 488                                              targetClass,
 489                                              modifiers);
 490     }
 491 
 492     /**
 493      * Constructor: only used by the Java Virtual Machine.
 494      */
 495     protected AccessibleObject() {}
 496 
 497     // Indicates whether language-level access checks are overridden
 498     // by this object. Initializes to "false". This field is used by
 499     // Field, Method, and Constructor.
 500     //
 501     // NOTE: for security purposes, this field must not be visible
 502     // outside this package.
 503     boolean override;
 504 
 505     // Reflection factory used by subclasses for creating field,
 506     // method, and constructor accessors. Note that this is called
 507     // very early in the bootstrapping process.
 508     static final ReflectionFactory reflectionFactory =
 509         AccessController.doPrivileged(
 510             new ReflectionFactory.GetReflectionFactoryAction());
 511 
 512     /**


< prev index next >