emul/src/main/java/java/lang/reflect/AccessibleObject.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 04 Dec 2012 14:08:19 +0100
branchreflection
changeset 259 9b0fbf4ec230
child 260 1d03cb35fbda
permissions -rw-r--r--
Merging in some reflection classes from jdk7-b147
jtulach@258
     1
/*
jtulach@258
     2
 * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved.
jtulach@258
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jtulach@258
     4
 *
jtulach@258
     5
 * This code is free software; you can redistribute it and/or modify it
jtulach@258
     6
 * under the terms of the GNU General Public License version 2 only, as
jtulach@258
     7
 * published by the Free Software Foundation.  Oracle designates this
jtulach@258
     8
 * particular file as subject to the "Classpath" exception as provided
jtulach@258
     9
 * by Oracle in the LICENSE file that accompanied this code.
jtulach@258
    10
 *
jtulach@258
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jtulach@258
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jtulach@258
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jtulach@258
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jtulach@258
    15
 * accompanied this code).
jtulach@258
    16
 *
jtulach@258
    17
 * You should have received a copy of the GNU General Public License version
jtulach@258
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jtulach@258
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jtulach@258
    20
 *
jtulach@258
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jtulach@258
    22
 * or visit www.oracle.com if you need additional information or have any
jtulach@258
    23
 * questions.
jtulach@258
    24
 */
jtulach@258
    25
jtulach@258
    26
package java.lang.reflect;
jtulach@258
    27
jtulach@258
    28
import java.security.AccessController;
jtulach@258
    29
import sun.reflect.Reflection;
jtulach@258
    30
import sun.reflect.ReflectionFactory;
jtulach@258
    31
import java.lang.annotation.Annotation;
jtulach@258
    32
jtulach@258
    33
/**
jtulach@258
    34
 * The AccessibleObject class is the base class for Field, Method and
jtulach@258
    35
 * Constructor objects.  It provides the ability to flag a reflected
jtulach@258
    36
 * object as suppressing default Java language access control checks
jtulach@258
    37
 * when it is used.  The access checks--for public, default (package)
jtulach@258
    38
 * access, protected, and private members--are performed when Fields,
jtulach@258
    39
 * Methods or Constructors are used to set or get fields, to invoke
jtulach@258
    40
 * methods, or to create and initialize new instances of classes,
jtulach@258
    41
 * respectively.
jtulach@258
    42
 *
jtulach@258
    43
 * <p>Setting the {@code accessible} flag in a reflected object
jtulach@258
    44
 * permits sophisticated applications with sufficient privilege, such
jtulach@258
    45
 * as Java Object Serialization or other persistence mechanisms, to
jtulach@258
    46
 * manipulate objects in a manner that would normally be prohibited.
jtulach@258
    47
 *
jtulach@258
    48
 * <p>By default, a reflected object is <em>not</em> accessible.
jtulach@258
    49
 *
jtulach@258
    50
 * @see Field
jtulach@258
    51
 * @see Method
jtulach@258
    52
 * @see Constructor
jtulach@258
    53
 * @see ReflectPermission
jtulach@258
    54
 *
jtulach@258
    55
 * @since 1.2
jtulach@258
    56
 */
jtulach@258
    57
public class AccessibleObject implements AnnotatedElement {
jtulach@258
    58
jtulach@258
    59
    /**
jtulach@258
    60
     * The Permission object that is used to check whether a client
jtulach@258
    61
     * has sufficient privilege to defeat Java language access
jtulach@258
    62
     * control checks.
jtulach@258
    63
     */
jtulach@258
    64
    static final private java.security.Permission ACCESS_PERMISSION =
jtulach@258
    65
        new ReflectPermission("suppressAccessChecks");
jtulach@258
    66
jtulach@258
    67
    /**
jtulach@258
    68
     * Convenience method to set the {@code accessible} flag for an
jtulach@258
    69
     * array of objects with a single security check (for efficiency).
jtulach@258
    70
     *
jtulach@258
    71
     * <p>First, if there is a security manager, its
jtulach@258
    72
     * {@code checkPermission} method is called with a
jtulach@258
    73
     * {@code ReflectPermission("suppressAccessChecks")} permission.
jtulach@258
    74
     *
jtulach@258
    75
     * <p>A {@code SecurityException} is raised if {@code flag} is
jtulach@258
    76
     * {@code true} but accessibility of any of the elements of the input
jtulach@258
    77
     * {@code array} may not be changed (for example, if the element
jtulach@258
    78
     * object is a {@link Constructor} object for the class {@link
jtulach@258
    79
     * java.lang.Class}).  In the event of such a SecurityException, the
jtulach@258
    80
     * accessibility of objects is set to {@code flag} for array elements
jtulach@258
    81
     * upto (and excluding) the element for which the exception occurred; the
jtulach@258
    82
     * accessibility of elements beyond (and including) the element for which
jtulach@258
    83
     * the exception occurred is unchanged.
jtulach@258
    84
     *
jtulach@258
    85
     * @param array the array of AccessibleObjects
jtulach@258
    86
     * @param flag  the new value for the {@code accessible} flag
jtulach@258
    87
     *              in each object
jtulach@258
    88
     * @throws SecurityException if the request is denied.
jtulach@258
    89
     * @see SecurityManager#checkPermission
jtulach@258
    90
     * @see java.lang.RuntimePermission
jtulach@258
    91
     */
jtulach@258
    92
    public static void setAccessible(AccessibleObject[] array, boolean flag)
jtulach@258
    93
        throws SecurityException {
jtulach@258
    94
        SecurityManager sm = System.getSecurityManager();
jtulach@258
    95
        if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
jtulach@258
    96
        for (int i = 0; i < array.length; i++) {
jtulach@258
    97
            setAccessible0(array[i], flag);
jtulach@258
    98
        }
jtulach@258
    99
    }
jtulach@258
   100
jtulach@258
   101
    /**
jtulach@258
   102
     * Set the {@code accessible} flag for this object to
jtulach@258
   103
     * the indicated boolean value.  A value of {@code true} indicates that
jtulach@258
   104
     * the reflected object should suppress Java language access
jtulach@258
   105
     * checking when it is used.  A value of {@code false} indicates
jtulach@258
   106
     * that the reflected object should enforce Java language access checks.
jtulach@258
   107
     *
jtulach@258
   108
     * <p>First, if there is a security manager, its
jtulach@258
   109
     * {@code checkPermission} method is called with a
jtulach@258
   110
     * {@code ReflectPermission("suppressAccessChecks")} permission.
jtulach@258
   111
     *
jtulach@258
   112
     * <p>A {@code SecurityException} is raised if {@code flag} is
jtulach@258
   113
     * {@code true} but accessibility of this object may not be changed
jtulach@258
   114
     * (for example, if this element object is a {@link Constructor} object for
jtulach@258
   115
     * the class {@link java.lang.Class}).
jtulach@258
   116
     *
jtulach@258
   117
     * <p>A {@code SecurityException} is raised if this object is a {@link
jtulach@258
   118
     * java.lang.reflect.Constructor} object for the class
jtulach@258
   119
     * {@code java.lang.Class}, and {@code flag} is true.
jtulach@258
   120
     *
jtulach@258
   121
     * @param flag the new value for the {@code accessible} flag
jtulach@258
   122
     * @throws SecurityException if the request is denied.
jtulach@258
   123
     * @see SecurityManager#checkPermission
jtulach@258
   124
     * @see java.lang.RuntimePermission
jtulach@258
   125
     */
jtulach@258
   126
    public void setAccessible(boolean flag) throws SecurityException {
jtulach@258
   127
        SecurityManager sm = System.getSecurityManager();
jtulach@258
   128
        if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
jtulach@258
   129
        setAccessible0(this, flag);
jtulach@258
   130
    }
jtulach@258
   131
jtulach@258
   132
    /* Check that you aren't exposing java.lang.Class.<init>. */
jtulach@258
   133
    private static void setAccessible0(AccessibleObject obj, boolean flag)
jtulach@258
   134
        throws SecurityException
jtulach@258
   135
    {
jtulach@258
   136
        if (obj instanceof Constructor && flag == true) {
jtulach@258
   137
            Constructor<?> c = (Constructor<?>)obj;
jtulach@258
   138
            if (c.getDeclaringClass() == Class.class) {
jtulach@258
   139
                throw new SecurityException("Can not make a java.lang.Class" +
jtulach@258
   140
                                            " constructor accessible");
jtulach@258
   141
            }
jtulach@258
   142
        }
jtulach@258
   143
        obj.override = flag;
jtulach@258
   144
    }
jtulach@258
   145
jtulach@258
   146
    /**
jtulach@258
   147
     * Get the value of the {@code accessible} flag for this object.
jtulach@258
   148
     *
jtulach@258
   149
     * @return the value of the object's {@code accessible} flag
jtulach@258
   150
     */
jtulach@258
   151
    public boolean isAccessible() {
jtulach@258
   152
        return override;
jtulach@258
   153
    }
jtulach@258
   154
jtulach@258
   155
    /**
jtulach@258
   156
     * Constructor: only used by the Java Virtual Machine.
jtulach@258
   157
     */
jtulach@258
   158
    protected AccessibleObject() {}
jtulach@258
   159
jtulach@258
   160
    // Indicates whether language-level access checks are overridden
jtulach@258
   161
    // by this object. Initializes to "false". This field is used by
jtulach@258
   162
    // Field, Method, and Constructor.
jtulach@258
   163
    //
jtulach@258
   164
    // NOTE: for security purposes, this field must not be visible
jtulach@258
   165
    // outside this package.
jtulach@258
   166
    boolean override;
jtulach@258
   167
jtulach@258
   168
    // Reflection factory used by subclasses for creating field,
jtulach@258
   169
    // method, and constructor accessors. Note that this is called
jtulach@258
   170
    // very early in the bootstrapping process.
jtulach@258
   171
    static final ReflectionFactory reflectionFactory =
jtulach@258
   172
        AccessController.doPrivileged(
jtulach@258
   173
            new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
jtulach@258
   174
jtulach@258
   175
    /**
jtulach@258
   176
     * @throws NullPointerException {@inheritDoc}
jtulach@258
   177
     * @since 1.5
jtulach@258
   178
     */
jtulach@258
   179
    public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
jtulach@258
   180
        throw new AssertionError("All subclasses should override this method");
jtulach@258
   181
    }
jtulach@258
   182
jtulach@258
   183
    /**
jtulach@258
   184
     * @throws NullPointerException {@inheritDoc}
jtulach@258
   185
     * @since 1.5
jtulach@258
   186
     */
jtulach@258
   187
    public boolean isAnnotationPresent(
jtulach@258
   188
        Class<? extends Annotation> annotationClass) {
jtulach@258
   189
        return getAnnotation(annotationClass) != null;
jtulach@258
   190
    }
jtulach@258
   191
jtulach@258
   192
    /**
jtulach@258
   193
     * @since 1.5
jtulach@258
   194
     */
jtulach@258
   195
    public Annotation[] getAnnotations() {
jtulach@258
   196
        return getDeclaredAnnotations();
jtulach@258
   197
    }
jtulach@258
   198
jtulach@258
   199
    /**
jtulach@258
   200
     * @since 1.5
jtulach@258
   201
     */
jtulach@258
   202
    public Annotation[] getDeclaredAnnotations()  {
jtulach@258
   203
        throw new AssertionError("All subclasses should override this method");
jtulach@258
   204
    }
jtulach@258
   205
jtulach@258
   206
jtulach@258
   207
    // Shared access checking logic.
jtulach@258
   208
jtulach@258
   209
    // For non-public members or members in package-private classes,
jtulach@258
   210
    // it is necessary to perform somewhat expensive security checks.
jtulach@258
   211
    // If the security check succeeds for a given class, it will
jtulach@258
   212
    // always succeed (it is not affected by the granting or revoking
jtulach@258
   213
    // of permissions); we speed up the check in the common case by
jtulach@258
   214
    // remembering the last Class for which the check succeeded.
jtulach@258
   215
    //
jtulach@258
   216
    // The simple security check for Constructor is to see if
jtulach@258
   217
    // the caller has already been seen, verified, and cached.
jtulach@258
   218
    // (See also Class.newInstance(), which uses a similar method.)
jtulach@258
   219
    //
jtulach@258
   220
    // A more complicated security check cache is needed for Method and Field
jtulach@258
   221
    // The cache can be either null (empty cache), a 2-array of {caller,target},
jtulach@258
   222
    // or a caller (with target implicitly equal to this.clazz).
jtulach@258
   223
    // In the 2-array case, the target is always different from the clazz.
jtulach@258
   224
    volatile Object securityCheckCache;
jtulach@258
   225
jtulach@258
   226
    void checkAccess(Class<?> caller, Class<?> clazz, Object obj, int modifiers)
jtulach@258
   227
        throws IllegalAccessException
jtulach@258
   228
    {
jtulach@258
   229
        if (caller == clazz) {  // quick check
jtulach@258
   230
            return;             // ACCESS IS OK
jtulach@258
   231
        }
jtulach@258
   232
        Object cache = securityCheckCache;  // read volatile
jtulach@258
   233
        Class<?> targetClass = clazz;
jtulach@258
   234
        if (obj != null
jtulach@258
   235
            && Modifier.isProtected(modifiers)
jtulach@258
   236
            && ((targetClass = obj.getClass()) != clazz)) {
jtulach@258
   237
            // Must match a 2-list of { caller, targetClass }.
jtulach@258
   238
            if (cache instanceof Class[]) {
jtulach@258
   239
                Class<?>[] cache2 = (Class<?>[]) cache;
jtulach@258
   240
                if (cache2[1] == targetClass &&
jtulach@258
   241
                    cache2[0] == caller) {
jtulach@258
   242
                    return;     // ACCESS IS OK
jtulach@258
   243
                }
jtulach@258
   244
                // (Test cache[1] first since range check for [1]
jtulach@258
   245
                // subsumes range check for [0].)
jtulach@258
   246
            }
jtulach@258
   247
        } else if (cache == caller) {
jtulach@258
   248
            // Non-protected case (or obj.class == this.clazz).
jtulach@258
   249
            return;             // ACCESS IS OK
jtulach@258
   250
        }
jtulach@258
   251
jtulach@258
   252
        // If no return, fall through to the slow path.
jtulach@258
   253
        slowCheckMemberAccess(caller, clazz, obj, modifiers, targetClass);
jtulach@258
   254
    }
jtulach@258
   255
jtulach@258
   256
    // Keep all this slow stuff out of line:
jtulach@258
   257
    void slowCheckMemberAccess(Class<?> caller, Class<?> clazz, Object obj, int modifiers,
jtulach@258
   258
                               Class<?> targetClass)
jtulach@258
   259
        throws IllegalAccessException
jtulach@258
   260
    {
jtulach@258
   261
        Reflection.ensureMemberAccess(caller, clazz, obj, modifiers);
jtulach@258
   262
jtulach@258
   263
        // Success: Update the cache.
jtulach@258
   264
        Object cache = ((targetClass == clazz)
jtulach@258
   265
                        ? caller
jtulach@258
   266
                        : new Class<?>[] { caller, targetClass });
jtulach@258
   267
jtulach@258
   268
        // Note:  The two cache elements are not volatile,
jtulach@258
   269
        // but they are effectively final.  The Java memory model
jtulach@258
   270
        // guarantees that the initializing stores for the cache
jtulach@258
   271
        // elements will occur before the volatile write.
jtulach@258
   272
        securityCheckCache = cache;         // write volatile
jtulach@258
   273
    }
jtulach@258
   274
}