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: jaroslav@1646: import java.util.*; jaroslav@1646: import sun.invoke.util.*; jaroslav@1646: import sun.misc.Unsafe; jaroslav@1646: jaroslav@1646: import static java.lang.invoke.MethodHandleStatics.*; jaroslav@1646: import java.util.logging.Level; jaroslav@1646: import java.util.logging.Logger; jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * A method handle is a typed, directly executable reference to an underlying method, jaroslav@1646: * constructor, field, or similar low-level operation, with optional jaroslav@1646: * transformations of arguments or return values. jaroslav@1646: * These transformations are quite general, and include such patterns as jaroslav@1646: * {@linkplain #asType conversion}, jaroslav@1646: * {@linkplain #bindTo insertion}, jaroslav@1646: * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion}, jaroslav@1646: * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}. jaroslav@1646: * jaroslav@1646: *

Method handle contents

jaroslav@1646: * Method handles are dynamically and strongly typed according to their parameter and return types. jaroslav@1646: * They are not distinguished by the name or the defining class of their underlying methods. jaroslav@1646: * A method handle must be invoked using a symbolic type descriptor which matches jaroslav@1646: * the method handle's own {@linkplain #type type descriptor}. jaroslav@1646: *

jaroslav@1646: * Every method handle reports its type descriptor via the {@link #type type} accessor. jaroslav@1646: * This type descriptor is a {@link java.lang.invoke.MethodType MethodType} object, jaroslav@1646: * whose structure is a series of classes, one of which is jaroslav@1646: * the return type of the method (or {@code void.class} if none). jaroslav@1646: *

jaroslav@1646: * A method handle's type controls the types of invocations it accepts, jaroslav@1646: * and the kinds of transformations that apply to it. jaroslav@1646: *

jaroslav@1646: * A method handle contains a pair of special invoker methods jaroslav@1646: * called {@link #invokeExact invokeExact} and {@link #invoke invoke}. jaroslav@1646: * Both invoker methods provide direct access to the method handle's jaroslav@1646: * underlying method, constructor, field, or other operation, jaroslav@1646: * as modified by transformations of arguments and return values. jaroslav@1646: * Both invokers accept calls which exactly match the method handle's own type. jaroslav@1646: * The plain, inexact invoker also accepts a range of other call types. jaroslav@1646: *

jaroslav@1646: * Method handles are immutable and have no visible state. jaroslav@1646: * Of course, they can be bound to underlying methods or data which exhibit state. jaroslav@1646: * With respect to the Java Memory Model, any method handle will behave jaroslav@1646: * as if all of its (internal) fields are final variables. This means that any method jaroslav@1646: * handle made visible to the application will always be fully formed. jaroslav@1646: * This is true even if the method handle is published through a shared jaroslav@1646: * variable in a data race. jaroslav@1646: *

jaroslav@1646: * Method handles cannot be subclassed by the user. jaroslav@1646: * Implementations may (or may not) create internal subclasses of {@code MethodHandle} jaroslav@1646: * which may be visible via the {@link java.lang.Object#getClass Object.getClass} jaroslav@1646: * operation. The programmer should not draw conclusions about a method handle jaroslav@1646: * from its specific class, as the method handle class hierarchy (if any) jaroslav@1646: * may change from time to time or across implementations from different vendors. jaroslav@1646: * jaroslav@1646: *

Method handle compilation

jaroslav@1646: * A Java method call expression naming {@code invokeExact} or {@code invoke} jaroslav@1646: * can invoke a method handle from Java source code. jaroslav@1646: * From the viewpoint of source code, these methods can take any arguments jaroslav@1646: * and their result can be cast to any return type. jaroslav@1646: * Formally this is accomplished by giving the invoker methods jaroslav@1646: * {@code Object} return types and variable arity {@code Object} arguments, jaroslav@1646: * but they have an additional quality called signature polymorphism jaroslav@1646: * which connects this freedom of invocation directly to the JVM execution stack. jaroslav@1646: *

jaroslav@1646: * As is usual with virtual methods, source-level calls to {@code invokeExact} jaroslav@1646: * and {@code invoke} compile to an {@code invokevirtual} instruction. jaroslav@1646: * More unusually, the compiler must record the actual argument types, jaroslav@1646: * and may not perform method invocation conversions on the arguments. jaroslav@1646: * Instead, it must push them on the stack according to their own unconverted types. jaroslav@1646: * The method handle object itself is pushed on the stack before the arguments. jaroslav@1646: * The compiler then calls the method handle with a symbolic type descriptor which jaroslav@1646: * describes the argument and return types. jaroslav@1646: *

jaroslav@1646: * To issue a complete symbolic type descriptor, the compiler must also determine jaroslav@1646: * the return type. This is based on a cast on the method invocation expression, jaroslav@1646: * if there is one, or else {@code Object} if the invocation is an expression jaroslav@1646: * or else {@code void} if the invocation is a statement. jaroslav@1646: * The cast may be to a primitive type (but not {@code void}). jaroslav@1646: *

jaroslav@1646: * As a corner case, an uncasted {@code null} argument is given jaroslav@1646: * a symbolic type descriptor of {@code java.lang.Void}. jaroslav@1646: * The ambiguity with the type {@code Void} is harmless, since there are no references of type jaroslav@1646: * {@code Void} except the null reference. jaroslav@1646: * jaroslav@1646: *

Method handle invocation

jaroslav@1646: * The first time a {@code invokevirtual} instruction is executed jaroslav@1646: * it is linked, by symbolically resolving the names in the instruction jaroslav@1646: * and verifying that the method call is statically legal. jaroslav@1646: * This is true of calls to {@code invokeExact} and {@code invoke}. jaroslav@1646: * In this case, the symbolic type descriptor emitted by the compiler is checked for jaroslav@1646: * correct syntax and names it contains are resolved. jaroslav@1646: * Thus, an {@code invokevirtual} instruction which invokes jaroslav@1646: * a method handle will always link, as long jaroslav@1646: * as the symbolic type descriptor is syntactically well-formed jaroslav@1646: * and the types exist. jaroslav@1646: *

jaroslav@1646: * When the {@code invokevirtual} is executed after linking, jaroslav@1646: * the receiving method handle's type is first checked by the JVM jaroslav@1646: * to ensure that it matches the symbolic type descriptor. jaroslav@1646: * If the type match fails, it means that the method which the jaroslav@1646: * caller is invoking is not present on the individual jaroslav@1646: * method handle being invoked. jaroslav@1646: *

jaroslav@1646: * In the case of {@code invokeExact}, the type descriptor of the invocation jaroslav@1646: * (after resolving symbolic type names) must exactly match the method type jaroslav@1646: * of the receiving method handle. jaroslav@1646: * In the case of plain, inexact {@code invoke}, the resolved type descriptor jaroslav@1646: * must be a valid argument to the receiver's {@link #asType asType} method. jaroslav@1646: * Thus, plain {@code invoke} is more permissive than {@code invokeExact}. jaroslav@1646: *

jaroslav@1646: * After type matching, a call to {@code invokeExact} directly jaroslav@1646: * and immediately invoke the method handle's underlying method jaroslav@1646: * (or other behavior, as the case may be). jaroslav@1646: *

jaroslav@1646: * A call to plain {@code invoke} works the same as a call to jaroslav@1646: * {@code invokeExact}, if the symbolic type descriptor specified by the caller jaroslav@1646: * exactly matches the method handle's own type. jaroslav@1646: * If there is a type mismatch, {@code invoke} attempts jaroslav@1646: * to adjust the type of the receiving method handle, jaroslav@1646: * as if by a call to {@link #asType asType}, jaroslav@1646: * to obtain an exactly invokable method handle {@code M2}. jaroslav@1646: * This allows a more powerful negotiation of method type jaroslav@1646: * between caller and callee. jaroslav@1646: *

jaroslav@1646: * (Note: The adjusted method handle {@code M2} is not directly observable, jaroslav@1646: * and implementations are therefore not required to materialize it.) jaroslav@1646: * jaroslav@1646: *

Invocation checking

jaroslav@1646: * In typical programs, method handle type matching will usually succeed. jaroslav@1646: * But if a match fails, the JVM will throw a {@link WrongMethodTypeException}, jaroslav@1646: * either directly (in the case of {@code invokeExact}) or indirectly as if jaroslav@1646: * by a failed call to {@code asType} (in the case of {@code invoke}). jaroslav@1646: *

jaroslav@1646: * Thus, a method type mismatch which might show up as a linkage error jaroslav@1646: * in a statically typed program can show up as jaroslav@1646: * a dynamic {@code WrongMethodTypeException} jaroslav@1646: * in a program which uses method handles. jaroslav@1646: *

jaroslav@1646: * Because method types contain "live" {@code Class} objects, jaroslav@1646: * method type matching takes into account both types names and class loaders. jaroslav@1646: * Thus, even if a method handle {@code M} is created in one jaroslav@1646: * class loader {@code L1} and used in another {@code L2}, jaroslav@1646: * method handle calls are type-safe, because the caller's symbolic type jaroslav@1646: * descriptor, as resolved in {@code L2}, jaroslav@1646: * is matched against the original callee method's symbolic type descriptor, jaroslav@1646: * as resolved in {@code L1}. jaroslav@1646: * The resolution in {@code L1} happens when {@code M} is created jaroslav@1646: * and its type is assigned, while the resolution in {@code L2} happens jaroslav@1646: * when the {@code invokevirtual} instruction is linked. jaroslav@1646: *

jaroslav@1646: * Apart from the checking of type descriptors, jaroslav@1646: * a method handle's capability to call its underlying method is unrestricted. jaroslav@1646: * If a method handle is formed on a non-public method by a class jaroslav@1646: * that has access to that method, the resulting handle can be used jaroslav@1646: * in any place by any caller who receives a reference to it. jaroslav@1646: *

jaroslav@1646: * Unlike with the Core Reflection API, where access is checked every time jaroslav@1646: * a reflective method is invoked, jaroslav@1646: * method handle access checking is performed jaroslav@1646: * when the method handle is created. jaroslav@1646: * In the case of {@code ldc} (see below), access checking is performed as part of linking jaroslav@1646: * the constant pool entry underlying the constant method handle. jaroslav@1646: *

jaroslav@1646: * Thus, handles to non-public methods, or to methods in non-public classes, jaroslav@1646: * should generally be kept secret. jaroslav@1646: * They should not be passed to untrusted code unless their use from jaroslav@1646: * the untrusted code would be harmless. jaroslav@1646: * jaroslav@1646: *

Method handle creation

jaroslav@1646: * Java code can create a method handle that directly accesses jaroslav@1646: * any method, constructor, or field that is accessible to that code. jaroslav@1646: * This is done via a reflective, capability-based API called jaroslav@1646: * {@link java.lang.invoke.MethodHandles.Lookup MethodHandles.Lookup} jaroslav@1646: * For example, a static method handle can be obtained jaroslav@1646: * from {@link java.lang.invoke.MethodHandles.Lookup#findStatic Lookup.findStatic}. jaroslav@1646: * There are also conversion methods from Core Reflection API objects, jaroslav@1646: * such as {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}. jaroslav@1646: *

jaroslav@1646: * Like classes and strings, method handles that correspond to accessible jaroslav@1646: * fields, methods, and constructors can also be represented directly jaroslav@1646: * in a class file's constant pool as constants to be loaded by {@code ldc} bytecodes. jaroslav@1646: * A new type of constant pool entry, {@code CONSTANT_MethodHandle}, jaroslav@1646: * refers directly to an associated {@code CONSTANT_Methodref}, jaroslav@1646: * {@code CONSTANT_InterfaceMethodref}, or {@code CONSTANT_Fieldref} jaroslav@1646: * constant pool entry. jaroslav@1646: * (For full details on method handle constants, jaroslav@1646: * see sections 4.4.8 and 5.4.3.5 of the Java Virtual Machine Specification.) jaroslav@1646: *

jaroslav@1646: * Method handles produced by lookups or constant loads from methods or jaroslav@1646: * constructors with the variable arity modifier bit ({@code 0x0080}) jaroslav@1646: * have a corresponding variable arity, as if they were defined with jaroslav@1646: * the help of {@link #asVarargsCollector asVarargsCollector}. jaroslav@1646: *

jaroslav@1646: * A method reference may refer either to a static or non-static method. jaroslav@1646: * In the non-static case, the method handle type includes an explicit jaroslav@1646: * receiver argument, prepended before any other arguments. jaroslav@1646: * In the method handle's type, the initial receiver argument is typed jaroslav@1646: * according to the class under which the method was initially requested. jaroslav@1646: * (E.g., if a non-static method handle is obtained via {@code ldc}, jaroslav@1646: * the type of the receiver is the class named in the constant pool entry.) jaroslav@1646: *

jaroslav@1646: * Method handle constants are subject to the same link-time access checks jaroslav@1646: * their corresponding bytecode instructions, and the {@code ldc} instruction jaroslav@1646: * will throw corresponding linkage errors if the bytecode behaviors would jaroslav@1646: * throw such errors. jaroslav@1646: *

jaroslav@1646: * As a corollary of this, access to protected members is restricted jaroslav@1646: * to receivers only of the accessing class, or one of its subclasses, jaroslav@1646: * and the accessing class must in turn be a subclass (or package sibling) jaroslav@1646: * of the protected member's defining class. jaroslav@1646: * If a method reference refers to a protected non-static method or field jaroslav@1646: * of a class outside the current package, the receiver argument will jaroslav@1646: * be narrowed to the type of the accessing class. jaroslav@1646: *

jaroslav@1646: * When a method handle to a virtual method is invoked, the method is jaroslav@1646: * always looked up in the receiver (that is, the first argument). jaroslav@1646: *

jaroslav@1646: * A non-virtual method handle to a specific virtual method implementation jaroslav@1646: * can also be created. These do not perform virtual lookup based on jaroslav@1646: * receiver type. Such a method handle simulates the effect of jaroslav@1646: * an {@code invokespecial} instruction to the same method. jaroslav@1646: * jaroslav@1646: *

Usage examples

jaroslav@1646: * Here are some examples of usage: jaroslav@1646: *
{@code
jaroslav@1646: Object x, y; String s; int i;
jaroslav@1646: MethodType mt; MethodHandle mh;
jaroslav@1646: MethodHandles.Lookup lookup = MethodHandles.lookup();
jaroslav@1646: // mt is (char,char)String
jaroslav@1646: mt = MethodType.methodType(String.class, char.class, char.class);
jaroslav@1646: mh = lookup.findVirtual(String.class, "replace", mt);
jaroslav@1646: s = (String) mh.invokeExact("daddy",'d','n');
jaroslav@1646: // invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
jaroslav@1646: assertEquals(s, "nanny");
jaroslav@1646: // weakly typed invocation (using MHs.invoke)
jaroslav@1646: s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
jaroslav@1646: assertEquals(s, "savvy");
jaroslav@1646: // mt is (Object[])List
jaroslav@1646: mt = MethodType.methodType(java.util.List.class, Object[].class);
jaroslav@1646: mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
jaroslav@1646: assert(mh.isVarargsCollector());
jaroslav@1646: x = mh.invoke("one", "two");
jaroslav@1646: // invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
jaroslav@1646: assertEquals(x, java.util.Arrays.asList("one","two"));
jaroslav@1646: // mt is (Object,Object,Object)Object
jaroslav@1646: mt = MethodType.genericMethodType(3);
jaroslav@1646: mh = mh.asType(mt);
jaroslav@1646: x = mh.invokeExact((Object)1, (Object)2, (Object)3);
jaroslav@1646: // invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
jaroslav@1646: assertEquals(x, java.util.Arrays.asList(1,2,3));
jaroslav@1646: // mt is ()int
jaroslav@1646: mt = MethodType.methodType(int.class);
jaroslav@1646: mh = lookup.findVirtual(java.util.List.class, "size", mt);
jaroslav@1646: i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
jaroslav@1646: // invokeExact(Ljava/util/List;)I
jaroslav@1646: assert(i == 3);
jaroslav@1646: mt = MethodType.methodType(void.class, String.class);
jaroslav@1646: mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
jaroslav@1646: mh.invokeExact(System.out, "Hello, world.");
jaroslav@1646: // invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
jaroslav@1646:  * }
jaroslav@1646: * Each of the above calls to {@code invokeExact} or plain {@code invoke} jaroslav@1646: * generates a single invokevirtual instruction with jaroslav@1646: * the symbolic type descriptor indicated in the following comment. jaroslav@1646: * In these examples, the helper method {@code assertEquals} is assumed to jaroslav@1646: * be a method which calls {@link java.util.Objects#equals(Object,Object) Objects.equals} jaroslav@1646: * on its arguments, and asserts that the result is true. jaroslav@1646: * jaroslav@1646: *

Exceptions

jaroslav@1646: * The methods {@code invokeExact} and {@code invoke} are declared jaroslav@1646: * to throw {@link java.lang.Throwable Throwable}, jaroslav@1646: * which is to say that there is no static restriction on what a method handle jaroslav@1646: * can throw. Since the JVM does not distinguish between checked jaroslav@1646: * and unchecked exceptions (other than by their class, of course), jaroslav@1646: * there is no particular effect on bytecode shape from ascribing jaroslav@1646: * checked exceptions to method handle invocations. But in Java source jaroslav@1646: * code, methods which perform method handle calls must either explicitly jaroslav@1646: * throw {@code Throwable}, or else must catch all jaroslav@1646: * throwables locally, rethrowing only those which are legal in the context, jaroslav@1646: * and wrapping ones which are illegal. jaroslav@1646: * jaroslav@1646: *

Signature polymorphism

jaroslav@1646: * The unusual compilation and linkage behavior of jaroslav@1646: * {@code invokeExact} and plain {@code invoke} jaroslav@1646: * is referenced by the term signature polymorphism. jaroslav@1646: * As defined in the Java Language Specification, jaroslav@1646: * a signature polymorphic method is one which can operate with jaroslav@1646: * any of a wide range of call signatures and return types. jaroslav@1646: *

jaroslav@1646: * In source code, a call to a signature polymorphic method will jaroslav@1646: * compile, regardless of the requested symbolic type descriptor. jaroslav@1646: * As usual, the Java compiler emits an {@code invokevirtual} jaroslav@1646: * instruction with the given symbolic type descriptor against the named method. jaroslav@1646: * The unusual part is that the symbolic type descriptor is derived from jaroslav@1646: * the actual argument and return types, not from the method declaration. jaroslav@1646: *

jaroslav@1646: * When the JVM processes bytecode containing signature polymorphic calls, jaroslav@1646: * it will successfully link any such call, regardless of its symbolic type descriptor. jaroslav@1646: * (In order to retain type safety, the JVM will guard such calls with suitable jaroslav@1646: * dynamic type checks, as described elsewhere.) jaroslav@1646: *

jaroslav@1646: * Bytecode generators, including the compiler back end, are required to emit jaroslav@1646: * untransformed symbolic type descriptors for these methods. jaroslav@1646: * Tools which determine symbolic linkage are required to accept such jaroslav@1646: * untransformed descriptors, without reporting linkage errors. jaroslav@1646: * jaroslav@1646: *

Interoperation between method handles and the Core Reflection API

jaroslav@1646: * Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup Lookup} API, jaroslav@1646: * any class member represented by a Core Reflection API object jaroslav@1646: * can be converted to a behaviorally equivalent method handle. jaroslav@1646: * For example, a reflective {@link java.lang.reflect.Method Method} can jaroslav@1646: * be converted to a method handle using jaroslav@1646: * {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}. jaroslav@1646: * The resulting method handles generally provide more direct and efficient jaroslav@1646: * access to the underlying class members. jaroslav@1646: *

jaroslav@1646: * As a special case, jaroslav@1646: * when the Core Reflection API is used to view the signature polymorphic jaroslav@1646: * methods {@code invokeExact} or plain {@code invoke} in this class, jaroslav@1646: * they appear as ordinary non-polymorphic methods. jaroslav@1646: * Their reflective appearance, as viewed by jaroslav@1646: * {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod}, jaroslav@1646: * is unaffected by their special status in this API. jaroslav@1646: * For example, {@link java.lang.reflect.Method#getModifiers Method.getModifiers} jaroslav@1646: * will report exactly those modifier bits required for any similarly jaroslav@1646: * declared method, including in this case {@code native} and {@code varargs} bits. jaroslav@1646: *

jaroslav@1646: * As with any reflected method, these methods (when reflected) may be jaroslav@1646: * invoked via {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}. jaroslav@1646: * However, such reflective calls do not result in method handle invocations. jaroslav@1646: * Such a call, if passed the required argument jaroslav@1646: * (a single one, of type {@code Object[]}), will ignore the argument and jaroslav@1646: * will throw an {@code UnsupportedOperationException}. jaroslav@1646: *

jaroslav@1646: * Since {@code invokevirtual} instructions can natively jaroslav@1646: * invoke method handles under any symbolic type descriptor, this reflective view conflicts jaroslav@1646: * with the normal presentation of these methods via bytecodes. jaroslav@1646: * Thus, these two native methods, when reflectively viewed by jaroslav@1646: * {@code Class.getDeclaredMethod}, may be regarded as placeholders only. jaroslav@1646: *

jaroslav@1646: * In order to obtain an invoker method for a particular type descriptor, jaroslav@1646: * use {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker}, jaroslav@1646: * or {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}. jaroslav@1646: * The {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual} jaroslav@1646: * API is also able to return a method handle jaroslav@1646: * to call {@code invokeExact} or plain {@code invoke}, jaroslav@1646: * for any specified type descriptor . jaroslav@1646: * jaroslav@1646: *

Interoperation between method handles and Java generics

jaroslav@1646: * A method handle can be obtained on a method, constructor, or field jaroslav@1646: * which is declared with Java generic types. jaroslav@1646: * As with the Core Reflection API, the type of the method handle jaroslav@1646: * will constructed from the erasure of the source-level type. jaroslav@1646: * When a method handle is invoked, the types of its arguments jaroslav@1646: * or the return value cast type may be generic types or type instances. jaroslav@1646: * If this occurs, the compiler will replace those jaroslav@1646: * types by their erasures when it constructs the symbolic type descriptor jaroslav@1646: * for the {@code invokevirtual} instruction. jaroslav@1646: *

jaroslav@1646: * Method handles do not represent jaroslav@1646: * their function-like types in terms of Java parameterized (generic) types, jaroslav@1646: * because there are three mismatches between function-like types and parameterized jaroslav@1646: * Java types. jaroslav@1646: *

jaroslav@1646: * jaroslav@1646: *

Arity limits

jaroslav@1646: * The JVM imposes on all methods and constructors of any kind an absolute jaroslav@1646: * limit of 255 stacked arguments. This limit can appear more restrictive jaroslav@1646: * in certain cases: jaroslav@1646: * jaroslav@1646: * These limits imply that certain method handles cannot be created, solely because of the JVM limit on stacked arguments. jaroslav@1646: * For example, if a static JVM method accepts exactly 255 arguments, a method handle cannot be created for it. jaroslav@1646: * Attempts to create method handles with impossible method types lead to an {@link IllegalArgumentException}. jaroslav@1646: * In particular, a method handle’s type must not have an arity of the exact maximum 255. jaroslav@1646: * jaroslav@1646: * @see MethodType jaroslav@1646: * @see MethodHandles jaroslav@1646: * @author John Rose, JSR 292 EG jaroslav@1646: */ jaroslav@1646: public abstract class MethodHandle { jaroslav@1646: static { MethodHandleImpl.initStatics(); } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Internal marker interface which distinguishes (to the Java compiler) jaroslav@1646: * those methods which are signature polymorphic. jaroslav@1646: */ jaroslav@1646: @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD}) jaroslav@1646: @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) jaroslav@1646: @interface PolymorphicSignature { } jaroslav@1646: jaroslav@1646: private final MethodType type; jaroslav@1646: /*private*/ final LambdaForm form; jaroslav@1646: // form is not private so that invokers can easily fetch it jaroslav@1646: /*private*/ MethodHandle asTypeCache; jaroslav@1646: // asTypeCache is not private so that invokers can easily fetch it jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Reports the type of this method handle. jaroslav@1646: * Every invocation of this method handle via {@code invokeExact} must exactly match this type. jaroslav@1646: * @return the method handle type jaroslav@1646: */ jaroslav@1646: public MethodType type() { jaroslav@1646: return type; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Package-private constructor for the method handle implementation hierarchy. jaroslav@1646: * Method handle inheritance will be contained completely within jaroslav@1646: * the {@code java.lang.invoke} package. jaroslav@1646: */ jaroslav@1646: // @param type type (permanently assigned) of the new method handle jaroslav@1646: /*non-public*/ MethodHandle(MethodType type, LambdaForm form) { jaroslav@1646: type.getClass(); // explicit NPE jaroslav@1646: form.getClass(); // explicit NPE jaroslav@1646: this.type = type; jaroslav@1646: this.form = form; jaroslav@1646: jaroslav@1646: form.prepare(); // TO DO: Try to delay this step until just before invocation. jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match. jaroslav@1646: * The symbolic type descriptor at the call site of {@code invokeExact} must jaroslav@1646: * exactly match this method handle's {@link #type type}. jaroslav@1646: * No conversions are allowed on arguments or return values. jaroslav@1646: *

jaroslav@1646: * When this method is observed via the Core Reflection API, jaroslav@1646: * it will appear as a single native method, taking an object array and returning an object. jaroslav@1646: * If this native method is invoked directly via jaroslav@1646: * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI, jaroslav@1646: * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}, jaroslav@1646: * it will throw an {@code UnsupportedOperationException}. jaroslav@1646: * @param args the signature-polymorphic parameter list, statically represented using varargs jaroslav@1646: * @return the signature-polymorphic result, statically represented using {@code Object} jaroslav@1646: * @throws WrongMethodTypeException if the target's type is not identical with the caller's symbolic type descriptor jaroslav@1646: * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call jaroslav@1646: */ jaroslav@1646: public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable; jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Invokes the method handle, allowing any caller type descriptor, jaroslav@1646: * and optionally performing conversions on arguments and return values. jaroslav@1646: *

jaroslav@1646: * If the call site's symbolic type descriptor exactly matches this method handle's {@link #type type}, jaroslav@1646: * the call proceeds as if by {@link #invokeExact invokeExact}. jaroslav@1646: *

jaroslav@1646: * Otherwise, the call proceeds as if this method handle were first jaroslav@1646: * adjusted by calling {@link #asType asType} to adjust this method handle jaroslav@1646: * to the required type, and then the call proceeds as if by jaroslav@1646: * {@link #invokeExact invokeExact} on the adjusted method handle. jaroslav@1646: *

jaroslav@1646: * There is no guarantee that the {@code asType} call is actually made. jaroslav@1646: * If the JVM can predict the results of making the call, it may perform jaroslav@1646: * adaptations directly on the caller's arguments, jaroslav@1646: * and call the target method handle according to its own exact type. jaroslav@1646: *

jaroslav@1646: * The resolved type descriptor at the call site of {@code invoke} must jaroslav@1646: * be a valid argument to the receivers {@code asType} method. jaroslav@1646: * In particular, the caller must specify the same argument arity jaroslav@1646: * as the callee's type, jaroslav@1646: * if the callee is not a {@linkplain #asVarargsCollector variable arity collector}. jaroslav@1646: *

jaroslav@1646: * When this method is observed via the Core Reflection API, jaroslav@1646: * it will appear as a single native method, taking an object array and returning an object. jaroslav@1646: * If this native method is invoked directly via jaroslav@1646: * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI, jaroslav@1646: * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}, jaroslav@1646: * it will throw an {@code UnsupportedOperationException}. jaroslav@1646: * @param args the signature-polymorphic parameter list, statically represented using varargs jaroslav@1646: * @return the signature-polymorphic result, statically represented using {@code Object} jaroslav@1646: * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's symbolic type descriptor jaroslav@1646: * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails jaroslav@1646: * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call jaroslav@1646: */ jaroslav@1646: public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable; jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Private method for trusted invocation of a method handle respecting simplified signatures. jaroslav@1646: * Type mismatches will not throw {@code WrongMethodTypeException}, but could crash the JVM. jaroslav@1646: *

jaroslav@1646: * The caller signature is restricted to the following basic types: jaroslav@1646: * Object, int, long, float, double, and void return. jaroslav@1646: *

jaroslav@1646: * The caller is responsible for maintaining type correctness by ensuring jaroslav@1646: * that the each outgoing argument value is a member of the range of the corresponding jaroslav@1646: * callee argument type. jaroslav@1646: * (The caller should therefore issue appropriate casts and integer narrowing jaroslav@1646: * operations on outgoing argument values.) jaroslav@1646: * The caller can assume that the incoming result value is part of the range jaroslav@1646: * of the callee's return type. jaroslav@1646: * @param args the signature-polymorphic parameter list, statically represented using varargs jaroslav@1646: * @return the signature-polymorphic result, statically represented using {@code Object} jaroslav@1646: */ jaroslav@1646: /*non-public*/ final native @PolymorphicSignature Object invokeBasic(Object... args) throws Throwable; jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Private method for trusted invocation of a MemberName of kind {@code REF_invokeVirtual}. jaroslav@1646: * The caller signature is restricted to basic types as with {@code invokeBasic}. jaroslav@1646: * The trailing (not leading) argument must be a MemberName. jaroslav@1646: * @param args the signature-polymorphic parameter list, statically represented using varargs jaroslav@1646: * @return the signature-polymorphic result, statically represented using {@code Object} jaroslav@1646: */ jaroslav@1646: /*non-public*/ static native @PolymorphicSignature Object linkToVirtual(Object... args) throws Throwable; jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Private method for trusted invocation of a MemberName of kind {@code REF_invokeStatic}. jaroslav@1646: * The caller signature is restricted to basic types as with {@code invokeBasic}. jaroslav@1646: * The trailing (not leading) argument must be a MemberName. jaroslav@1646: * @param args the signature-polymorphic parameter list, statically represented using varargs jaroslav@1646: * @return the signature-polymorphic result, statically represented using {@code Object} jaroslav@1646: */ jaroslav@1646: /*non-public*/ static native @PolymorphicSignature Object linkToStatic(Object... args) throws Throwable; jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Private method for trusted invocation of a MemberName of kind {@code REF_invokeSpecial}. jaroslav@1646: * The caller signature is restricted to basic types as with {@code invokeBasic}. jaroslav@1646: * The trailing (not leading) argument must be a MemberName. jaroslav@1646: * @param args the signature-polymorphic parameter list, statically represented using varargs jaroslav@1646: * @return the signature-polymorphic result, statically represented using {@code Object} jaroslav@1646: */ jaroslav@1646: /*non-public*/ static native @PolymorphicSignature Object linkToSpecial(Object... args) throws Throwable; jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Private method for trusted invocation of a MemberName of kind {@code REF_invokeInterface}. jaroslav@1646: * The caller signature is restricted to basic types as with {@code invokeBasic}. jaroslav@1646: * The trailing (not leading) argument must be a MemberName. jaroslav@1646: * @param args the signature-polymorphic parameter list, statically represented using varargs jaroslav@1646: * @return the signature-polymorphic result, statically represented using {@code Object} jaroslav@1646: */ jaroslav@1646: /*non-public*/ static native @PolymorphicSignature Object linkToInterface(Object... args) throws Throwable; jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Performs a variable arity invocation, passing the arguments in the given list jaroslav@1646: * to the method handle, as if via an inexact {@link #invoke invoke} from a call site jaroslav@1646: * which mentions only the type {@code Object}, and whose arity is the length jaroslav@1646: * of the argument list. jaroslav@1646: *

jaroslav@1646: * Specifically, execution proceeds as if by the following steps, jaroslav@1646: * although the methods are not guaranteed to be called if the JVM jaroslav@1646: * can predict their effects. jaroslav@1646: *

jaroslav@1646: *

jaroslav@1646: * Because of the action of the {@code asType} step, the following argument jaroslav@1646: * conversions are applied as necessary: jaroslav@1646: *

jaroslav@1646: *

jaroslav@1646: * The result returned by the call is boxed if it is a primitive, jaroslav@1646: * or forced to null if the return type is void. jaroslav@1646: *

jaroslav@1646: * This call is equivalent to the following code: jaroslav@1646: *

{@code
jaroslav@1646:      * MethodHandle invoker = MethodHandles.spreadInvoker(this.type(), 0);
jaroslav@1646:      * Object result = invoker.invokeExact(this, arguments);
jaroslav@1646:      * }
jaroslav@1646: *

jaroslav@1646: * Unlike the signature polymorphic methods {@code invokeExact} and {@code invoke}, jaroslav@1646: * {@code invokeWithArguments} can be accessed normally via the Core Reflection API and JNI. jaroslav@1646: * It can therefore be used as a bridge between native or reflective code and method handles. jaroslav@1646: * jaroslav@1646: * @param arguments the arguments to pass to the target jaroslav@1646: * @return the result returned by the target jaroslav@1646: * @throws ClassCastException if an argument cannot be converted by reference casting jaroslav@1646: * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments jaroslav@1646: * @throws Throwable anything thrown by the target method invocation jaroslav@1646: * @see MethodHandles#spreadInvoker jaroslav@1646: */ jaroslav@1646: public Object invokeWithArguments(Object... arguments) throws Throwable { jaroslav@1646: int argc = arguments == null ? 0 : arguments.length; jaroslav@1646: @SuppressWarnings("LocalVariableHidesMemberVariable") jaroslav@1646: MethodType type = type(); jaroslav@1646: if (type.parameterCount() != argc || isVarargsCollector()) { jaroslav@1646: // simulate invoke jaroslav@1646: return asType(MethodType.genericMethodType(argc)).invokeWithArguments(arguments); jaroslav@1646: } jaroslav@1646: MethodHandle invoker = type.invokers().varargsInvoker(); jaroslav@1646: return invoker.invokeExact(this, arguments); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Performs a variable arity invocation, passing the arguments in the given array jaroslav@1646: * to the method handle, as if via an inexact {@link #invoke invoke} from a call site jaroslav@1646: * which mentions only the type {@code Object}, and whose arity is the length jaroslav@1646: * of the argument array. jaroslav@1646: *

jaroslav@1646: * This method is also equivalent to the following code: jaroslav@1646: *

{@code
jaroslav@1646:      *   invokeWithArguments(arguments.toArray()
jaroslav@1646:      * }
jaroslav@1646: * jaroslav@1646: * @param arguments the arguments to pass to the target jaroslav@1646: * @return the result returned by the target jaroslav@1646: * @throws NullPointerException if {@code arguments} is a null reference jaroslav@1646: * @throws ClassCastException if an argument cannot be converted by reference casting jaroslav@1646: * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments jaroslav@1646: * @throws Throwable anything thrown by the target method invocation jaroslav@1646: */ jaroslav@1646: public Object invokeWithArguments(java.util.List arguments) throws Throwable { jaroslav@1646: return invokeWithArguments(arguments.toArray()); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Produces an adapter method handle which adapts the type of the jaroslav@1646: * current method handle to a new type. jaroslav@1646: * The resulting method handle is guaranteed to report a type jaroslav@1646: * which is equal to the desired new type. jaroslav@1646: *

jaroslav@1646: * If the original type and new type are equal, returns {@code this}. jaroslav@1646: *

jaroslav@1646: * The new method handle, when invoked, will perform the following jaroslav@1646: * steps: jaroslav@1646: *

jaroslav@1646: *

jaroslav@1646: * This method provides the crucial behavioral difference between jaroslav@1646: * {@link #invokeExact invokeExact} and plain, inexact {@link #invoke invoke}. jaroslav@1646: * The two methods jaroslav@1646: * perform the same steps when the caller's type descriptor exactly m atches jaroslav@1646: * the callee's, but when the types differ, plain {@link #invoke invoke} jaroslav@1646: * also calls {@code asType} (or some internal equivalent) in order jaroslav@1646: * to match up the caller's and callee's types. jaroslav@1646: *

jaroslav@1646: * If the current method is a variable arity method handle jaroslav@1646: * argument list conversion may involve the conversion and collection jaroslav@1646: * of several arguments into an array, as jaroslav@1646: * {@linkplain #asVarargsCollector described elsewhere}. jaroslav@1646: * In every other case, all conversions are applied pairwise, jaroslav@1646: * which means that each argument or return value is converted to jaroslav@1646: * exactly one argument or return value (or no return value). jaroslav@1646: * The applied conversions are defined by consulting the jaroslav@1646: * the corresponding component types of the old and new jaroslav@1646: * method handle types. jaroslav@1646: *

jaroslav@1646: * Let T0 and T1 be corresponding new and old parameter types, jaroslav@1646: * or old and new return types. Specifically, for some valid index {@code i}, let jaroslav@1646: * T0{@code =newType.parameterType(i)} and T1{@code =this.type().parameterType(i)}. jaroslav@1646: * Or else, going the other way for return values, let jaroslav@1646: * T0{@code =this.type().returnType()} and T1{@code =newType.returnType()}. jaroslav@1646: * If the types are the same, the new method handle makes no change jaroslav@1646: * to the corresponding argument or return value (if any). jaroslav@1646: * Otherwise, one of the following conversions is applied jaroslav@1646: * if possible: jaroslav@1646: *

jaroslav@1646: * (Note: Both T0 and T1 may be regarded as static types, jaroslav@1646: * because neither corresponds specifically to the dynamic type of any jaroslav@1646: * actual argument or return value.) jaroslav@1646: *

jaroslav@1646: * The method handle conversion cannot be made if any one of the required jaroslav@1646: * pairwise conversions cannot be made. jaroslav@1646: *

jaroslav@1646: * At runtime, the conversions applied to reference arguments jaroslav@1646: * or return values may require additional runtime checks which can fail. jaroslav@1646: * An unboxing operation may fail because the original reference is null, jaroslav@1646: * causing a {@link java.lang.NullPointerException NullPointerException}. jaroslav@1646: * An unboxing operation or a reference cast may also fail on a reference jaroslav@1646: * to an object of the wrong type, jaroslav@1646: * causing a {@link java.lang.ClassCastException ClassCastException}. jaroslav@1646: * Although an unboxing operation may accept several kinds of wrappers, jaroslav@1646: * if none are available, a {@code ClassCastException} will be thrown. jaroslav@1646: * jaroslav@1646: * @param newType the expected type of the new method handle jaroslav@1646: * @return a method handle which delegates to {@code this} after performing jaroslav@1646: * any necessary argument conversions, and arranges for any jaroslav@1646: * necessary return value conversions jaroslav@1646: * @throws NullPointerException if {@code newType} is a null reference jaroslav@1646: * @throws WrongMethodTypeException if the conversion cannot be made jaroslav@1646: * @see MethodHandles#explicitCastArguments jaroslav@1646: */ jaroslav@1646: public MethodHandle asType(MethodType newType) { jaroslav@1646: // Fast path alternative to a heavyweight {@code asType} call. jaroslav@1646: // Return 'this' if the conversion will be a no-op. jaroslav@1646: if (newType == type) { jaroslav@1646: return this; jaroslav@1646: } jaroslav@1646: // Return 'this.asTypeCache' if the conversion is already memoized. jaroslav@1646: MethodHandle atc = asTypeCache; jaroslav@1646: if (atc != null && newType == atc.type) { jaroslav@1646: return atc; jaroslav@1646: } jaroslav@1646: return asTypeUncached(newType); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** Override this to change asType behavior. */ jaroslav@1646: /*non-public*/ MethodHandle asTypeUncached(MethodType newType) { jaroslav@1646: if (!type.isConvertibleTo(newType)) jaroslav@1646: throw new WrongMethodTypeException("cannot convert "+this+" to "+newType); jaroslav@1646: return asTypeCache = convertArguments(newType); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Makes an array-spreading method handle, which accepts a trailing array argument jaroslav@1646: * and spreads its elements as positional arguments. jaroslav@1646: * The new method handle adapts, as its target, jaroslav@1646: * the current method handle. The type of the adapter will be jaroslav@1646: * the same as the type of the target, except that the final jaroslav@1646: * {@code arrayLength} parameters of the target's type are replaced jaroslav@1646: * by a single array parameter of type {@code arrayType}. jaroslav@1646: *

jaroslav@1646: * If the array element type differs from any of the corresponding jaroslav@1646: * argument types on the original target, jaroslav@1646: * the original target is adapted to take the array elements directly, jaroslav@1646: * as if by a call to {@link #asType asType}. jaroslav@1646: *

jaroslav@1646: * When called, the adapter replaces a trailing array argument jaroslav@1646: * by the array's elements, each as its own argument to the target. jaroslav@1646: * (The order of the arguments is preserved.) jaroslav@1646: * They are converted pairwise by casting and/or unboxing jaroslav@1646: * to the types of the trailing parameters of the target. jaroslav@1646: * Finally the target is called. jaroslav@1646: * What the target eventually returns is returned unchanged by the adapter. jaroslav@1646: *

jaroslav@1646: * Before calling the target, the adapter verifies that the array jaroslav@1646: * contains exactly enough elements to provide a correct argument count jaroslav@1646: * to the target method handle. jaroslav@1646: * (The array may also be null when zero elements are required.) jaroslav@1646: *

jaroslav@1646: * If, when the adapter is called, the supplied array argument does jaroslav@1646: * not have the correct number of elements, the adapter will throw jaroslav@1646: * an {@link IllegalArgumentException} instead of invoking the target. jaroslav@1646: *

jaroslav@1646: * Here are some simple examples of array-spreading method handles: jaroslav@1646: *

{@code
jaroslav@1646: MethodHandle equals = publicLookup()
jaroslav@1646:   .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
jaroslav@1646: assert( (boolean) equals.invokeExact("me", (Object)"me"));
jaroslav@1646: assert(!(boolean) equals.invokeExact("me", (Object)"thee"));
jaroslav@1646: // spread both arguments from a 2-array:
jaroslav@1646: MethodHandle eq2 = equals.asSpreader(Object[].class, 2);
jaroslav@1646: assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" }));
jaroslav@1646: assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
jaroslav@1646: // try to spread from anything but a 2-array:
jaroslav@1646: for (int n = 0; n <= 10; n++) {
jaroslav@1646:   Object[] badArityArgs = (n == 2 ? null : new Object[n]);
jaroslav@1646:   try { assert((boolean) eq2.invokeExact(badArityArgs) && false); }
jaroslav@1646:   catch (IllegalArgumentException ex) { } // OK
jaroslav@1646: }
jaroslav@1646: // spread both arguments from a String array:
jaroslav@1646: MethodHandle eq2s = equals.asSpreader(String[].class, 2);
jaroslav@1646: assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" }));
jaroslav@1646: assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" }));
jaroslav@1646: // spread second arguments from a 1-array:
jaroslav@1646: MethodHandle eq1 = equals.asSpreader(Object[].class, 1);
jaroslav@1646: assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" }));
jaroslav@1646: assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" }));
jaroslav@1646: // spread no arguments from a 0-array or null:
jaroslav@1646: MethodHandle eq0 = equals.asSpreader(Object[].class, 0);
jaroslav@1646: assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0]));
jaroslav@1646: assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null));
jaroslav@1646: // asSpreader and asCollector are approximate inverses:
jaroslav@1646: for (int n = 0; n <= 2; n++) {
jaroslav@1646:     for (Class a : new Class[]{Object[].class, String[].class, CharSequence[].class}) {
jaroslav@1646:         MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n);
jaroslav@1646:         assert( (boolean) equals2.invokeWithArguments("me", "me"));
jaroslav@1646:         assert(!(boolean) equals2.invokeWithArguments("me", "thee"));
jaroslav@1646:     }
jaroslav@1646: }
jaroslav@1646: MethodHandle caToString = publicLookup()
jaroslav@1646:   .findStatic(Arrays.class, "toString", methodType(String.class, char[].class));
jaroslav@1646: assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray()));
jaroslav@1646: MethodHandle caString3 = caToString.asCollector(char[].class, 3);
jaroslav@1646: assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
jaroslav@1646: MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
jaroslav@1646: assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
jaroslav@1646:      * }
jaroslav@1646: * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments jaroslav@1646: * @param arrayLength the number of arguments to spread from an incoming array argument jaroslav@1646: * @return a new method handle which spreads its final array argument, jaroslav@1646: * before calling the original method handle jaroslav@1646: * @throws NullPointerException if {@code arrayType} is a null reference jaroslav@1646: * @throws IllegalArgumentException if {@code arrayType} is not an array type, jaroslav@1646: * or if target does not have at least jaroslav@1646: * {@code arrayLength} parameter types, jaroslav@1646: * or if {@code arrayLength} is negative, jaroslav@1646: * or if the resulting method handle's type would have jaroslav@1646: * too many parameters jaroslav@1646: * @throws WrongMethodTypeException if the implied {@code asType} call fails jaroslav@1646: * @see #asCollector jaroslav@1646: */ jaroslav@1646: public MethodHandle asSpreader(Class arrayType, int arrayLength) { jaroslav@1646: asSpreaderChecks(arrayType, arrayLength); jaroslav@1646: int spreadArgPos = type.parameterCount() - arrayLength; jaroslav@1646: return MethodHandleImpl.makeSpreadArguments(this, arrayType, spreadArgPos, arrayLength); jaroslav@1646: } jaroslav@1646: jaroslav@1646: private void asSpreaderChecks(Class arrayType, int arrayLength) { jaroslav@1646: spreadArrayChecks(arrayType, arrayLength); jaroslav@1646: int nargs = type().parameterCount(); jaroslav@1646: if (nargs < arrayLength || arrayLength < 0) jaroslav@1646: throw newIllegalArgumentException("bad spread array length"); jaroslav@1646: if (arrayType != Object[].class && arrayLength != 0) { jaroslav@1646: boolean sawProblem = false; jaroslav@1646: Class arrayElement = arrayType.getComponentType(); jaroslav@1646: for (int i = nargs - arrayLength; i < nargs; i++) { jaroslav@1646: if (!MethodType.canConvert(arrayElement, type().parameterType(i))) { jaroslav@1646: sawProblem = true; jaroslav@1646: break; jaroslav@1646: } jaroslav@1646: } jaroslav@1646: if (sawProblem) { jaroslav@1646: ArrayList> ptypes = new ArrayList<>(type().parameterList()); jaroslav@1646: for (int i = nargs - arrayLength; i < nargs; i++) { jaroslav@1646: ptypes.set(i, arrayElement); jaroslav@1646: } jaroslav@1646: // elicit an error: jaroslav@1646: this.asType(MethodType.methodType(type().returnType(), ptypes)); jaroslav@1646: } jaroslav@1646: } jaroslav@1646: } jaroslav@1646: jaroslav@1646: private void spreadArrayChecks(Class arrayType, int arrayLength) { jaroslav@1646: Class arrayElement = arrayType.getComponentType(); jaroslav@1646: if (arrayElement == null) jaroslav@1646: throw newIllegalArgumentException("not an array type", arrayType); jaroslav@1646: if ((arrayLength & 0x7F) != arrayLength) { jaroslav@1646: if ((arrayLength & 0xFF) != arrayLength) jaroslav@1646: throw newIllegalArgumentException("array length is not legal", arrayLength); jaroslav@1646: assert(arrayLength >= 128); jaroslav@1646: if (arrayElement == long.class || jaroslav@1646: arrayElement == double.class) jaroslav@1646: throw newIllegalArgumentException("array length is not legal for long[] or double[]", arrayLength); jaroslav@1646: } jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Makes an array-collecting method handle, which accepts a given number of trailing jaroslav@1646: * positional arguments and collects them into an array argument. jaroslav@1646: * The new method handle adapts, as its target, jaroslav@1646: * the current method handle. The type of the adapter will be jaroslav@1646: * the same as the type of the target, except that a single trailing jaroslav@1646: * parameter (usually of type {@code arrayType}) is replaced by jaroslav@1646: * {@code arrayLength} parameters whose type is element type of {@code arrayType}. jaroslav@1646: *

jaroslav@1646: * If the array type differs from the final argument type on the original target, jaroslav@1646: * the original target is adapted to take the array type directly, jaroslav@1646: * as if by a call to {@link #asType asType}. jaroslav@1646: *

jaroslav@1646: * When called, the adapter replaces its trailing {@code arrayLength} jaroslav@1646: * arguments by a single new array of type {@code arrayType}, whose elements jaroslav@1646: * comprise (in order) the replaced arguments. jaroslav@1646: * Finally the target is called. jaroslav@1646: * What the target eventually returns is returned unchanged by the adapter. jaroslav@1646: *

jaroslav@1646: * (The array may also be a shared constant when {@code arrayLength} is zero.) jaroslav@1646: *

jaroslav@1646: * (Note: The {@code arrayType} is often identical to the last jaroslav@1646: * parameter type of the original target. jaroslav@1646: * It is an explicit argument for symmetry with {@code asSpreader}, and also jaroslav@1646: * to allow the target to use a simple {@code Object} as its last parameter type.) jaroslav@1646: *

jaroslav@1646: * In order to create a collecting adapter which is not restricted to a particular jaroslav@1646: * number of collected arguments, use {@link #asVarargsCollector asVarargsCollector} instead. jaroslav@1646: *

jaroslav@1646: * Here are some examples of array-collecting method handles: jaroslav@1646: *

{@code
jaroslav@1646: MethodHandle deepToString = publicLookup()
jaroslav@1646:   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
jaroslav@1646: assertEquals("[won]",   (String) deepToString.invokeExact(new Object[]{"won"}));
jaroslav@1646: MethodHandle ts1 = deepToString.asCollector(Object[].class, 1);
jaroslav@1646: assertEquals(methodType(String.class, Object.class), ts1.type());
jaroslav@1646: //assertEquals("[won]", (String) ts1.invokeExact(         new Object[]{"won"})); //FAIL
jaroslav@1646: assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"}));
jaroslav@1646: // arrayType can be a subtype of Object[]
jaroslav@1646: MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
jaroslav@1646: assertEquals(methodType(String.class, String.class, String.class), ts2.type());
jaroslav@1646: assertEquals("[two, too]", (String) ts2.invokeExact("two", "too"));
jaroslav@1646: MethodHandle ts0 = deepToString.asCollector(Object[].class, 0);
jaroslav@1646: assertEquals("[]", (String) ts0.invokeExact());
jaroslav@1646: // collectors can be nested, Lisp-style
jaroslav@1646: MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2);
jaroslav@1646: assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D")));
jaroslav@1646: // arrayType can be any primitive array type
jaroslav@1646: MethodHandle bytesToString = publicLookup()
jaroslav@1646:   .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class))
jaroslav@1646:   .asCollector(byte[].class, 3);
jaroslav@1646: assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3));
jaroslav@1646: MethodHandle longsToString = publicLookup()
jaroslav@1646:   .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
jaroslav@1646:   .asCollector(long[].class, 1);
jaroslav@1646: assertEquals("[123]", (String) longsToString.invokeExact((long)123));
jaroslav@1646:      * }
jaroslav@1646: * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments jaroslav@1646: * @param arrayLength the number of arguments to collect into a new array argument jaroslav@1646: * @return a new method handle which collects some trailing argument jaroslav@1646: * into an array, before calling the original method handle jaroslav@1646: * @throws NullPointerException if {@code arrayType} is a null reference jaroslav@1646: * @throws IllegalArgumentException if {@code arrayType} is not an array type jaroslav@1646: * or {@code arrayType} is not assignable to this method handle's trailing parameter type, jaroslav@1646: * or {@code arrayLength} is not a legal array size, jaroslav@1646: * or the resulting method handle's type would have jaroslav@1646: * too many parameters jaroslav@1646: * @throws WrongMethodTypeException if the implied {@code asType} call fails jaroslav@1646: * @see #asSpreader jaroslav@1646: * @see #asVarargsCollector jaroslav@1646: */ jaroslav@1646: public MethodHandle asCollector(Class arrayType, int arrayLength) { jaroslav@1646: asCollectorChecks(arrayType, arrayLength); jaroslav@1646: int collectArgPos = type().parameterCount()-1; jaroslav@1646: MethodHandle target = this; jaroslav@1646: if (arrayType != type().parameterType(collectArgPos)) jaroslav@1646: target = convertArguments(type().changeParameterType(collectArgPos, arrayType)); jaroslav@1646: MethodHandle collector = ValueConversions.varargsArray(arrayType, arrayLength); jaroslav@1646: return MethodHandles.collectArguments(target, collectArgPos, collector); jaroslav@1646: } jaroslav@1646: jaroslav@1646: // private API: return true if last param exactly matches arrayType jaroslav@1646: private boolean asCollectorChecks(Class arrayType, int arrayLength) { jaroslav@1646: spreadArrayChecks(arrayType, arrayLength); jaroslav@1646: int nargs = type().parameterCount(); jaroslav@1646: if (nargs != 0) { jaroslav@1646: Class lastParam = type().parameterType(nargs-1); jaroslav@1646: if (lastParam == arrayType) return true; jaroslav@1646: if (lastParam.isAssignableFrom(arrayType)) return false; jaroslav@1646: } jaroslav@1646: throw newIllegalArgumentException("array type not assignable to trailing argument", this, arrayType); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Makes a variable arity adapter which is able to accept jaroslav@1646: * any number of trailing positional arguments and collect them jaroslav@1646: * into an array argument. jaroslav@1646: *

jaroslav@1646: * The type and behavior of the adapter will be the same as jaroslav@1646: * the type and behavior of the target, except that certain jaroslav@1646: * {@code invoke} and {@code asType} requests can lead to jaroslav@1646: * trailing positional arguments being collected into target's jaroslav@1646: * trailing parameter. jaroslav@1646: * Also, the last parameter type of the adapter will be jaroslav@1646: * {@code arrayType}, even if the target has a different jaroslav@1646: * last parameter type. jaroslav@1646: *

jaroslav@1646: * This transformation may return {@code this} if the method handle is jaroslav@1646: * already of variable arity and its trailing parameter type jaroslav@1646: * is identical to {@code arrayType}. jaroslav@1646: *

jaroslav@1646: * When called with {@link #invokeExact invokeExact}, the adapter invokes jaroslav@1646: * the target with no argument changes. jaroslav@1646: * (Note: This behavior is different from a jaroslav@1646: * {@linkplain #asCollector fixed arity collector}, jaroslav@1646: * since it accepts a whole array of indeterminate length, jaroslav@1646: * rather than a fixed number of arguments.) jaroslav@1646: *

jaroslav@1646: * When called with plain, inexact {@link #invoke invoke}, if the caller jaroslav@1646: * type is the same as the adapter, the adapter invokes the target as with jaroslav@1646: * {@code invokeExact}. jaroslav@1646: * (This is the normal behavior for {@code invoke} when types match.) jaroslav@1646: *

jaroslav@1646: * Otherwise, if the caller and adapter arity are the same, and the jaroslav@1646: * trailing parameter type of the caller is a reference type identical to jaroslav@1646: * or assignable to the trailing parameter type of the adapter, jaroslav@1646: * the arguments and return values are converted pairwise, jaroslav@1646: * as if by {@link #asType asType} on a fixed arity jaroslav@1646: * method handle. jaroslav@1646: *

jaroslav@1646: * Otherwise, the arities differ, or the adapter's trailing parameter jaroslav@1646: * type is not assignable from the corresponding caller type. jaroslav@1646: * In this case, the adapter replaces all trailing arguments from jaroslav@1646: * the original trailing argument position onward, by jaroslav@1646: * a new array of type {@code arrayType}, whose elements jaroslav@1646: * comprise (in order) the replaced arguments. jaroslav@1646: *

jaroslav@1646: * The caller type must provides as least enough arguments, jaroslav@1646: * and of the correct type, to satisfy the target's requirement for jaroslav@1646: * positional arguments before the trailing array argument. jaroslav@1646: * Thus, the caller must supply, at a minimum, {@code N-1} arguments, jaroslav@1646: * where {@code N} is the arity of the target. jaroslav@1646: * Also, there must exist conversions from the incoming arguments jaroslav@1646: * to the target's arguments. jaroslav@1646: * As with other uses of plain {@code invoke}, if these basic jaroslav@1646: * requirements are not fulfilled, a {@code WrongMethodTypeException} jaroslav@1646: * may be thrown. jaroslav@1646: *

jaroslav@1646: * In all cases, what the target eventually returns is returned unchanged by the adapter. jaroslav@1646: *

jaroslav@1646: * In the final case, it is exactly as if the target method handle were jaroslav@1646: * temporarily adapted with a {@linkplain #asCollector fixed arity collector} jaroslav@1646: * to the arity required by the caller type. jaroslav@1646: * (As with {@code asCollector}, if the array length is zero, jaroslav@1646: * a shared constant may be used instead of a new array. jaroslav@1646: * If the implied call to {@code asCollector} would throw jaroslav@1646: * an {@code IllegalArgumentException} or {@code WrongMethodTypeException}, jaroslav@1646: * the call to the variable arity adapter must throw jaroslav@1646: * {@code WrongMethodTypeException}.) jaroslav@1646: *

jaroslav@1646: * The behavior of {@link #asType asType} is also specialized for jaroslav@1646: * variable arity adapters, to maintain the invariant that jaroslav@1646: * plain, inexact {@code invoke} is always equivalent to an {@code asType} jaroslav@1646: * call to adjust the target type, followed by {@code invokeExact}. jaroslav@1646: * Therefore, a variable arity adapter responds jaroslav@1646: * to an {@code asType} request by building a fixed arity collector, jaroslav@1646: * if and only if the adapter and requested type differ either jaroslav@1646: * in arity or trailing argument type. jaroslav@1646: * The resulting fixed arity collector has its type further adjusted jaroslav@1646: * (if necessary) to the requested type by pairwise conversion, jaroslav@1646: * as if by another application of {@code asType}. jaroslav@1646: *

jaroslav@1646: * When a method handle is obtained by executing an {@code ldc} instruction jaroslav@1646: * of a {@code CONSTANT_MethodHandle} constant, and the target method is marked jaroslav@1646: * as a variable arity method (with the modifier bit {@code 0x0080}), jaroslav@1646: * the method handle will accept multiple arities, as if the method handle jaroslav@1646: * constant were created by means of a call to {@code asVarargsCollector}. jaroslav@1646: *

jaroslav@1646: * In order to create a collecting adapter which collects a predetermined jaroslav@1646: * number of arguments, and whose type reflects this predetermined number, jaroslav@1646: * use {@link #asCollector asCollector} instead. jaroslav@1646: *

jaroslav@1646: * No method handle transformations produce new method handles with jaroslav@1646: * variable arity, unless they are documented as doing so. jaroslav@1646: * Therefore, besides {@code asVarargsCollector}, jaroslav@1646: * all methods in {@code MethodHandle} and {@code MethodHandles} jaroslav@1646: * will return a method handle with fixed arity, jaroslav@1646: * except in the cases where they are specified to return their original jaroslav@1646: * operand (e.g., {@code asType} of the method handle's own type). jaroslav@1646: *

jaroslav@1646: * Calling {@code asVarargsCollector} on a method handle which is already jaroslav@1646: * of variable arity will produce a method handle with the same type and behavior. jaroslav@1646: * It may (or may not) return the original variable arity method handle. jaroslav@1646: *

jaroslav@1646: * Here is an example, of a list-making variable arity method handle: jaroslav@1646: *

{@code
jaroslav@1646: MethodHandle deepToString = publicLookup()
jaroslav@1646:   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
jaroslav@1646: MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
jaroslav@1646: assertEquals("[won]",   (String) ts1.invokeExact(    new Object[]{"won"}));
jaroslav@1646: assertEquals("[won]",   (String) ts1.invoke(         new Object[]{"won"}));
jaroslav@1646: assertEquals("[won]",   (String) ts1.invoke(                      "won" ));
jaroslav@1646: assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"}));
jaroslav@1646: // findStatic of Arrays.asList(...) produces a variable arity method handle:
jaroslav@1646: MethodHandle asList = publicLookup()
jaroslav@1646:   .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
jaroslav@1646: assertEquals(methodType(List.class, Object[].class), asList.type());
jaroslav@1646: assert(asList.isVarargsCollector());
jaroslav@1646: assertEquals("[]", asList.invoke().toString());
jaroslav@1646: assertEquals("[1]", asList.invoke(1).toString());
jaroslav@1646: assertEquals("[two, too]", asList.invoke("two", "too").toString());
jaroslav@1646: String[] argv = { "three", "thee", "tee" };
jaroslav@1646: assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
jaroslav@1646: assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString());
jaroslav@1646: List ls = (List) asList.invoke((Object)argv);
jaroslav@1646: assertEquals(1, ls.size());
jaroslav@1646: assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
jaroslav@1646:      * }
jaroslav@1646: *

jaroslav@1646: * Discussion: jaroslav@1646: * These rules are designed as a dynamically-typed variation jaroslav@1646: * of the Java rules for variable arity methods. jaroslav@1646: * In both cases, callers to a variable arity method or method handle jaroslav@1646: * can either pass zero or more positional arguments, or else pass jaroslav@1646: * pre-collected arrays of any length. Users should be aware of the jaroslav@1646: * special role of the final argument, and of the effect of a jaroslav@1646: * type match on that final argument, which determines whether jaroslav@1646: * or not a single trailing argument is interpreted as a whole jaroslav@1646: * array or a single element of an array to be collected. jaroslav@1646: * Note that the dynamic type of the trailing argument has no jaroslav@1646: * effect on this decision, only a comparison between the symbolic jaroslav@1646: * type descriptor of the call site and the type descriptor of the method handle.) jaroslav@1646: * jaroslav@1646: * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments jaroslav@1646: * @return a new method handle which can collect any number of trailing arguments jaroslav@1646: * into an array, before calling the original method handle jaroslav@1646: * @throws NullPointerException if {@code arrayType} is a null reference jaroslav@1646: * @throws IllegalArgumentException if {@code arrayType} is not an array type jaroslav@1646: * or {@code arrayType} is not assignable to this method handle's trailing parameter type jaroslav@1646: * @see #asCollector jaroslav@1646: * @see #isVarargsCollector jaroslav@1646: * @see #asFixedArity jaroslav@1646: */ jaroslav@1646: public MethodHandle asVarargsCollector(Class arrayType) { jaroslav@1646: Class arrayElement = arrayType.getComponentType(); jaroslav@1646: boolean lastMatch = asCollectorChecks(arrayType, 0); jaroslav@1646: if (isVarargsCollector() && lastMatch) jaroslav@1646: return this; jaroslav@1646: return MethodHandleImpl.makeVarargsCollector(this, arrayType); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Determines if this method handle jaroslav@1646: * supports {@linkplain #asVarargsCollector variable arity} calls. jaroslav@1646: * Such method handles arise from the following sources: jaroslav@1646: *

jaroslav@1646: * @return true if this method handle accepts more than one arity of plain, inexact {@code invoke} calls jaroslav@1646: * @see #asVarargsCollector jaroslav@1646: * @see #asFixedArity jaroslav@1646: */ jaroslav@1646: public boolean isVarargsCollector() { jaroslav@1646: return false; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Makes a fixed arity method handle which is otherwise jaroslav@1646: * equivalent to the current method handle. jaroslav@1646: *

jaroslav@1646: * If the current method handle is not of jaroslav@1646: * {@linkplain #asVarargsCollector variable arity}, jaroslav@1646: * the current method handle is returned. jaroslav@1646: * This is true even if the current method handle jaroslav@1646: * could not be a valid input to {@code asVarargsCollector}. jaroslav@1646: *

jaroslav@1646: * Otherwise, the resulting fixed-arity method handle has the same jaroslav@1646: * type and behavior of the current method handle, jaroslav@1646: * except that {@link #isVarargsCollector isVarargsCollector} jaroslav@1646: * will be false. jaroslav@1646: * The fixed-arity method handle may (or may not) be the jaroslav@1646: * a previous argument to {@code asVarargsCollector}. jaroslav@1646: *

jaroslav@1646: * Here is an example, of a list-making variable arity method handle: jaroslav@1646: *

{@code
jaroslav@1646: MethodHandle asListVar = publicLookup()
jaroslav@1646:   .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
jaroslav@1646:   .asVarargsCollector(Object[].class);
jaroslav@1646: MethodHandle asListFix = asListVar.asFixedArity();
jaroslav@1646: assertEquals("[1]", asListVar.invoke(1).toString());
jaroslav@1646: Exception caught = null;
jaroslav@1646: try { asListFix.invoke((Object)1); }
jaroslav@1646: catch (Exception ex) { caught = ex; }
jaroslav@1646: assert(caught instanceof ClassCastException);
jaroslav@1646: assertEquals("[two, too]", asListVar.invoke("two", "too").toString());
jaroslav@1646: try { asListFix.invoke("two", "too"); }
jaroslav@1646: catch (Exception ex) { caught = ex; }
jaroslav@1646: assert(caught instanceof WrongMethodTypeException);
jaroslav@1646: Object[] argv = { "three", "thee", "tee" };
jaroslav@1646: assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString());
jaroslav@1646: assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
jaroslav@1646: assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
jaroslav@1646: assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
jaroslav@1646:      * }
jaroslav@1646: * jaroslav@1646: * @return a new method handle which accepts only a fixed number of arguments jaroslav@1646: * @see #asVarargsCollector jaroslav@1646: * @see #isVarargsCollector jaroslav@1646: */ jaroslav@1646: public MethodHandle asFixedArity() { jaroslav@1646: assert(!isVarargsCollector()); jaroslav@1646: return this; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Binds a value {@code x} to the first argument of a method handle, without invoking it. jaroslav@1646: * The new method handle adapts, as its target, jaroslav@1646: * the current method handle by binding it to the given argument. jaroslav@1646: * The type of the bound handle will be jaroslav@1646: * the same as the type of the target, except that a single leading jaroslav@1646: * reference parameter will be omitted. jaroslav@1646: *

jaroslav@1646: * When called, the bound handle inserts the given value {@code x} jaroslav@1646: * as a new leading argument to the target. The other arguments are jaroslav@1646: * also passed unchanged. jaroslav@1646: * What the target eventually returns is returned unchanged by the bound handle. jaroslav@1646: *

jaroslav@1646: * The reference {@code x} must be convertible to the first parameter jaroslav@1646: * type of the target. jaroslav@1646: *

jaroslav@1646: * (Note: Because method handles are immutable, the target method handle jaroslav@1646: * retains its original type and behavior.) jaroslav@1646: * @param x the value to bind to the first argument of the target jaroslav@1646: * @return a new method handle which prepends the given value to the incoming jaroslav@1646: * argument list, before calling the original method handle jaroslav@1646: * @throws IllegalArgumentException if the target does not have a jaroslav@1646: * leading parameter type that is a reference type jaroslav@1646: * @throws ClassCastException if {@code x} cannot be converted jaroslav@1646: * to the leading parameter type of the target jaroslav@1646: * @see MethodHandles#insertArguments jaroslav@1646: */ jaroslav@1646: public MethodHandle bindTo(Object x) { jaroslav@1646: Class ptype; jaroslav@1646: @SuppressWarnings("LocalVariableHidesMemberVariable") jaroslav@1646: MethodType type = type(); jaroslav@1646: if (type.parameterCount() == 0 || jaroslav@1646: (ptype = type.parameterType(0)).isPrimitive()) jaroslav@1646: throw newIllegalArgumentException("no leading reference parameter", x); jaroslav@1646: x = ptype.cast(x); // throw CCE if needed jaroslav@1646: return bindReceiver(x); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Returns a string representation of the method handle, jaroslav@1646: * starting with the string {@code "MethodHandle"} and jaroslav@1646: * ending with the string representation of the method handle's type. jaroslav@1646: * In other words, this method returns a string equal to the value of: jaroslav@1646: *

{@code
jaroslav@1646:      * "MethodHandle" + type().toString()
jaroslav@1646:      * }
jaroslav@1646: *

jaroslav@1646: * (Note: Future releases of this API may add further information jaroslav@1646: * to the string representation. jaroslav@1646: * Therefore, the present syntax should not be parsed by applications.) jaroslav@1646: * jaroslav@1646: * @return a string representation of the method handle jaroslav@1646: */ jaroslav@1646: @Override jaroslav@1646: public String toString() { jaroslav@1646: if (DEBUG_METHOD_HANDLE_NAMES) return debugString(); jaroslav@1646: return standardString(); jaroslav@1646: } jaroslav@1646: String standardString() { jaroslav@1646: return "MethodHandle"+type; jaroslav@1646: } jaroslav@1646: String debugString() { jaroslav@1646: return standardString()+"/LF="+internalForm()+internalProperties(); jaroslav@1646: } jaroslav@1646: jaroslav@1646: //// Implementation methods. jaroslav@1646: //// Sub-classes can override these default implementations. jaroslav@1646: //// All these methods assume arguments are already validated. jaroslav@1646: jaroslav@1646: // Other transforms to do: convert, explicitCast, permute, drop, filter, fold, GWT, catch jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: MethodHandle setVarargs(MemberName member) throws IllegalAccessException { jaroslav@1646: if (!member.isVarargs()) return this; jaroslav@1646: int argc = type().parameterCount(); jaroslav@1646: if (argc != 0) { jaroslav@1646: Class arrayType = type().parameterType(argc-1); jaroslav@1646: if (arrayType.isArray()) { jaroslav@1646: return MethodHandleImpl.makeVarargsCollector(this, arrayType); jaroslav@1646: } jaroslav@1646: } jaroslav@1646: throw member.makeAccessException("cannot make variable arity", null); jaroslav@1646: } jaroslav@1646: /*non-public*/ jaroslav@1646: MethodHandle viewAsType(MethodType newType) { jaroslav@1646: // No actual conversions, just a new view of the same method. jaroslav@1646: return MethodHandleImpl.makePairwiseConvert(this, newType, 0); jaroslav@1646: } jaroslav@1646: jaroslav@1646: // Decoding jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: LambdaForm internalForm() { jaroslav@1646: return form; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: MemberName internalMemberName() { jaroslav@1646: return null; // DMH returns DMH.member jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: Class internalCallerClass() { jaroslav@1646: return null; // caller-bound MH for @CallerSensitive method returns caller jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: MethodHandle withInternalMemberName(MemberName member) { jaroslav@1646: if (member != null) { jaroslav@1646: return MethodHandleImpl.makeWrappedMember(this, member); jaroslav@1646: } else if (internalMemberName() == null) { jaroslav@1646: // The required internaMemberName is null, and this MH (like most) doesn't have one. jaroslav@1646: return this; jaroslav@1646: } else { jaroslav@1646: // The following case is rare. Mask the internalMemberName by wrapping the MH in a BMH. jaroslav@1646: MethodHandle result = rebind(); jaroslav@1646: assert (result.internalMemberName() == null); jaroslav@1646: return result; jaroslav@1646: } jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: boolean isInvokeSpecial() { jaroslav@1646: return false; // DMH.Special returns true jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: Object internalValues() { jaroslav@1646: return null; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: Object internalProperties() { jaroslav@1646: // Override to something like "/FOO=bar" jaroslav@1646: return ""; jaroslav@1646: } jaroslav@1646: jaroslav@1646: //// Method handle implementation methods. jaroslav@1646: //// Sub-classes can override these default implementations. jaroslav@1646: //// All these methods assume arguments are already validated. jaroslav@1646: jaroslav@1646: /*non-public*/ MethodHandle convertArguments(MethodType newType) { jaroslav@1646: // Override this if it can be improved. jaroslav@1646: return MethodHandleImpl.makePairwiseConvert(this, newType, 1); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: MethodHandle bindArgument(int pos, char basicType, Object value) { jaroslav@1646: // Override this if it can be improved. jaroslav@1646: return rebind().bindArgument(pos, basicType, value); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: MethodHandle bindReceiver(Object receiver) { jaroslav@1646: // Override this if it can be improved. jaroslav@1646: return bindArgument(0, 'L', receiver); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: MethodHandle bindImmediate(int pos, char basicType, Object value) { jaroslav@1646: // Bind an immediate value to a position in the arguments. jaroslav@1646: // This means, elide the respective argument, jaroslav@1646: // and replace all references to it in NamedFunction args with the specified value. jaroslav@1646: jaroslav@1646: // CURRENT RESTRICTIONS jaroslav@1646: // * only for pos 0 and UNSAFE (position is adjusted in MHImpl to make API usable for others) jaroslav@1646: assert pos == 0 && basicType == 'L' && value instanceof Unsafe; jaroslav@1646: MethodType type2 = type.dropParameterTypes(pos, pos + 1); // adjustment: ignore receiver! jaroslav@1646: LambdaForm form2 = form.bindImmediate(pos + 1, basicType, value); // adjust pos to form-relative pos jaroslav@1646: return copyWith(type2, form2); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: MethodHandle copyWith(MethodType mt, LambdaForm lf) { jaroslav@1646: throw new InternalError("copyWith: " + this.getClass()); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: MethodHandle dropArguments(MethodType srcType, int pos, int drops) { jaroslav@1646: // Override this if it can be improved. jaroslav@1646: return rebind().dropArguments(srcType, pos, drops); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: MethodHandle permuteArguments(MethodType newType, int[] reorder) { jaroslav@1646: // Override this if it can be improved. jaroslav@1646: return rebind().permuteArguments(newType, reorder); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: MethodHandle rebind() { jaroslav@1646: // Bind 'this' into a new invoker, of the known class BMH. jaroslav@1646: MethodType type2 = type(); jaroslav@1646: LambdaForm form2 = reinvokerForm(this); jaroslav@1646: // form2 = lambda (bmh, arg*) { thismh = bmh[0]; invokeBasic(thismh, arg*) } jaroslav@1646: return BoundMethodHandle.bindSingle(type2, form2, this); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: MethodHandle reinvokerTarget() { jaroslav@1646: throw new InternalError("not a reinvoker MH: "+this.getClass().getName()+": "+this); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** Create a LF which simply reinvokes a target of the given basic type. jaroslav@1646: * The target MH must override {@link #reinvokerTarget} to provide the target. jaroslav@1646: */ jaroslav@1646: static LambdaForm reinvokerForm(MethodHandle target) { jaroslav@1646: MethodType mtype = target.type().basicType(); jaroslav@1646: LambdaForm reinvoker = mtype.form().cachedLambdaForm(MethodTypeForm.LF_REINVOKE); jaroslav@1646: if (reinvoker != null) return reinvoker; jaroslav@1646: if (mtype.parameterSlotCount() >= MethodType.MAX_MH_ARITY) jaroslav@1646: return makeReinvokerForm(target.type(), target); // cannot cache this jaroslav@1646: reinvoker = makeReinvokerForm(mtype, null); jaroslav@1646: return mtype.form().setCachedLambdaForm(MethodTypeForm.LF_REINVOKE, reinvoker); jaroslav@1646: } jaroslav@1646: private static LambdaForm makeReinvokerForm(MethodType mtype, MethodHandle customTargetOrNull) { jaroslav@1646: boolean customized = (customTargetOrNull != null); jaroslav@1646: MethodHandle MH_invokeBasic = customized ? null : MethodHandles.basicInvoker(mtype); jaroslav@1646: final int THIS_BMH = 0; jaroslav@1646: final int ARG_BASE = 1; jaroslav@1646: final int ARG_LIMIT = ARG_BASE + mtype.parameterCount(); jaroslav@1646: int nameCursor = ARG_LIMIT; jaroslav@1646: final int NEXT_MH = customized ? -1 : nameCursor++; jaroslav@1646: final int REINVOKE = nameCursor++; jaroslav@1646: LambdaForm.Name[] names = LambdaForm.arguments(nameCursor - ARG_LIMIT, mtype.invokerType()); jaroslav@1646: Object[] targetArgs; jaroslav@1646: MethodHandle targetMH; jaroslav@1646: if (customized) { jaroslav@1646: targetArgs = Arrays.copyOfRange(names, ARG_BASE, ARG_LIMIT, Object[].class); jaroslav@1646: targetMH = customTargetOrNull; jaroslav@1646: } else { jaroslav@1646: names[NEXT_MH] = new LambdaForm.Name(NF_reinvokerTarget, names[THIS_BMH]); jaroslav@1646: targetArgs = Arrays.copyOfRange(names, THIS_BMH, ARG_LIMIT, Object[].class); jaroslav@1646: targetArgs[0] = names[NEXT_MH]; // overwrite this MH with next MH jaroslav@1646: targetMH = MethodHandles.basicInvoker(mtype); jaroslav@1646: } jaroslav@1646: names[REINVOKE] = new LambdaForm.Name(targetMH, targetArgs); jaroslav@1646: return new LambdaForm("BMH.reinvoke", ARG_LIMIT, names); jaroslav@1646: } jaroslav@1646: jaroslav@1646: private static final LambdaForm.NamedFunction NF_reinvokerTarget; jaroslav@1646: static { jaroslav@1646: try { jaroslav@1646: NF_reinvokerTarget = new LambdaForm.NamedFunction(MethodHandle.class jaroslav@1646: .getDeclaredMethod("reinvokerTarget")); jaroslav@1646: } catch (ReflectiveOperationException ex) { jaroslav@1646: throw newInternalError(ex); jaroslav@1646: } jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Replace the old lambda form of this method handle with a new one. jaroslav@1646: * The new one must be functionally equivalent to the old one. jaroslav@1646: * Threads may continue running the old form indefinitely, jaroslav@1646: * but it is likely that the new one will be preferred for new executions. jaroslav@1646: * Use with discretion. jaroslav@1646: */ jaroslav@1646: /*non-public*/ jaroslav@1646: void updateForm(LambdaForm newForm) { jaroslav@1646: if (form == newForm) return; jaroslav@1646: // ISSUE: Should we have a memory fence here? jaroslav@1646: UNSAFE.putObject(this, FORM_OFFSET, newForm); jaroslav@1646: this.form.prepare(); // as in MethodHandle. jaroslav@1646: } jaroslav@1646: jaroslav@1646: private static final long FORM_OFFSET; jaroslav@1646: static { jaroslav@1646: try { jaroslav@1646: FORM_OFFSET = UNSAFE.objectFieldOffset(MethodHandle.class.getDeclaredField("form")); jaroslav@1646: } catch (ReflectiveOperationException ex) { jaroslav@1646: throw newInternalError(ex); jaroslav@1646: } jaroslav@1646: } jaroslav@1646: }