jaroslav@1646: /*
jaroslav@1646: * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
jaroslav@1646: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1646: *
jaroslav@1646: * This code is free software; you can redistribute it and/or modify it
jaroslav@1646: * under the terms of the GNU General Public License version 2 only, as
jaroslav@1646: * published by the Free Software Foundation. Oracle designates this
jaroslav@1646: * particular file as subject to the "Classpath" exception as provided
jaroslav@1646: * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1646: *
jaroslav@1646: * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1646: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1646: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
jaroslav@1646: * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1646: * accompanied this code).
jaroslav@1646: *
jaroslav@1646: * You should have received a copy of the GNU General Public License version
jaroslav@1646: * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1646: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1646: *
jaroslav@1646: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1646: * or visit www.oracle.com if you need additional information or have any
jaroslav@1646: * questions.
jaroslav@1646: */
jaroslav@1646:
jaroslav@1646: package java.lang.invoke;
jaroslav@1646:
jaroslav@1646: import java.lang.reflect.*;
jaroslav@1646: import java.security.AccessController;
jaroslav@1646: import java.security.PrivilegedAction;
jaroslav@1646: import sun.invoke.WrapperInstance;
jaroslav@1646: import java.util.ArrayList;
jaroslav@1646: import sun.reflect.CallerSensitive;
jaroslav@1646: import sun.reflect.Reflection;
jaroslav@1646: import sun.reflect.misc.ReflectUtil;
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * This class consists exclusively of static methods that help adapt
jaroslav@1646: * method handles to other JVM types, such as interfaces.
jaroslav@1646: */
jaroslav@1646: public class MethodHandleProxies {
jaroslav@1646:
jaroslav@1646: private MethodHandleProxies() { } // do not instantiate
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces an instance of the given single-method interface which redirects
jaroslav@1646: * its calls to the given method handle.
jaroslav@1646: *
jaroslav@1646: * A single-method interface is an interface which declares a uniquely named method.
jaroslav@1646: * When determining the uniquely named method of a single-method interface,
jaroslav@1646: * the public {@code Object} methods ({@code toString}, {@code equals}, {@code hashCode})
jaroslav@1646: * are disregarded. For example, {@link java.util.Comparator} is a single-method interface,
jaroslav@1646: * even though it re-declares the {@code Object.equals} method.
jaroslav@1646: *
jaroslav@1646: * The interface must be public. No additional access checks are performed.
jaroslav@1646: *
jaroslav@1646: * The resulting instance of the required type will respond to
jaroslav@1646: * invocation of the type's uniquely named method by calling
jaroslav@1646: * the given target on the incoming arguments,
jaroslav@1646: * and returning or throwing whatever the target
jaroslav@1646: * returns or throws. The invocation will be as if by
jaroslav@1646: * {@code target.invoke}.
jaroslav@1646: * The target's type will be checked before the
jaroslav@1646: * instance is created, as if by a call to {@code asType},
jaroslav@1646: * which may result in a {@code WrongMethodTypeException}.
jaroslav@1646: *
jaroslav@1646: * The uniquely named method is allowed to be multiply declared,
jaroslav@1646: * with distinct type descriptors. (E.g., it can be overloaded,
jaroslav@1646: * or can possess bridge methods.) All such declarations are
jaroslav@1646: * connected directly to the target method handle.
jaroslav@1646: * Argument and return types are adjusted by {@code asType}
jaroslav@1646: * for each individual declaration.
jaroslav@1646: *
jaroslav@1646: * The wrapper instance will implement the requested interface
jaroslav@1646: * and its super-types, but no other single-method interfaces.
jaroslav@1646: * This means that the instance will not unexpectedly
jaroslav@1646: * pass an {@code instanceof} test for any unrequested type.
jaroslav@1646: *
jaroslav@1646: * Implementation Note:
jaroslav@1646: * Therefore, each instance must implement a unique single-method interface.
jaroslav@1646: * Implementations may not bundle together
jaroslav@1646: * multiple single-method interfaces onto single implementation classes
jaroslav@1646: * in the style of {@link java.awt.AWTEventMulticaster}.
jaroslav@1646: *
jaroslav@1646: * The method handle may throw an undeclared exception,
jaroslav@1646: * which means any checked exception (or other checked throwable)
jaroslav@1646: * not declared by the requested type's single abstract method.
jaroslav@1646: * If this happens, the throwable will be wrapped in an instance of
jaroslav@1646: * {@link java.lang.reflect.UndeclaredThrowableException UndeclaredThrowableException}
jaroslav@1646: * and thrown in that wrapped form.
jaroslav@1646: *
jaroslav@1646: * Like {@link java.lang.Integer#valueOf Integer.valueOf},
jaroslav@1646: * {@code asInterfaceInstance} is a factory method whose results are defined
jaroslav@1646: * by their behavior.
jaroslav@1646: * It is not guaranteed to return a new instance for every call.
jaroslav@1646: *
jaroslav@1646: * Because of the possibility of {@linkplain java.lang.reflect.Method#isBridge bridge methods}
jaroslav@1646: * and other corner cases, the interface may also have several abstract methods
jaroslav@1646: * with the same name but having distinct descriptors (types of returns and parameters).
jaroslav@1646: * In this case, all the methods are bound in common to the one given target.
jaroslav@1646: * The type check and effective {@code asType} conversion is applied to each
jaroslav@1646: * method type descriptor, and all abstract methods are bound to the target in common.
jaroslav@1646: * Beyond this type check, no further checks are made to determine that the
jaroslav@1646: * abstract methods are related in any way.
jaroslav@1646: *
jaroslav@1646: * Future versions of this API may accept additional types,
jaroslav@1646: * such as abstract classes with single abstract methods.
jaroslav@1646: * Future versions of this API may also equip wrapper instances
jaroslav@1646: * with one or more additional public "marker" interfaces.
jaroslav@1646: *
jaroslav@1646: * If a security manager is installed, this method is caller sensitive.
jaroslav@1646: * During any invocation of the target method handle via the returned wrapper,
jaroslav@1646: * the original creator of the wrapper (the caller) will be visible
jaroslav@1646: * to context checks requested by the security manager.
jaroslav@1646: *
jaroslav@1646: * @param the desired type of the wrapper, a single-method interface
jaroslav@1646: * @param intfc a class object representing {@code T}
jaroslav@1646: * @param target the method handle to invoke from the wrapper
jaroslav@1646: * @return a correctly-typed wrapper for the given target
jaroslav@1646: * @throws NullPointerException if either argument is null
jaroslav@1646: * @throws IllegalArgumentException if the {@code intfc} is not a
jaroslav@1646: * valid argument to this method
jaroslav@1646: * @throws WrongMethodTypeException if the target cannot
jaroslav@1646: * be converted to the type required by the requested interface
jaroslav@1646: */
jaroslav@1646: // Other notes to implementors:
jaroslav@1646: //
jaroslav@1646: // No stable mapping is promised between the single-method interface and
jaroslav@1646: // the implementation class C. Over time, several implementation
jaroslav@1646: // classes might be used for the same type.
jaroslav@1646: //
jaroslav@1646: // If the implementation is able
jaroslav@1646: // to prove that a wrapper of the required type
jaroslav@1646: // has already been created for a given
jaroslav@1646: // method handle, or for another method handle with the
jaroslav@1646: // same behavior, the implementation may return that wrapper in place of
jaroslav@1646: // a new wrapper.
jaroslav@1646: //
jaroslav@1646: // This method is designed to apply to common use cases
jaroslav@1646: // where a single method handle must interoperate with
jaroslav@1646: // an interface that implements a function-like
jaroslav@1646: // API. Additional variations, such as single-abstract-method classes with
jaroslav@1646: // private constructors, or interfaces with multiple but related
jaroslav@1646: // entry points, must be covered by hand-written or automatically
jaroslav@1646: // generated adapter classes.
jaroslav@1646: //
jaroslav@1646: @CallerSensitive
jaroslav@1646: public static
jaroslav@1646: T asInterfaceInstance(final Class intfc, final MethodHandle target) {
jaroslav@1646: if (!intfc.isInterface() || !Modifier.isPublic(intfc.getModifiers()))
jaroslav@1646: throw new IllegalArgumentException("not a public interface: "+intfc.getName());
jaroslav@1646: final MethodHandle mh;
jaroslav@1646: if (System.getSecurityManager() != null) {
jaroslav@1646: final Class> caller = Reflection.getCallerClass();
jaroslav@1646: final ClassLoader ccl = caller != null ? caller.getClassLoader() : null;
jaroslav@1646: ReflectUtil.checkProxyPackageAccess(ccl, intfc);
jaroslav@1646: mh = ccl != null ? bindCaller(target, caller) : target;
jaroslav@1646: } else {
jaroslav@1646: mh = target;
jaroslav@1646: }
jaroslav@1646: ClassLoader proxyLoader = intfc.getClassLoader();
jaroslav@1646: if (proxyLoader == null) {
jaroslav@1646: ClassLoader cl = Thread.currentThread().getContextClassLoader(); // avoid use of BCP
jaroslav@1646: proxyLoader = cl != null ? cl : ClassLoader.getSystemClassLoader();
jaroslav@1646: }
jaroslav@1646: final Method[] methods = getSingleNameMethods(intfc);
jaroslav@1646: if (methods == null)
jaroslav@1646: throw new IllegalArgumentException("not a single-method interface: "+intfc.getName());
jaroslav@1646: final MethodHandle[] vaTargets = new MethodHandle[methods.length];
jaroslav@1646: for (int i = 0; i < methods.length; i++) {
jaroslav@1646: Method sm = methods[i];
jaroslav@1646: MethodType smMT = MethodType.methodType(sm.getReturnType(), sm.getParameterTypes());
jaroslav@1646: MethodHandle checkTarget = mh.asType(smMT); // make throw WMT
jaroslav@1646: checkTarget = checkTarget.asType(checkTarget.type().changeReturnType(Object.class));
jaroslav@1646: vaTargets[i] = checkTarget.asSpreader(Object[].class, smMT.parameterCount());
jaroslav@1646: }
jaroslav@1646: final InvocationHandler ih = new InvocationHandler() {
jaroslav@1646: private Object getArg(String name) {
jaroslav@1646: if ((Object)name == "getWrapperInstanceTarget") return target;
jaroslav@1646: if ((Object)name == "getWrapperInstanceType") return intfc;
jaroslav@1646: throw new AssertionError();
jaroslav@1646: }
jaroslav@1646: public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
jaroslav@1646: for (int i = 0; i < methods.length; i++) {
jaroslav@1646: if (method.equals(methods[i]))
jaroslav@1646: return vaTargets[i].invokeExact(args);
jaroslav@1646: }
jaroslav@1646: if (method.getDeclaringClass() == WrapperInstance.class)
jaroslav@1646: return getArg(method.getName());
jaroslav@1646: if (isObjectMethod(method))
jaroslav@1646: return callObjectMethod(proxy, method, args);
jaroslav@1646: throw new InternalError("bad proxy method: "+method);
jaroslav@1646: }
jaroslav@1646: };
jaroslav@1646:
jaroslav@1646: final Object proxy;
jaroslav@1646: if (System.getSecurityManager() != null) {
jaroslav@1646: // sun.invoke.WrapperInstance is a restricted interface not accessible
jaroslav@1646: // by any non-null class loader.
jaroslav@1646: final ClassLoader loader = proxyLoader;
jaroslav@1646: proxy = AccessController.doPrivileged(new PrivilegedAction