sun.reflect.Reflection Java Examples

The following examples show how to use sun.reflect.Reflection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SerialJavaObject.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an array of <code>Field</code> objects that contains each
 * field of the object that this helper class is serializing.
 *
 * @return an array of <code>Field</code> objects
 * @throws SerialException if an error is encountered accessing
 * the serialized object
 * @throws  SecurityException  If a security manager, <i>s</i>, is present
 * and the caller's class loader is not the same as or an
 * ancestor of the class loader for the class of the
 * {@linkplain #getObject object} being serialized
 * and invocation of {@link SecurityManager#checkPackageAccess
 * s.checkPackageAccess()} denies access to the package
 * of that class.
 * @see Class#getFields
 */
@CallerSensitive
public Field[] getFields() throws SerialException {
    if (fields != null) {
        Class<?> c = this.obj.getClass();
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            /*
             * Check if the caller is allowed to access the specified class's package.
             * If access is denied, throw a SecurityException.
             */
            Class<?> caller = sun.reflect.Reflection.getCallerClass();
            if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
                                                    c.getClassLoader())) {
                ReflectUtil.checkPackageAccess(c);
            }
        }
        return c.getFields();
    } else {
        throw new SerialException("SerialJavaObject does not contain" +
            " a serialized object instance");
    }
}
 
Example #2
Source File: Proxy.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the invocation handler for the specified proxy instance.
 *
 * @param   proxy the proxy instance to return the invocation handler for
 * @return  the invocation handler for the proxy instance
 * @throws  IllegalArgumentException if the argument is not a
 *          proxy instance
 * @throws  SecurityException if a security manager, <em>s</em>, is present
 *          and the caller's class loader is not the same as or an
 *          ancestor of the class loader for the invocation handler
 *          and invocation of {@link SecurityManager#checkPackageAccess
 *          s.checkPackageAccess()} denies access to the invocation
 *          handler's class.
 */
@CallerSensitive
public static InvocationHandler getInvocationHandler(Object proxy)
    throws IllegalArgumentException
{
    /*
     * Verify that the object is actually a proxy instance.
     */
    if (!isProxyClass(proxy.getClass())) {
        throw new IllegalArgumentException("not a proxy instance");
    }

    final Proxy p = (Proxy) proxy;
    final InvocationHandler ih = p.h;
    if (System.getSecurityManager() != null) {
        Class<?> ihClass = ih.getClass();
        Class<?> caller = Reflection.getCallerClass();
        if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
                                                ihClass.getClassLoader()))
        {
            ReflectUtil.checkPackageAccess(ihClass);
        }
    }

    return ih;
}
 
Example #3
Source File: Class.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private Method[] privateGetDeclaredMethods(boolean publicOnly) {
    checkInitted();
    Method[] res;
    ReflectionData<T> rd = reflectionData();
    if (rd != null) {
        res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
        if (res != null) return res;
    }
    // No cached value available; request value from VM
    res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
    if (rd != null) {
        if (publicOnly) {
            rd.declaredPublicMethods = res;
        } else {
            rd.declaredMethods = res;
        }
    }
    return res;
}
 
Example #4
Source File: AccessibleObject.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
void slowCheckMemberAccess(Class<?> caller, Class<?> clazz, Object obj, int modifiers,
                           Class<?> targetClass)
    throws IllegalAccessException
{
    Reflection.ensureMemberAccess(caller, clazz, obj, modifiers);

    // Success: Update the cache.
    Object cache = ((targetClass == clazz)
                    ? caller
                    : new Class<?>[] { caller, targetClass });

    // Note:  The two cache elements are not volatile,
    // but they are effectively final.  The Java memory model
    // guarantees that the initializing stores for the cache
    // elements will occur before the volatile write.
    securityCheckCache = cache;         // write volatile
}
 
Example #5
Source File: Class.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private Field[] privateGetDeclaredFields(boolean publicOnly) {
    checkInitted();
    Field[] res;
    ReflectionData<T> rd = reflectionData();
    if (rd != null) {
        res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
        if (res != null) return res;
    }
    // No cached value available; request value from VM
    res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
    if (rd != null) {
        if (publicOnly) {
            rd.declaredPublicFields = res;
        } else {
            rd.declaredFields = res;
        }
    }
    return res;
}
 
Example #6
Source File: SerialJavaObject.java    From Java8CN with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an array of <code>Field</code> objects that contains each
 * field of the object that this helper class is serializing.
 *
 * @return an array of <code>Field</code> objects
 * @throws SerialException if an error is encountered accessing
 * the serialized object
 * @throws  SecurityException  If a security manager, <i>s</i>, is present
 * and the caller's class loader is not the same as or an
 * ancestor of the class loader for the class of the
 * {@linkplain #getObject object} being serialized
 * and invocation of {@link SecurityManager#checkPackageAccess
 * s.checkPackageAccess()} denies access to the package
 * of that class.
 * @see Class#getFields
 */
@CallerSensitive
public Field[] getFields() throws SerialException {
    if (fields != null) {
        Class<?> c = this.obj.getClass();
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            /*
             * Check if the caller is allowed to access the specified class's package.
             * If access is denied, throw a SecurityException.
             */
            Class<?> caller = sun.reflect.Reflection.getCallerClass();
            if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
                                                    c.getClassLoader())) {
                ReflectUtil.checkPackageAccess(c);
            }
        }
        return c.getFields();
    } else {
        throw new SerialException("SerialJavaObject does not contain" +
            " a serialized object instance");
    }
}
 
Example #7
Source File: SerialJavaObject.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an array of <code>Field</code> objects that contains each
 * field of the object that this helper class is serializing.
 *
 * @return an array of <code>Field</code> objects
 * @throws SerialException if an error is encountered accessing
 * the serialized object
 * @throws  SecurityException  If a security manager, <i>s</i>, is present
 * and the caller's class loader is not the same as or an
 * ancestor of the class loader for the class of the
 * {@linkplain #getObject object} being serialized
 * and invocation of {@link SecurityManager#checkPackageAccess
 * s.checkPackageAccess()} denies access to the package
 * of that class.
 * @see Class#getFields
 */
@CallerSensitive
public Field[] getFields() throws SerialException {
    if (fields != null) {
        Class<?> c = this.obj.getClass();
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            /*
             * Check if the caller is allowed to access the specified class's package.
             * If access is denied, throw a SecurityException.
             */
            Class<?> caller = sun.reflect.Reflection.getCallerClass();
            if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
                                                    c.getClassLoader())) {
                ReflectUtil.checkPackageAccess(c);
            }
        }
        return c.getFields();
    } else {
        throw new SerialException("SerialJavaObject does not contain" +
            " a serialized object instance");
    }
}
 
Example #8
Source File: DriverManager.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Attempts to locate a driver that understands the given URL.
 * The <code>DriverManager</code> attempts to select an appropriate driver from
 * the set of registered JDBC drivers.
 *
 * @param url a database URL of the form
 *     <code>jdbc:<em>subprotocol</em>:<em>subname</em></code>
 * @return a <code>Driver</code> object representing a driver
 * that can connect to the given URL
 * @exception SQLException if a database access error occurs
 */
@CallerSensitive
public static Driver getDriver(String url)
    throws SQLException {

    println("DriverManager.getDriver(\"" + url + "\")");

    Class<?> callerClass = Reflection.getCallerClass();

    // Walk through the loaded registeredDrivers attempting to locate someone
    // who understands the given URL.
    for (DriverInfo aDriver : registeredDrivers) {
        // If the caller does not have permission to load the driver then
        // skip it.
        if(isDriverAllowed(aDriver.driver, callerClass)) {
            try {
                if(aDriver.driver.acceptsURL(url)) {
                    // Success!
                    println("getDriver returning " + aDriver.driver.getClass().getName());
                return (aDriver.driver);
                }

            } catch(SQLException sqe) {
                // Drop through and try the next driver.
            }
        } else {
            println("    skipping: " + aDriver.driver.getClass().getName());
        }

    }

    println("getDriver: no suitable driver");
    throw new SQLException("No suitable driver", "08001");
}
 
Example #9
Source File: HugeFactoryAuthProxy.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
private static boolean registerClass(Class<?> clazz,
                                     List<String> fields,
                                     List<String> methods) {
    if (clazz.getName().startsWith("java") ||
        fields.isEmpty() && methods.isEmpty()) {
        return false;
    }
    final String[] array = new String[fields.size()];
    try {
        Reflection.registerFieldsToFilter(clazz, fields.toArray(array));
        Reflection.registerMethodsToFilter(clazz, methods.toArray(array));
    } catch (IllegalArgumentException e) {
        if (e.getMessage().contains("Filter already registered: class")) {
            return false;
        }
        throw e;
    }

    String code;
    code = String.format("Reflection.registerFieldsToFilter(%s.class, \"%s\");",
                         clazz.getCanonicalName(), String.join("\", \"", fields));
    if (!fields.isEmpty()) {
        System.out.println(code);
    }

    code = String.format("Reflection.registerMethodsToFilter(%s.class, \"%s\");",
                         clazz.getCanonicalName(), String.join("\", \"", methods));
    if (!methods.isEmpty()) {
        System.out.println(code);
    }

    return true;
}
 
Example #10
Source File: VerifyAccess.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static int getClassModifiers(Class<?> c) {
    // This would return the mask stored by javac for the source-level modifiers.
    //   return c.getModifiers();
    // But what we need for JVM access checks are the actual bits from the class header.
    // ...But arrays and primitives are synthesized with their own odd flags:
    if (c.isArray() || c.isPrimitive())
        return c.getModifiers();
    return Reflection.getClassAccessFlags(c);
}
 
Example #11
Source File: MethodHandleImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@CallerSensitive
private static boolean checkCallerClass(Class<?> expected, Class<?> expected2) {
    // This method is called via MH_checkCallerClass and so it's
    // correct to ask for the immediate caller here.
    Class<?> actual = Reflection.getCallerClass();
    if (actual != expected && actual != expected2)
        throw new InternalError("found "+actual.getName()+", expected "+expected.getName()
                                +(expected == expected2 ? "" : ", or else "+expected2.getName()));
    return true;
}
 
Example #12
Source File: Class.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns an array containing {@code Class} objects representing all
 * the public classes and interfaces that are members of the class
 * represented by this {@code Class} object.  This includes public
 * class and interface members inherited from superclasses and public class
 * and interface members declared by the class.  This method returns an
 * array of length 0 if this {@code Class} object has no public member
 * classes or interfaces.  This method also returns an array of length 0 if
 * this {@code Class} object represents a primitive type, an array
 * class, or void.
 *
 * @return the array of {@code Class} objects representing the public
 *         members of this class
 * @throws SecurityException
 *         If a security manager, <i>s</i>, is present and
 *         the caller's class loader is not the same as or an
 *         ancestor of the class loader for the current class and
 *         invocation of {@link SecurityManager#checkPackageAccess
 *         s.checkPackageAccess()} denies access to the package
 *         of this class.
 *
 * @since JDK1.1
 */
@CallerSensitive
public Class<?>[] getClasses() {
    checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);

    // Privileged so this implementation can look at DECLARED classes,
    // something the caller might not have privilege to do.  The code here
    // is allowed to look at DECLARED classes because (1) it does not hand
    // out anything other than public members and (2) public member access
    // has already been ok'd by the SecurityManager.

    return java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<Class<?>[]>() {
            public Class<?>[] run() {
                List<Class<?>> list = new ArrayList<>();
                Class<?> currentClass = Class.this;
                while (currentClass != null) {
                    Class<?>[] members = currentClass.getDeclaredClasses();
                    for (int i = 0; i < members.length; i++) {
                        if (Modifier.isPublic(members[i].getModifiers())) {
                            list.add(members[i]);
                        }
                    }
                    currentClass = currentClass.getSuperclass();
                }
                return list.toArray(new Class<?>[0]);
            }
        });
}
 
Example #13
Source File: Constructor.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Uses the constructor represented by this {@code Constructor} object to
 * create and initialize a new instance of the constructor's
 * declaring class, with the specified initialization parameters.
 * Individual parameters are automatically unwrapped to match
 * primitive formal parameters, and both primitive and reference
 * parameters are subject to method invocation conversions as necessary.
 *
 * <p>If the number of formal parameters required by the underlying constructor
 * is 0, the supplied {@code initargs} array may be of length 0 or null.
 *
 * <p>If the constructor's declaring class is an inner class in a
 * non-static context, the first argument to the constructor needs
 * to be the enclosing instance; see section 15.9.3 of
 * <cite>The Java&trade; Language Specification</cite>.
 *
 * <p>If the required access and argument checks succeed and the
 * instantiation will proceed, the constructor's declaring class
 * is initialized if it has not already been initialized.
 *
 * <p>If the constructor completes normally, returns the newly
 * created and initialized instance.
 *
 * @param initargs array of objects to be passed as arguments to
 * the constructor call; values of primitive types are wrapped in
 * a wrapper object of the appropriate type (e.g. a {@code float}
 * in a {@link java.lang.Float Float})
 *
 * @return a new object created by calling the constructor
 * this object represents
 *
 * @exception IllegalAccessException    if this {@code Constructor} object
 *              is enforcing Java language access control and the underlying
 *              constructor is inaccessible.
 * @exception IllegalArgumentException  if the number of actual
 *              and formal parameters differ; if an unwrapping
 *              conversion for primitive arguments fails; or if,
 *              after possible unwrapping, a parameter value
 *              cannot be converted to the corresponding formal
 *              parameter type by a method invocation conversion; if
 *              this constructor pertains to an enum type.
 * @exception InstantiationException    if the class that declares the
 *              underlying constructor represents an abstract class.
 * @exception InvocationTargetException if the underlying constructor
 *              throws an exception.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 */
@CallerSensitive
public T newInstance(Object ... initargs)
    throws InstantiationException, IllegalAccessException,
           IllegalArgumentException, InvocationTargetException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, null, modifiers);
        }
    }
    if ((clazz.getModifiers() & Modifier.ENUM) != 0)
        throw new IllegalArgumentException("Cannot reflectively create enum objects");
    ConstructorAccessor ca = constructorAccessor;   // read volatile
    if (ca == null) {
        ca = acquireConstructorAccessor();
    }
    @SuppressWarnings("unchecked")
    T inst = (T) ca.newInstance(initargs);
    return inst;
}
 
Example #14
Source File: Class.java    From jdk-1.7-annotated with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the {@code Class} object associated with the class or
 * interface with the given string name, using the given class loader.
 * Given the fully qualified name for a class or interface (in the same
 * format returned by {@code getName}) this method attempts to
 * locate, load, and link the class or interface.  The specified class
 * loader is used to load the class or interface.  If the parameter
 * {@code loader} is null, the class is loaded through the bootstrap
 * class loader.  The class is initialized only if the
 * {@code initialize} parameter is {@code true} and if it has
 * not been initialized earlier.
 *
 * <p> If {@code name} denotes a primitive type or void, an attempt
 * will be made to locate a user-defined class in the unnamed package whose
 * name is {@code name}. Therefore, this method cannot be used to
 * obtain any of the {@code Class} objects representing primitive
 * types or void.
 *
 * <p> If {@code name} denotes an array class, the component type of
 * the array class is loaded but not initialized.
 *
 * <p> For example, in an instance method the expression:
 *
 * <blockquote>
 *  {@code Class.forName("Foo")}
 * </blockquote>
 *
 * is equivalent to:
 *
 * <blockquote>
 *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
 * </blockquote>
 *
 * Note that this method throws errors related to loading, linking or
 * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
 * Java Language Specification</em>.
 * Note that this method does not check whether the requested class
 * is accessible to its caller.
 *
 * <p> If the {@code loader} is {@code null}, and a security
 * manager is present, and the caller's class loader is not null, then this
 * method calls the security manager's {@code checkPermission} method
 * with a {@code RuntimePermission("getClassLoader")} permission to
 * ensure it's ok to access the bootstrap class loader.
 *
 * @param name       fully qualified name of the desired class
 * @param initialize whether the class must be initialized
 * @param loader     class loader from which the class must be loaded
 * @return           class object representing the desired class
 *
 * @exception LinkageError if the linkage fails
 * @exception ExceptionInInitializerError if the initialization provoked
 *            by this method fails
 * @exception ClassNotFoundException if the class cannot be located by
 *            the specified class loader
 *
 * @see       java.lang.Class#forName(String)
 * @see       java.lang.ClassLoader
 * @since     1.2
 */
@CallerSensitive
public static Class<?> forName(String name, boolean initialize,
                               ClassLoader loader)
    throws ClassNotFoundException
{
    if (loader == null) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            ClassLoader ccl = ClassLoader.getClassLoader(Reflection.getCallerClass());
            if (ccl != null) {
                sm.checkPermission(
                    SecurityConstants.GET_CLASSLOADER_PERMISSION);
            }
        }
    }
    return forName0(name, initialize, loader);
}
 
Example #15
Source File: AccessController.java    From jdk1.8-source-analysis with Apache License 2.0 4 votes vote down vote up
/**
 * Performs the specified {@code PrivilegedAction} with privileges
 * enabled and restricted by the specified
 * {@code AccessControlContext} and with a privilege scope limited
 * by specified {@code Permission} arguments.
 *
 * The action is performed with the intersection of the permissions
 * possessed by the caller's protection domain, and those possessed
 * by the domains represented by the specified
 * {@code AccessControlContext}.
 * <p>
 * If the action's {@code run} method throws an (unchecked) exception,
 * it will propagate through this method.
 *
 * <p> This method preserves the current AccessControlContext's
 * DomainCombiner (which may be null) while the action is performed.
 * <p>
 * If a security manager is installed and the specified
 * {@code AccessControlContext} was not created by system code and the
 * caller's {@code ProtectionDomain} has not been granted the
 * {@literal "createAccessControlContext"}
 * {@link java.security.SecurityPermission}, then the action is performed
 * with no permissions.
 *
 * @param <T> the type of the value returned by the PrivilegedAction's
 *                  {@code run} method.
 * @param action the action to be performed.
 * @param context an <i>access control context</i>
 *                representing the restriction to be applied to the
 *                caller's domain's privileges before performing
 *                the specified action.  If the context is
 *                {@code null},
 *                then no additional restriction is applied.
 * @param perms the {@code Permission} arguments which limit the
 *              scope of the caller's privileges. The number of arguments
 *              is variable.
 *
 * @return the value returned by the action's {@code run} method.
 *
 * @throws NullPointerException if action or perms or any element of
 *         perms is {@code null}
 *
 * @see #doPrivileged(PrivilegedAction)
 * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext)
 * @see java.security.DomainCombiner
 *
 * @since 1.8
 */
@CallerSensitive
public static <T> T doPrivilegedWithCombiner(PrivilegedAction<T> action,
    AccessControlContext context, Permission... perms) {

    AccessControlContext parent = getContext();
    DomainCombiner dc = parent.getCombiner();
    if (dc == null && context != null) {
        dc = context.getCombiner();
    }
    if (perms == null) {
        throw new NullPointerException("null permissions parameter");
    }
    Class <?> caller = Reflection.getCallerClass();
    return AccessController.doPrivileged(action, createWrapper(dc, caller,
        parent, context, perms));
}
 
Example #16
Source File: AccessController.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Performs the specified {@code PrivilegedExceptionAction} with
 * privileges enabled and restricted by the specified
 * {@code AccessControlContext} and with a privilege scope limited by
 * specified {@code Permission} arguments.
 *
 * The action is performed with the intersection of the permissions
 * possessed by the caller's protection domain, and those possessed
 * by the domains represented by the specified
 * {@code AccessControlContext}.
 * <p>
 * If the action's {@code run} method throws an (unchecked) exception,
 * it will propagate through this method.
 *
 * <p> This method preserves the current AccessControlContext's
 * DomainCombiner (which may be null) while the action is performed.
 * <p>
 * If a security manager is installed and the specified
 * {@code AccessControlContext} was not created by system code and the
 * caller's {@code ProtectionDomain} has not been granted the
 * {@literal "createAccessControlContext"}
 * {@link java.security.SecurityPermission}, then the action is performed
 * with no permissions.
 *
 * @param <T> the type of the value returned by the
 *                  PrivilegedExceptionAction's {@code run} method.
 * @param action the action to be performed.
 * @param context an <i>access control context</i>
 *                representing the restriction to be applied to the
 *                caller's domain's privileges before performing
 *                the specified action.  If the context is
 *                {@code null},
 *                then no additional restriction is applied.
 * @param perms the {@code Permission} arguments which limit the
 *              scope of the caller's privileges. The number of arguments
 *              is variable.
 *
 * @return the value returned by the action's {@code run} method.
 *
 * @throws PrivilegedActionException if the specified action's
 *         {@code run} method threw a <i>checked</i> exception
 * @throws NullPointerException if action or perms or any element of
 *         perms is {@code null}
 *
 * @see #doPrivileged(PrivilegedAction)
 * @see #doPrivileged(PrivilegedAction,AccessControlContext)
 * @see java.security.DomainCombiner
 *
 * @since 1.8
 */
@CallerSensitive
public static <T> T doPrivilegedWithCombiner(PrivilegedExceptionAction<T> action,
                                             AccessControlContext context,
                                             Permission... perms)
    throws PrivilegedActionException
{
    AccessControlContext parent = getContext();
    DomainCombiner dc = parent.getCombiner();
    if (dc == null && context != null) {
        dc = context.getCombiner();
    }
    if (perms == null) {
        throw new NullPointerException("null permissions parameter");
    }
    Class <?> caller = Reflection.getCallerClass();
    return AccessController.doPrivileged(action, createWrapper(dc, caller,
        parent, context, perms));
}
 
Example #17
Source File: Logger.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create an anonymous Logger.  The newly created Logger is not
 * registered in the LogManager namespace.  There will be no
 * access checks on updates to the logger.
 * <p>
 * This factory method is primarily intended for use from applets.
 * Because the resulting Logger is anonymous it can be kept private
 * by the creating class.  This removes the need for normal security
 * checks, which in turn allows untrusted applet code to update
 * the control state of the Logger.  For example an applet can do
 * a setLevel or an addHandler on an anonymous Logger.
 * <p>
 * Even although the new logger is anonymous, it is configured
 * to have the root logger ("") as its parent.  This means that
 * by default it inherits its effective level and handlers
 * from the root logger.  Changing its parent via the
 * {@link #setParent(java.util.logging.Logger) setParent} method
 * will still require the security permission specified by that method.
 * <p>
 * @param   resourceBundleName  name of ResourceBundle to be used for localizing
 *                          messages for this logger.
 *          May be null if none of the messages require localization.
 * @return a newly created private Logger
 * @throws MissingResourceException if the resourceBundleName is non-null and
 *             no corresponding resource can be found.
 */

// Synchronization is not required here. All synchronization for
// adding a new anonymous Logger object is handled by doSetParent().
@CallerSensitive
public static Logger getAnonymousLogger(String resourceBundleName) {
    LogManager manager = LogManager.getLogManager();
    // cleanup some Loggers that have been GC'ed
    manager.drainLoggerRefQueueBounded();
    Logger result = new Logger(null, resourceBundleName,
                               Reflection.getCallerClass(), manager, false);
    result.anonymous = true;
    Logger root = manager.getLogger("");
    result.doSetParent(root);
    return result;
}
 
Example #18
Source File: Logger.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find or create a logger for a named subsystem.  If a logger has
 * already been created with the given name it is returned.  Otherwise
 * a new logger is created.
 * <p>
 * If a new logger is created its log level will be configured
 * based on the LogManager and it will configured to also send logging
 * output to its parent's Handlers.  It will be registered in
 * the LogManager global namespace.
 * <p>
 * Note: The LogManager may only retain a weak reference to the newly
 * created Logger. It is important to understand that a previously
 * created Logger with the given name may be garbage collected at any
 * time if there is no strong reference to the Logger. In particular,
 * this means that two back-to-back calls like
 * {@code getLogger("MyLogger", ...).log(...)} may use different Logger
 * objects named "MyLogger" if there is no strong reference to the
 * Logger named "MyLogger" elsewhere in the program.
 * <p>
 * If the named Logger already exists and does not yet have a
 * localization resource bundle then the given resource bundle
 * name is used.  If the named Logger already exists and has
 * a different resource bundle name then an IllegalArgumentException
 * is thrown.
 * <p>
 * @param   name    A name for the logger.  This should
 *                          be a dot-separated name and should normally
 *                          be based on the package name or class name
 *                          of the subsystem, such as java.net
 *                          or javax.swing
 * @param   resourceBundleName  name of ResourceBundle to be used for localizing
 *                          messages for this logger. May be {@code null}
 *                          if none of the messages require localization.
 * @return a suitable Logger
 * @throws MissingResourceException if the resourceBundleName is non-null and
 *             no corresponding resource can be found.
 * @throws IllegalArgumentException if the Logger already exists and uses
 *             a different resource bundle name; or if
 *             {@code resourceBundleName} is {@code null} but the named
 *             logger has a resource bundle set.
 * @throws NullPointerException if the name is null.
 */

// Synchronization is not required here. All synchronization for
// adding a new Logger object is handled by LogManager.addLogger().
@CallerSensitive
public static Logger getLogger(String name, String resourceBundleName) {
    Class<?> callerClass = Reflection.getCallerClass();
    Logger result = demandLogger(name, resourceBundleName, callerClass);

    // MissingResourceException or IllegalArgumentException can be
    // thrown by setupResourceInfo().
    // We have to set the callers ClassLoader here in case demandLogger
    // above found a previously created Logger.  This can happen, for
    // example, if Logger.getLogger(name) is called and subsequently
    // Logger.getLogger(name, resourceBundleName) is called.  In this case
    // we won't necessarily have the correct classloader saved away, so
    // we need to set it here, too.

    result.setupResourceInfo(resourceBundleName, callerClass);
    return result;
}
 
Example #19
Source File: AccessController.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Performs the specified {@code PrivilegedExceptionAction} with
 * privileges enabled and restricted by the specified
 * {@code AccessControlContext} and with a privilege scope limited by
 * specified {@code Permission} arguments.
 *
 * The action is performed with the intersection of the permissions
 * possessed by the caller's protection domain, and those possessed
 * by the domains represented by the specified
 * {@code AccessControlContext}.
 * <p>
 * If the action's {@code run} method throws an (unchecked) exception,
 * it will propagate through this method.
 *
 * <p> This method preserves the current AccessControlContext's
 * DomainCombiner (which may be null) while the action is performed.
 * <p>
 * If a security manager is installed and the specified
 * {@code AccessControlContext} was not created by system code and the
 * caller's {@code ProtectionDomain} has not been granted the
 * {@literal "createAccessControlContext"}
 * {@link java.security.SecurityPermission}, then the action is performed
 * with no permissions.
 *
 * @param <T> the type of the value returned by the
 *                  PrivilegedExceptionAction's {@code run} method.
 * @param action the action to be performed.
 * @param context an <i>access control context</i>
 *                representing the restriction to be applied to the
 *                caller's domain's privileges before performing
 *                the specified action.  If the context is
 *                {@code null},
 *                then no additional restriction is applied.
 * @param perms the {@code Permission} arguments which limit the
 *              scope of the caller's privileges. The number of arguments
 *              is variable.
 *
 * @return the value returned by the action's {@code run} method.
 *
 * @throws PrivilegedActionException if the specified action's
 *         {@code run} method threw a <i>checked</i> exception
 * @throws NullPointerException if action or perms or any element of
 *         perms is {@code null}
 *
 * @see #doPrivileged(PrivilegedAction)
 * @see #doPrivileged(PrivilegedAction,AccessControlContext)
 * @see java.security.DomainCombiner
 *
 * @since 1.8
 */
@CallerSensitive
public static <T> T doPrivilegedWithCombiner(PrivilegedExceptionAction<T> action,
                                             AccessControlContext context,
                                             Permission... perms)
    throws PrivilegedActionException
{
    AccessControlContext parent = getContext();
    DomainCombiner dc = parent.getCombiner();
    if (dc == null && context != null) {
        dc = context.getCombiner();
    }
    if (perms == null) {
        throw new NullPointerException("null permissions parameter");
    }
    Class <?> caller = Reflection.getCallerClass();
    return AccessController.doPrivileged(action, createWrapper(dc, caller,
        parent, context, perms));
}
 
Example #20
Source File: AccessController.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Performs the specified {@code PrivilegedExceptionAction} with
 * privileges enabled and restricted by the specified
 * {@code AccessControlContext} and with a privilege scope limited by
 * specified {@code Permission} arguments.
 *
 * The action is performed with the intersection of the permissions
 * possessed by the caller's protection domain, and those possessed
 * by the domains represented by the specified
 * {@code AccessControlContext}.
 * <p>
 * If the action's {@code run} method throws an (unchecked) exception,
 * it will propagate through this method.
 *
 * <p> This method preserves the current AccessControlContext's
 * DomainCombiner (which may be null) while the action is performed.
 * <p>
 * If a security manager is installed and the specified
 * {@code AccessControlContext} was not created by system code and the
 * caller's {@code ProtectionDomain} has not been granted the
 * {@literal "createAccessControlContext"}
 * {@link java.security.SecurityPermission}, then the action is performed
 * with no permissions.
 *
 * @param <T> the type of the value returned by the
 *                  PrivilegedExceptionAction's {@code run} method.
 * @param action the action to be performed.
 * @param context an <i>access control context</i>
 *                representing the restriction to be applied to the
 *                caller's domain's privileges before performing
 *                the specified action.  If the context is
 *                {@code null},
 *                then no additional restriction is applied.
 * @param perms the {@code Permission} arguments which limit the
 *              scope of the caller's privileges. The number of arguments
 *              is variable.
 *
 * @return the value returned by the action's {@code run} method.
 *
 * @throws PrivilegedActionException if the specified action's
 *         {@code run} method threw a <i>checked</i> exception
 * @throws NullPointerException if action or perms or any element of
 *         perms is {@code null}
 *
 * @see #doPrivileged(PrivilegedAction)
 * @see #doPrivileged(PrivilegedAction,AccessControlContext)
 * @see java.security.DomainCombiner
 *
 * @since 1.8
 */
@CallerSensitive
public static <T> T doPrivilegedWithCombiner(PrivilegedExceptionAction<T> action,
                                             AccessControlContext context,
                                             Permission... perms)
    throws PrivilegedActionException
{
    AccessControlContext parent = getContext();
    DomainCombiner dc = parent.getCombiner();
    if (dc == null && context != null) {
        dc = context.getCombiner();
    }
    if (perms == null) {
        throw new NullPointerException("null permissions parameter");
    }
    Class <?> caller = Reflection.getCallerClass();
    return AccessController.doPrivileged(action, createWrapper(dc, caller,
        parent, context, perms));
}
 
Example #21
Source File: Constructor.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Uses the constructor represented by this {@code Constructor} object to
 * create and initialize a new instance of the constructor's
 * declaring class, with the specified initialization parameters.
 * Individual parameters are automatically unwrapped to match
 * primitive formal parameters, and both primitive and reference
 * parameters are subject to method invocation conversions as necessary.
 *
 * <p>If the number of formal parameters required by the underlying constructor
 * is 0, the supplied {@code initargs} array may be of length 0 or null.
 *
 * <p>If the constructor's declaring class is an inner class in a
 * non-static context, the first argument to the constructor needs
 * to be the enclosing instance; see section 15.9.3 of
 * <cite>The Java&trade; Language Specification</cite>.
 *
 * <p>If the required access and argument checks succeed and the
 * instantiation will proceed, the constructor's declaring class
 * is initialized if it has not already been initialized.
 *
 * <p>If the constructor completes normally, returns the newly
 * created and initialized instance.
 *
 * @param initargs array of objects to be passed as arguments to
 * the constructor call; values of primitive types are wrapped in
 * a wrapper object of the appropriate type (e.g. a {@code float}
 * in a {@link java.lang.Float Float})
 *
 * @return a new object created by calling the constructor
 * this object represents
 *
 * @exception IllegalAccessException    if this {@code Constructor} object
 *              is enforcing Java language access control and the underlying
 *              constructor is inaccessible.
 * @exception IllegalArgumentException  if the number of actual
 *              and formal parameters differ; if an unwrapping
 *              conversion for primitive arguments fails; or if,
 *              after possible unwrapping, a parameter value
 *              cannot be converted to the corresponding formal
 *              parameter type by a method invocation conversion; if
 *              this constructor pertains to an enum type.
 * @exception InstantiationException    if the class that declares the
 *              underlying constructor represents an abstract class.
 * @exception InvocationTargetException if the underlying constructor
 *              throws an exception.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 */
@CallerSensitive
public T newInstance(Object ... initargs)
    throws InstantiationException, IllegalAccessException,
           IllegalArgumentException, InvocationTargetException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, null, modifiers);
        }
    }
    if ((clazz.getModifiers() & Modifier.ENUM) != 0)
        throw new IllegalArgumentException("Cannot reflectively create enum objects");
    ConstructorAccessor ca = constructorAccessor;   // read volatile
    if (ca == null) {
        ca = acquireConstructorAccessor();
    }
    @SuppressWarnings("unchecked")
    T inst = (T) ca.newInstance(initargs);
    return inst;
}
 
Example #22
Source File: Method.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Invokes the underlying method represented by this {@code Method}
 * object, on the specified object with the specified parameters.
 * Individual parameters are automatically unwrapped to match
 * primitive formal parameters, and both primitive and reference
 * parameters are subject to method invocation conversions as
 * necessary.
 *
 * <p>If the underlying method is static, then the specified {@code obj}
 * argument is ignored. It may be null.
 *
 * <p>If the number of formal parameters required by the underlying method is
 * 0, the supplied {@code args} array may be of length 0 or null.
 *
 * <p>If the underlying method is an instance method, it is invoked
 * using dynamic method lookup as documented in The Java Language
 * Specification, Second Edition, section 15.12.4.4; in particular,
 * overriding based on the runtime type of the target object will occur.
 *
 * <p>If the underlying method is static, the class that declared
 * the method is initialized if it has not already been initialized.
 *
 * <p>If the method completes normally, the value it returns is
 * returned to the caller of invoke; if the value has a primitive
 * type, it is first appropriately wrapped in an object. However,
 * if the value has the type of an array of a primitive type, the
 * elements of the array are <i>not</i> wrapped in objects; in
 * other words, an array of primitive type is returned.  If the
 * underlying method return type is void, the invocation returns
 * null.
 *
 * @param obj  the object the underlying method is invoked from
 * @param args the arguments used for the method call
 * @return the result of dispatching the method represented by
 * this object on {@code obj} with parameters
 * {@code args}
 *
 * @exception IllegalAccessException    if this {@code Method} object
 *              is enforcing Java language access control and the underlying
 *              method is inaccessible.
 * @exception IllegalArgumentException  if the method is an
 *              instance method and the specified object argument
 *              is not an instance of the class or interface
 *              declaring the underlying method (or of a subclass
 *              or implementor thereof); if the number of actual
 *              and formal parameters differ; if an unwrapping
 *              conversion for primitive arguments fails; or if,
 *              after possible unwrapping, a parameter value
 *              cannot be converted to the corresponding formal
 *              parameter type by a method invocation conversion.
 * @exception InvocationTargetException if the underlying method
 *              throws an exception.
 * @exception NullPointerException      if the specified object is null
 *              and the method is an instance method.
 * @exception ExceptionInInitializerError if the initialization
 * provoked by this method fails.
 */
@CallerSensitive
public Object invoke(Object obj, Object... args)
    throws IllegalAccessException, IllegalArgumentException,
       InvocationTargetException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, obj, modifiers);
        }
    }
    MethodAccessor ma = methodAccessor;             // read volatile
    if (ma == null) {
        ma = acquireMethodAccessor();
    }
    return ma.invoke(obj, args);
}
 
Example #23
Source File: Logger.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find or create a logger for a named subsystem.  If a logger has
 * already been created with the given name it is returned.  Otherwise
 * a new logger is created.
 * <p>
 * If a new logger is created its log level will be configured
 * based on the LogManager and it will configured to also send logging
 * output to its parent's Handlers.  It will be registered in
 * the LogManager global namespace.
 * <p>
 * Note: The LogManager may only retain a weak reference to the newly
 * created Logger. It is important to understand that a previously
 * created Logger with the given name may be garbage collected at any
 * time if there is no strong reference to the Logger. In particular,
 * this means that two back-to-back calls like
 * {@code getLogger("MyLogger", ...).log(...)} may use different Logger
 * objects named "MyLogger" if there is no strong reference to the
 * Logger named "MyLogger" elsewhere in the program.
 * <p>
 * If the named Logger already exists and does not yet have a
 * localization resource bundle then the given resource bundle
 * name is used.  If the named Logger already exists and has
 * a different resource bundle name then an IllegalArgumentException
 * is thrown.
 * <p>
 * @param   name    A name for the logger.  This should
 *                          be a dot-separated name and should normally
 *                          be based on the package name or class name
 *                          of the subsystem, such as java.net
 *                          or javax.swing
 * @param   resourceBundleName  name of ResourceBundle to be used for localizing
 *                          messages for this logger. May be {@code null}
 *                          if none of the messages require localization.
 * @return a suitable Logger
 * @throws MissingResourceException if the resourceBundleName is non-null and
 *             no corresponding resource can be found.
 * @throws IllegalArgumentException if the Logger already exists and uses
 *             a different resource bundle name; or if
 *             {@code resourceBundleName} is {@code null} but the named
 *             logger has a resource bundle set.
 * @throws NullPointerException if the name is null.
 */

// Synchronization is not required here. All synchronization for
// adding a new Logger object is handled by LogManager.addLogger().
@CallerSensitive
public static Logger getLogger(String name, String resourceBundleName) {
    Class<?> callerClass = Reflection.getCallerClass();
    Logger result = demandLogger(name, resourceBundleName, callerClass);

    // MissingResourceException or IllegalArgumentException can be
    // thrown by setupResourceInfo().
    // We have to set the callers ClassLoader here in case demandLogger
    // above found a previously created Logger.  This can happen, for
    // example, if Logger.getLogger(name) is called and subsequently
    // Logger.getLogger(name, resourceBundleName) is called.  In this case
    // we won't necessarily have the correct classloader saved away, so
    // we need to set it here, too.

    result.setupResourceInfo(resourceBundleName, callerClass);
    return result;
}
 
Example #24
Source File: Method.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Invokes the underlying method represented by this {@code Method}
 * object, on the specified object with the specified parameters.
 * Individual parameters are automatically unwrapped to match
 * primitive formal parameters, and both primitive and reference
 * parameters are subject to method invocation conversions as
 * necessary.
 *
 * <p>If the underlying method is static, then the specified {@code obj}
 * argument is ignored. It may be null.
 *
 * <p>If the number of formal parameters required by the underlying method is
 * 0, the supplied {@code args} array may be of length 0 or null.
 *
 * <p>If the underlying method is an instance method, it is invoked
 * using dynamic method lookup as documented in The Java Language
 * Specification, Second Edition, section 15.12.4.4; in particular,
 * overriding based on the runtime type of the target object will occur.
 *
 * <p>If the underlying method is static, the class that declared
 * the method is initialized if it has not already been initialized.
 *
 * <p>If the method completes normally, the value it returns is
 * returned to the caller of invoke; if the value has a primitive
 * type, it is first appropriately wrapped in an object. However,
 * if the value has the type of an array of a primitive type, the
 * elements of the array are <i>not</i> wrapped in objects; in
 * other words, an array of primitive type is returned.  If the
 * underlying method return type is void, the invocation returns
 * null.
 *
 * @param obj  the object the underlying method is invoked from
 * @param args the arguments used for the method call
 * @return the result of dispatching the method represented by
 * this object on {@code obj} with parameters
 * {@code args}
 *
 * @exception IllegalAccessException    if this {@code Method} object
 *              is enforcing Java language access control and the underlying
 *              method is inaccessible.
 * @exception IllegalArgumentException  if the method is an
 *              instance method and the specified object argument
 *              is not an instance of the class or interface
 *              declaring the underlying method (or of a subclass
 *              or implementor thereof); if the number of actual
 *              and formal parameters differ; if an unwrapping
 *              conversion for primitive arguments fails; or if,
 *              after possible unwrapping, a parameter value
 *              cannot be converted to the corresponding formal
 *              parameter type by a method invocation conversion.
 * @exception InvocationTargetException if the underlying method
 *              throws an exception.
 * @exception NullPointerException      if the specified object is null
 *              and the method is an instance method.
 * @exception ExceptionInInitializerError if the initialization
 * provoked by this method fails.
 */
@CallerSensitive
public Object invoke(Object obj, Object... args)
    throws IllegalAccessException, IllegalArgumentException,
       InvocationTargetException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, obj, modifiers);
        }
    }
    MethodAccessor ma = methodAccessor;             // read volatile
    if (ma == null) {
        ma = acquireMethodAccessor();
    }
    return ma.invoke(obj, args);
}
 
Example #25
Source File: Field.java    From hottub with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Gets the value of a static or instance field of type
 * {@code short} or of another primitive type convertible to
 * type {@code short} via a widening conversion.
 *
 * @param obj the object to extract the {@code short} value
 * from
 * @return the value of the field converted to type {@code short}
 *
 * @exception IllegalAccessException    if this {@code Field} object
 *              is enforcing Java language access control and the underlying
 *              field is inaccessible.
 * @exception IllegalArgumentException  if the specified object is not
 *              an instance of the class or interface declaring the
 *              underlying field (or a subclass or implementor
 *              thereof), or if the field value cannot be
 *              converted to the type {@code short} by a
 *              widening conversion.
 * @exception NullPointerException      if the specified object is null
 *              and the field is an instance field.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 * @see       Field#get
 */
@CallerSensitive
public short getShort(Object obj)
    throws IllegalArgumentException, IllegalAccessException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, obj, modifiers);
        }
    }
    return getFieldAccessor(obj).getShort(obj);
}
 
Example #26
Source File: Class.java    From jdk-1.7-annotated with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a {@code Method} object that reflects the specified
 * declared method of the class or interface represented by this
 * {@code Class} object. The {@code name} parameter is a
 * {@code String} that specifies the simple name of the desired
 * method, and the {@code parameterTypes} parameter is an array of
 * {@code Class} objects that identify the method's formal parameter
 * types, in declared order.  If more than one method with the same
 * parameter types is declared in a class, and one of these methods has a
 * return type that is more specific than any of the others, that method is
 * returned; otherwise one of the methods is chosen arbitrarily.  If the
 * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
 * is raised.
 *
 * @param name the name of the method
 * @param parameterTypes the parameter array
 * @return    the {@code Method} object for the method of this class
 * matching the specified name and parameters
 * @exception NoSuchMethodException if a matching method is not found.
 * @exception NullPointerException if {@code name} is {@code null}
 * @exception  SecurityException
 *             If a security manager, <i>s</i>, is present and any of the
 *             following conditions is met:
 *
 *             <ul>
 *
 *             <li> invocation of
 *             {@link SecurityManager#checkMemberAccess
 *             s.checkMemberAccess(this, Member.DECLARED)} denies
 *             access to the declared method
 *
 *             <li> the caller's class loader is not the same as or an
 *             ancestor of the class loader for the current class and
 *             invocation of {@link SecurityManager#checkPackageAccess
 *             s.checkPackageAccess()} denies access to the package
 *             of this class
 *
 *             </ul>
 *
 * @since JDK1.1
 */
@CallerSensitive
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
    throws NoSuchMethodException, SecurityException {
    // be very careful not to change the stack depth of this
    // checkMemberAccess call for security reasons
    // see java.lang.SecurityManager.checkMemberAccess
    checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
    Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
    if (method == null) {
        throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
    }
    return method;
}
 
Example #27
Source File: AccessController.java    From jdk1.8-source-analysis with Apache License 2.0 3 votes vote down vote up
/**
 * Performs the specified {@code PrivilegedExceptionAction} with
 * privileges enabled and restricted by the specified
 * {@code AccessControlContext} and with a privilege scope limited by
 * specified {@code Permission} arguments.
 *
 * The action is performed with the intersection of the permissions
 * possessed by the caller's protection domain, and those possessed
 * by the domains represented by the specified
 * {@code AccessControlContext}.
 * <p>
 * If the action's {@code run} method throws an (unchecked) exception,
 * it will propagate through this method.
 * <p>
 * If a security manager is installed and the specified
 * {@code AccessControlContext} was not created by system code and the
 * caller's {@code ProtectionDomain} has not been granted the
 * {@literal "createAccessControlContext"}
 * {@link java.security.SecurityPermission}, then the action is performed
 * with no permissions.
 *
 * @param <T> the type of the value returned by the
 *                  PrivilegedExceptionAction's {@code run} method.
 * @param action the action to be performed.
 * @param context an <i>access control context</i>
 *                representing the restriction to be applied to the
 *                caller's domain's privileges before performing
 *                the specified action.  If the context is
 *                {@code null},
 *                then no additional restriction is applied.
 * @param perms the {@code Permission} arguments which limit the
 *              scope of the caller's privileges. The number of arguments
 *              is variable.
 *
 * @return the value returned by the action's {@code run} method.
 *
 * @throws PrivilegedActionException if the specified action's
 *         {@code run} method threw a <i>checked</i> exception
 * @throws NullPointerException if action or perms or any element of
 *         perms is {@code null}
 *
 * @see #doPrivileged(PrivilegedAction)
 * @see #doPrivileged(PrivilegedAction,AccessControlContext)
 *
 * @since 1.8
 */
@CallerSensitive
public static <T> T doPrivileged(PrivilegedExceptionAction<T> action,
                                 AccessControlContext context, Permission... perms)
    throws PrivilegedActionException
{
    AccessControlContext parent = getContext();
    if (perms == null) {
        throw new NullPointerException("null permissions parameter");
    }
    Class <?> caller = Reflection.getCallerClass();
    return AccessController.doPrivileged(action, createWrapper(null, caller, parent, context, perms));
}
 
Example #28
Source File: Field.java    From jdk8u-jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Sets the value of a field as a {@code short} on the specified object.
 * This method is equivalent to
 * {@code set(obj, sObj)},
 * where {@code sObj} is a {@code Short} object and
 * {@code sObj.shortValue() == s}.
 *
 * @param obj the object whose field should be modified
 * @param s   the new value for the field of {@code obj}
 * being modified
 *
 * @exception IllegalAccessException    if this {@code Field} object
 *              is enforcing Java language access control and the underlying
 *              field is either inaccessible or final.
 * @exception IllegalArgumentException  if the specified object is not an
 *              instance of the class or interface declaring the underlying
 *              field (or a subclass or implementor thereof),
 *              or if an unwrapping conversion fails.
 * @exception NullPointerException      if the specified object is null
 *              and the field is an instance field.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 * @see       Field#set
 */
@CallerSensitive
public void setShort(Object obj, short s)
    throws IllegalArgumentException, IllegalAccessException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, obj, modifiers);
        }
    }
    getFieldAccessor(obj).setShort(obj, s);
}
 
Example #29
Source File: Class.java    From openjdk-jdk8u with GNU General Public License v2.0 3 votes vote down vote up
/**
 * If the class or interface represented by this {@code Class} object
 * is a member of another class, returns the {@code Class} object
 * representing the class in which it was declared.  This method returns
 * null if this class or interface is not a member of any other class.  If
 * this {@code Class} object represents an array class, a primitive
 * type, or void,then this method returns null.
 *
 * @return the declaring class for this class
 * @throws SecurityException
 *         If a security manager, <i>s</i>, is present and the caller's
 *         class loader is not the same as or an ancestor of the class
 *         loader for the declaring class and invocation of {@link
 *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
 *         denies access to the package of the declaring class
 * @since JDK1.1
 */
@CallerSensitive
public Class<?> getDeclaringClass() throws SecurityException {
    final Class<?> candidate = getDeclaringClass0();

    if (candidate != null)
        candidate.checkPackageAccess(
                ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
    return candidate;
}
 
Example #30
Source File: Field.java    From dragonwell8_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Gets the value of a static or instance {@code boolean} field.
 *
 * @param obj the object to extract the {@code boolean} value
 * from
 * @return the value of the {@code boolean} field
 *
 * @exception IllegalAccessException    if this {@code Field} object
 *              is enforcing Java language access control and the underlying
 *              field is inaccessible.
 * @exception IllegalArgumentException  if the specified object is not
 *              an instance of the class or interface declaring the
 *              underlying field (or a subclass or implementor
 *              thereof), or if the field value cannot be
 *              converted to the type {@code boolean} by a
 *              widening conversion.
 * @exception NullPointerException      if the specified object is null
 *              and the field is an instance field.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 * @see       Field#get
 */
@CallerSensitive
public boolean getBoolean(Object obj)
    throws IllegalArgumentException, IllegalAccessException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, obj, modifiers);
        }
    }
    return getFieldAccessor(obj).getBoolean(obj);
}