jaroslav@1692: /* jaroslav@1692: * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. jaroslav@1692: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@1692: * jaroslav@1692: * This code is free software; you can redistribute it and/or modify it jaroslav@1692: * under the terms of the GNU General Public License version 2 only, as jaroslav@1692: * published by the Free Software Foundation. Oracle designates this jaroslav@1692: * particular file as subject to the "Classpath" exception as provided jaroslav@1692: * by Oracle in the LICENSE file that accompanied this code. jaroslav@1692: * jaroslav@1692: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@1692: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@1692: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@1692: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@1692: * accompanied this code). jaroslav@1692: * jaroslav@1692: * You should have received a copy of the GNU General Public License version jaroslav@1692: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@1692: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@1692: * jaroslav@1692: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@1692: * or visit www.oracle.com if you need additional information or have any jaroslav@1692: * questions. jaroslav@1692: */ jaroslav@1692: jaroslav@1692: package java.lang.invoke; jaroslav@1692: jaroslav@1692: jaroslav@1692: import java.util.*; jaroslav@1692: jaroslav@1692: /** jaroslav@1692: * A method handle is a typed, directly executable reference to an underlying method, jaroslav@1692: * constructor, field, or similar low-level operation, with optional jaroslav@1692: * transformations of arguments or return values. jaroslav@1692: * These transformations are quite general, and include such patterns as jaroslav@1692: * {@linkplain #asType conversion}, jaroslav@1692: * {@linkplain #bindTo insertion}, jaroslav@1692: * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion}, jaroslav@1692: * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}. jaroslav@1692: * jaroslav@1692: *

Method handle contents

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

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

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

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

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

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

Method handle compilation

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

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

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

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

Method handle invocation

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

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

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

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

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

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

Invocation checking

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

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

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

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

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

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

Method handle creation

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

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

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

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

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

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

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

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

Usage examples

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

Exceptions

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

Signature polymorphism

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

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

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

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

Interoperation between method handles and the Core Reflection API

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

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

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

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

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

Interoperation between method handles and Java generics

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

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

jaroslav@1692: * jaroslav@1692: *

Arity limits

jaroslav@1692: * The JVM imposes on all methods and constructors of any kind an absolute jaroslav@1692: * limit of 255 stacked arguments. This limit can appear more restrictive jaroslav@1692: * in certain cases: jaroslav@1692: * jaroslav@1692: * These limits imply that certain method handles cannot be created, solely because of the JVM limit on stacked arguments. jaroslav@1692: * For example, if a static JVM method accepts exactly 255 arguments, a method handle cannot be created for it. jaroslav@1692: * Attempts to create method handles with impossible method types lead to an {@link IllegalArgumentException}. jaroslav@1692: * In particular, a method handle’s type must not have an arity of the exact maximum 255. jaroslav@1692: * jaroslav@1692: * @see MethodType jaroslav@1692: * @see MethodHandles jaroslav@1692: * @author John Rose, JSR 292 EG jaroslav@1692: */ jaroslav@1692: public abstract class MethodHandle { jaroslav@1692: /** jaroslav@1692: * Internal marker interface which distinguishes (to the Java compiler) jaroslav@1692: * those methods which are signature polymorphic. jaroslav@1692: */ jaroslav@1692: @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD}) jaroslav@1692: @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) jaroslav@1692: @interface PolymorphicSignature { } jaroslav@1692: jaroslav@1692: /** jaroslav@1692: * Reports the type of this method handle. jaroslav@1692: * Every invocation of this method handle via {@code invokeExact} must exactly match this type. jaroslav@1692: * @return the method handle type jaroslav@1692: */ jaroslav@1692: public MethodType type() { jaroslav@1692: throw new IllegalStateException(); jaroslav@1692: } jaroslav@1692: jaroslav@1692: /** jaroslav@1692: * Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match. jaroslav@1692: * The symbolic type descriptor at the call site of {@code invokeExact} must jaroslav@1692: * exactly match this method handle's {@link #type type}. jaroslav@1692: * No conversions are allowed on arguments or return values. jaroslav@1692: *

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

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

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

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

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

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

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

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

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

jaroslav@1692: *

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

jaroslav@1692: *

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

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

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

jaroslav@1692: * Unlike the signature polymorphic methods {@code invokeExact} and {@code invoke}, jaroslav@1692: * {@code invokeWithArguments} can be accessed normally via the Core Reflection API and JNI. jaroslav@1692: * It can therefore be used as a bridge between native or reflective code and method handles. jaroslav@1692: * jaroslav@1692: * @param arguments the arguments to pass to the target jaroslav@1692: * @return the result returned by the target jaroslav@1692: * @throws ClassCastException if an argument cannot be converted by reference casting jaroslav@1692: * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments jaroslav@1692: * @throws Throwable anything thrown by the target method invocation jaroslav@1692: * @see MethodHandles#spreadInvoker jaroslav@1692: */ jaroslav@1692: public Object invokeWithArguments(Object... arguments) throws Throwable { jaroslav@1692: throw new IllegalStateException(); jaroslav@1692: } jaroslav@1692: jaroslav@1692: /** jaroslav@1692: * Performs a variable arity invocation, passing the arguments in the given array jaroslav@1692: * to the method handle, as if via an inexact {@link #invoke invoke} from a call site jaroslav@1692: * which mentions only the type {@code Object}, and whose arity is the length jaroslav@1692: * of the argument array. jaroslav@1692: *

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

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

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

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

jaroslav@1692: *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

jaroslav@1692: * (Note: Future releases of this API may add further information jaroslav@1692: * to the string representation. jaroslav@1692: * Therefore, the present syntax should not be parsed by applications.) jaroslav@1692: * jaroslav@1692: * @return a string representation of the method handle jaroslav@1692: */ jaroslav@1692: @Override jaroslav@1692: public String toString() { jaroslav@1692: return standardString(); jaroslav@1692: } jaroslav@1692: String standardString() { jaroslav@1692: throw new IllegalStateException(); jaroslav@1692: } jaroslav@1692: }