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