rt/emul/compact/src/main/java/java/lang/invoke/MethodHandleProxies.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 09 Aug 2014 11:11:13 +0200
branchjdk8-b132
changeset 1646 c880a8a8803b
child 1651 5c990ed353e9
permissions -rw-r--r--
Batch of classes necessary to implement invoke dynamic interfaces. Taken from JDK8 build 132
jaroslav@1646
     1
/*
jaroslav@1646
     2
 * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
jaroslav@1646
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1646
     4
 *
jaroslav@1646
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1646
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1646
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1646
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1646
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1646
    10
 *
jaroslav@1646
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1646
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1646
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1646
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1646
    15
 * accompanied this code).
jaroslav@1646
    16
 *
jaroslav@1646
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@1646
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1646
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1646
    20
 *
jaroslav@1646
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1646
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1646
    23
 * questions.
jaroslav@1646
    24
 */
jaroslav@1646
    25
jaroslav@1646
    26
package java.lang.invoke;
jaroslav@1646
    27
jaroslav@1646
    28
import java.lang.reflect.*;
jaroslav@1646
    29
import java.security.AccessController;
jaroslav@1646
    30
import java.security.PrivilegedAction;
jaroslav@1646
    31
import sun.invoke.WrapperInstance;
jaroslav@1646
    32
import java.util.ArrayList;
jaroslav@1646
    33
import sun.reflect.CallerSensitive;
jaroslav@1646
    34
import sun.reflect.Reflection;
jaroslav@1646
    35
import sun.reflect.misc.ReflectUtil;
jaroslav@1646
    36
jaroslav@1646
    37
/**
jaroslav@1646
    38
 * This class consists exclusively of static methods that help adapt
jaroslav@1646
    39
 * method handles to other JVM types, such as interfaces.
jaroslav@1646
    40
 */
jaroslav@1646
    41
public class MethodHandleProxies {
jaroslav@1646
    42
jaroslav@1646
    43
    private MethodHandleProxies() { }  // do not instantiate
jaroslav@1646
    44
jaroslav@1646
    45
    /**
jaroslav@1646
    46
     * Produces an instance of the given single-method interface which redirects
jaroslav@1646
    47
     * its calls to the given method handle.
jaroslav@1646
    48
     * <p>
jaroslav@1646
    49
     * A single-method interface is an interface which declares a uniquely named method.
jaroslav@1646
    50
     * When determining the uniquely named method of a single-method interface,
jaroslav@1646
    51
     * the public {@code Object} methods ({@code toString}, {@code equals}, {@code hashCode})
jaroslav@1646
    52
     * are disregarded.  For example, {@link java.util.Comparator} is a single-method interface,
jaroslav@1646
    53
     * even though it re-declares the {@code Object.equals} method.
jaroslav@1646
    54
     * <p>
jaroslav@1646
    55
     * The interface must be public.  No additional access checks are performed.
jaroslav@1646
    56
     * <p>
jaroslav@1646
    57
     * The resulting instance of the required type will respond to
jaroslav@1646
    58
     * invocation of the type's uniquely named method by calling
jaroslav@1646
    59
     * the given target on the incoming arguments,
jaroslav@1646
    60
     * and returning or throwing whatever the target
jaroslav@1646
    61
     * returns or throws.  The invocation will be as if by
jaroslav@1646
    62
     * {@code target.invoke}.
jaroslav@1646
    63
     * The target's type will be checked before the
jaroslav@1646
    64
     * instance is created, as if by a call to {@code asType},
jaroslav@1646
    65
     * which may result in a {@code WrongMethodTypeException}.
jaroslav@1646
    66
     * <p>
jaroslav@1646
    67
     * The uniquely named method is allowed to be multiply declared,
jaroslav@1646
    68
     * with distinct type descriptors.  (E.g., it can be overloaded,
jaroslav@1646
    69
     * or can possess bridge methods.)  All such declarations are
jaroslav@1646
    70
     * connected directly to the target method handle.
jaroslav@1646
    71
     * Argument and return types are adjusted by {@code asType}
jaroslav@1646
    72
     * for each individual declaration.
jaroslav@1646
    73
     * <p>
jaroslav@1646
    74
     * The wrapper instance will implement the requested interface
jaroslav@1646
    75
     * and its super-types, but no other single-method interfaces.
jaroslav@1646
    76
     * This means that the instance will not unexpectedly
jaroslav@1646
    77
     * pass an {@code instanceof} test for any unrequested type.
jaroslav@1646
    78
     * <p style="font-size:smaller;">
jaroslav@1646
    79
     * <em>Implementation Note:</em>
jaroslav@1646
    80
     * Therefore, each instance must implement a unique single-method interface.
jaroslav@1646
    81
     * Implementations may not bundle together
jaroslav@1646
    82
     * multiple single-method interfaces onto single implementation classes
jaroslav@1646
    83
     * in the style of {@link java.awt.AWTEventMulticaster}.
jaroslav@1646
    84
     * <p>
jaroslav@1646
    85
     * The method handle may throw an <em>undeclared exception</em>,
jaroslav@1646
    86
     * which means any checked exception (or other checked throwable)
jaroslav@1646
    87
     * not declared by the requested type's single abstract method.
jaroslav@1646
    88
     * If this happens, the throwable will be wrapped in an instance of
jaroslav@1646
    89
     * {@link java.lang.reflect.UndeclaredThrowableException UndeclaredThrowableException}
jaroslav@1646
    90
     * and thrown in that wrapped form.
jaroslav@1646
    91
     * <p>
jaroslav@1646
    92
     * Like {@link java.lang.Integer#valueOf Integer.valueOf},
jaroslav@1646
    93
     * {@code asInterfaceInstance} is a factory method whose results are defined
jaroslav@1646
    94
     * by their behavior.
jaroslav@1646
    95
     * It is not guaranteed to return a new instance for every call.
jaroslav@1646
    96
     * <p>
jaroslav@1646
    97
     * Because of the possibility of {@linkplain java.lang.reflect.Method#isBridge bridge methods}
jaroslav@1646
    98
     * and other corner cases, the interface may also have several abstract methods
jaroslav@1646
    99
     * with the same name but having distinct descriptors (types of returns and parameters).
jaroslav@1646
   100
     * In this case, all the methods are bound in common to the one given target.
jaroslav@1646
   101
     * The type check and effective {@code asType} conversion is applied to each
jaroslav@1646
   102
     * method type descriptor, and all abstract methods are bound to the target in common.
jaroslav@1646
   103
     * Beyond this type check, no further checks are made to determine that the
jaroslav@1646
   104
     * abstract methods are related in any way.
jaroslav@1646
   105
     * <p>
jaroslav@1646
   106
     * Future versions of this API may accept additional types,
jaroslav@1646
   107
     * such as abstract classes with single abstract methods.
jaroslav@1646
   108
     * Future versions of this API may also equip wrapper instances
jaroslav@1646
   109
     * with one or more additional public "marker" interfaces.
jaroslav@1646
   110
     * <p>
jaroslav@1646
   111
     * If a security manager is installed, this method is caller sensitive.
jaroslav@1646
   112
     * During any invocation of the target method handle via the returned wrapper,
jaroslav@1646
   113
     * the original creator of the wrapper (the caller) will be visible
jaroslav@1646
   114
     * to context checks requested by the security manager.
jaroslav@1646
   115
     *
jaroslav@1646
   116
     * @param <T> the desired type of the wrapper, a single-method interface
jaroslav@1646
   117
     * @param intfc a class object representing {@code T}
jaroslav@1646
   118
     * @param target the method handle to invoke from the wrapper
jaroslav@1646
   119
     * @return a correctly-typed wrapper for the given target
jaroslav@1646
   120
     * @throws NullPointerException if either argument is null
jaroslav@1646
   121
     * @throws IllegalArgumentException if the {@code intfc} is not a
jaroslav@1646
   122
     *         valid argument to this method
jaroslav@1646
   123
     * @throws WrongMethodTypeException if the target cannot
jaroslav@1646
   124
     *         be converted to the type required by the requested interface
jaroslav@1646
   125
     */
jaroslav@1646
   126
    // Other notes to implementors:
jaroslav@1646
   127
    // <p>
jaroslav@1646
   128
    // No stable mapping is promised between the single-method interface and
jaroslav@1646
   129
    // the implementation class C.  Over time, several implementation
jaroslav@1646
   130
    // classes might be used for the same type.
jaroslav@1646
   131
    // <p>
jaroslav@1646
   132
    // If the implementation is able
jaroslav@1646
   133
    // to prove that a wrapper of the required type
jaroslav@1646
   134
    // has already been created for a given
jaroslav@1646
   135
    // method handle, or for another method handle with the
jaroslav@1646
   136
    // same behavior, the implementation may return that wrapper in place of
jaroslav@1646
   137
    // a new wrapper.
jaroslav@1646
   138
    // <p>
jaroslav@1646
   139
    // This method is designed to apply to common use cases
jaroslav@1646
   140
    // where a single method handle must interoperate with
jaroslav@1646
   141
    // an interface that implements a function-like
jaroslav@1646
   142
    // API.  Additional variations, such as single-abstract-method classes with
jaroslav@1646
   143
    // private constructors, or interfaces with multiple but related
jaroslav@1646
   144
    // entry points, must be covered by hand-written or automatically
jaroslav@1646
   145
    // generated adapter classes.
jaroslav@1646
   146
    //
jaroslav@1646
   147
    @CallerSensitive
jaroslav@1646
   148
    public static
jaroslav@1646
   149
    <T> T asInterfaceInstance(final Class<T> intfc, final MethodHandle target) {
jaroslav@1646
   150
        if (!intfc.isInterface() || !Modifier.isPublic(intfc.getModifiers()))
jaroslav@1646
   151
            throw new IllegalArgumentException("not a public interface: "+intfc.getName());
jaroslav@1646
   152
        final MethodHandle mh;
jaroslav@1646
   153
        if (System.getSecurityManager() != null) {
jaroslav@1646
   154
            final Class<?> caller = Reflection.getCallerClass();
jaroslav@1646
   155
            final ClassLoader ccl = caller != null ? caller.getClassLoader() : null;
jaroslav@1646
   156
            ReflectUtil.checkProxyPackageAccess(ccl, intfc);
jaroslav@1646
   157
            mh = ccl != null ? bindCaller(target, caller) : target;
jaroslav@1646
   158
        } else {
jaroslav@1646
   159
            mh = target;
jaroslav@1646
   160
        }
jaroslav@1646
   161
        ClassLoader proxyLoader = intfc.getClassLoader();
jaroslav@1646
   162
        if (proxyLoader == null) {
jaroslav@1646
   163
            ClassLoader cl = Thread.currentThread().getContextClassLoader(); // avoid use of BCP
jaroslav@1646
   164
            proxyLoader = cl != null ? cl : ClassLoader.getSystemClassLoader();
jaroslav@1646
   165
        }
jaroslav@1646
   166
        final Method[] methods = getSingleNameMethods(intfc);
jaroslav@1646
   167
        if (methods == null)
jaroslav@1646
   168
            throw new IllegalArgumentException("not a single-method interface: "+intfc.getName());
jaroslav@1646
   169
        final MethodHandle[] vaTargets = new MethodHandle[methods.length];
jaroslav@1646
   170
        for (int i = 0; i < methods.length; i++) {
jaroslav@1646
   171
            Method sm = methods[i];
jaroslav@1646
   172
            MethodType smMT = MethodType.methodType(sm.getReturnType(), sm.getParameterTypes());
jaroslav@1646
   173
            MethodHandle checkTarget = mh.asType(smMT);  // make throw WMT
jaroslav@1646
   174
            checkTarget = checkTarget.asType(checkTarget.type().changeReturnType(Object.class));
jaroslav@1646
   175
            vaTargets[i] = checkTarget.asSpreader(Object[].class, smMT.parameterCount());
jaroslav@1646
   176
        }
jaroslav@1646
   177
        final InvocationHandler ih = new InvocationHandler() {
jaroslav@1646
   178
                private Object getArg(String name) {
jaroslav@1646
   179
                    if ((Object)name == "getWrapperInstanceTarget")  return target;
jaroslav@1646
   180
                    if ((Object)name == "getWrapperInstanceType")    return intfc;
jaroslav@1646
   181
                    throw new AssertionError();
jaroslav@1646
   182
                }
jaroslav@1646
   183
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
jaroslav@1646
   184
                    for (int i = 0; i < methods.length; i++) {
jaroslav@1646
   185
                        if (method.equals(methods[i]))
jaroslav@1646
   186
                            return vaTargets[i].invokeExact(args);
jaroslav@1646
   187
                    }
jaroslav@1646
   188
                    if (method.getDeclaringClass() == WrapperInstance.class)
jaroslav@1646
   189
                        return getArg(method.getName());
jaroslav@1646
   190
                    if (isObjectMethod(method))
jaroslav@1646
   191
                        return callObjectMethod(proxy, method, args);
jaroslav@1646
   192
                    throw new InternalError("bad proxy method: "+method);
jaroslav@1646
   193
                }
jaroslav@1646
   194
            };
jaroslav@1646
   195
jaroslav@1646
   196
        final Object proxy;
jaroslav@1646
   197
        if (System.getSecurityManager() != null) {
jaroslav@1646
   198
            // sun.invoke.WrapperInstance is a restricted interface not accessible
jaroslav@1646
   199
            // by any non-null class loader.
jaroslav@1646
   200
            final ClassLoader loader = proxyLoader;
jaroslav@1646
   201
            proxy = AccessController.doPrivileged(new PrivilegedAction<Object>() {
jaroslav@1646
   202
                public Object run() {
jaroslav@1646
   203
                    return Proxy.newProxyInstance(
jaroslav@1646
   204
                            loader,
jaroslav@1646
   205
                            new Class<?>[]{ intfc, WrapperInstance.class },
jaroslav@1646
   206
                            ih);
jaroslav@1646
   207
                }
jaroslav@1646
   208
            });
jaroslav@1646
   209
        } else {
jaroslav@1646
   210
            proxy = Proxy.newProxyInstance(proxyLoader,
jaroslav@1646
   211
                                           new Class<?>[]{ intfc, WrapperInstance.class },
jaroslav@1646
   212
                                           ih);
jaroslav@1646
   213
        }
jaroslav@1646
   214
        return intfc.cast(proxy);
jaroslav@1646
   215
    }
jaroslav@1646
   216
jaroslav@1646
   217
    private static MethodHandle bindCaller(MethodHandle target, Class<?> hostClass) {
jaroslav@1646
   218
        MethodHandle cbmh = MethodHandleImpl.bindCaller(target, hostClass);
jaroslav@1646
   219
        if (target.isVarargsCollector()) {
jaroslav@1646
   220
            MethodType type = cbmh.type();
jaroslav@1646
   221
            int arity = type.parameterCount();
jaroslav@1646
   222
            return cbmh.asVarargsCollector(type.parameterType(arity-1));
jaroslav@1646
   223
        }
jaroslav@1646
   224
        return cbmh;
jaroslav@1646
   225
    }
jaroslav@1646
   226
jaroslav@1646
   227
    /**
jaroslav@1646
   228
     * Determines if the given object was produced by a call to {@link #asInterfaceInstance asInterfaceInstance}.
jaroslav@1646
   229
     * @param x any reference
jaroslav@1646
   230
     * @return true if the reference is not null and points to an object produced by {@code asInterfaceInstance}
jaroslav@1646
   231
     */
jaroslav@1646
   232
    public static
jaroslav@1646
   233
    boolean isWrapperInstance(Object x) {
jaroslav@1646
   234
        return x instanceof WrapperInstance;
jaroslav@1646
   235
    }
jaroslav@1646
   236
jaroslav@1646
   237
    private static WrapperInstance asWrapperInstance(Object x) {
jaroslav@1646
   238
        try {
jaroslav@1646
   239
            if (x != null)
jaroslav@1646
   240
                return (WrapperInstance) x;
jaroslav@1646
   241
        } catch (ClassCastException ex) {
jaroslav@1646
   242
        }
jaroslav@1646
   243
        throw new IllegalArgumentException("not a wrapper instance");
jaroslav@1646
   244
    }
jaroslav@1646
   245
jaroslav@1646
   246
    /**
jaroslav@1646
   247
     * Produces or recovers a target method handle which is behaviorally
jaroslav@1646
   248
     * equivalent to the unique method of this wrapper instance.
jaroslav@1646
   249
     * The object {@code x} must have been produced by a call to {@link #asInterfaceInstance asInterfaceInstance}.
jaroslav@1646
   250
     * This requirement may be tested via {@link #isWrapperInstance isWrapperInstance}.
jaroslav@1646
   251
     * @param x any reference
jaroslav@1646
   252
     * @return a method handle implementing the unique method
jaroslav@1646
   253
     * @throws IllegalArgumentException if the reference x is not to a wrapper instance
jaroslav@1646
   254
     */
jaroslav@1646
   255
    public static
jaroslav@1646
   256
    MethodHandle wrapperInstanceTarget(Object x) {
jaroslav@1646
   257
        return asWrapperInstance(x).getWrapperInstanceTarget();
jaroslav@1646
   258
    }
jaroslav@1646
   259
jaroslav@1646
   260
    /**
jaroslav@1646
   261
     * Recovers the unique single-method interface type for which this wrapper instance was created.
jaroslav@1646
   262
     * The object {@code x} must have been produced by a call to {@link #asInterfaceInstance asInterfaceInstance}.
jaroslav@1646
   263
     * This requirement may be tested via {@link #isWrapperInstance isWrapperInstance}.
jaroslav@1646
   264
     * @param x any reference
jaroslav@1646
   265
     * @return the single-method interface type for which the wrapper was created
jaroslav@1646
   266
     * @throws IllegalArgumentException if the reference x is not to a wrapper instance
jaroslav@1646
   267
     */
jaroslav@1646
   268
    public static
jaroslav@1646
   269
    Class<?> wrapperInstanceType(Object x) {
jaroslav@1646
   270
        return asWrapperInstance(x).getWrapperInstanceType();
jaroslav@1646
   271
    }
jaroslav@1646
   272
jaroslav@1646
   273
    private static
jaroslav@1646
   274
    boolean isObjectMethod(Method m) {
jaroslav@1646
   275
        switch (m.getName()) {
jaroslav@1646
   276
        case "toString":
jaroslav@1646
   277
            return (m.getReturnType() == String.class
jaroslav@1646
   278
                    && m.getParameterTypes().length == 0);
jaroslav@1646
   279
        case "hashCode":
jaroslav@1646
   280
            return (m.getReturnType() == int.class
jaroslav@1646
   281
                    && m.getParameterTypes().length == 0);
jaroslav@1646
   282
        case "equals":
jaroslav@1646
   283
            return (m.getReturnType() == boolean.class
jaroslav@1646
   284
                    && m.getParameterTypes().length == 1
jaroslav@1646
   285
                    && m.getParameterTypes()[0] == Object.class);
jaroslav@1646
   286
        }
jaroslav@1646
   287
        return false;
jaroslav@1646
   288
    }
jaroslav@1646
   289
jaroslav@1646
   290
    private static
jaroslav@1646
   291
    Object callObjectMethod(Object self, Method m, Object[] args) {
jaroslav@1646
   292
        assert(isObjectMethod(m)) : m;
jaroslav@1646
   293
        switch (m.getName()) {
jaroslav@1646
   294
        case "toString":
jaroslav@1646
   295
            return self.getClass().getName() + "@" + Integer.toHexString(self.hashCode());
jaroslav@1646
   296
        case "hashCode":
jaroslav@1646
   297
            return System.identityHashCode(self);
jaroslav@1646
   298
        case "equals":
jaroslav@1646
   299
            return (self == args[0]);
jaroslav@1646
   300
        }
jaroslav@1646
   301
        return null;
jaroslav@1646
   302
    }
jaroslav@1646
   303
jaroslav@1646
   304
    private static
jaroslav@1646
   305
    Method[] getSingleNameMethods(Class<?> intfc) {
jaroslav@1646
   306
        ArrayList<Method> methods = new ArrayList<Method>();
jaroslav@1646
   307
        String uniqueName = null;
jaroslav@1646
   308
        for (Method m : intfc.getMethods()) {
jaroslav@1646
   309
            if (isObjectMethod(m))  continue;
jaroslav@1646
   310
            if (!Modifier.isAbstract(m.getModifiers()))  continue;
jaroslav@1646
   311
            String mname = m.getName();
jaroslav@1646
   312
            if (uniqueName == null)
jaroslav@1646
   313
                uniqueName = mname;
jaroslav@1646
   314
            else if (!uniqueName.equals(mname))
jaroslav@1646
   315
                return null;  // too many abstract methods
jaroslav@1646
   316
            methods.add(m);
jaroslav@1646
   317
        }
jaroslav@1646
   318
        if (uniqueName == null)  return null;
jaroslav@1646
   319
        return methods.toArray(new Method[methods.size()]);
jaroslav@1646
   320
    }
jaroslav@1646
   321
}