rt/emul/compact/src/main/java/java/lang/invoke/MethodHandle.java
changeset 1985 cd1cc103a03c
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/rt/emul/compact/src/main/java/java/lang/invoke/MethodHandle.java	Tue Jan 17 07:04:06 2017 +0100
     1.3 @@ -0,0 +1,1168 @@
     1.4 +/*
     1.5 + * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +package java.lang.invoke;
    1.30 +
    1.31 +
    1.32 +import java.util.*;
    1.33 +
    1.34 +/**
    1.35 + * A method handle is a typed, directly executable reference to an underlying method,
    1.36 + * constructor, field, or similar low-level operation, with optional
    1.37 + * transformations of arguments or return values.
    1.38 + * These transformations are quite general, and include such patterns as
    1.39 + * {@linkplain #asType conversion},
    1.40 + * {@linkplain #bindTo insertion},
    1.41 + * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion},
    1.42 + * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}.
    1.43 + *
    1.44 + * <h1>Method handle contents</h1>
    1.45 + * Method handles are dynamically and strongly typed according to their parameter and return types.
    1.46 + * They are not distinguished by the name or the defining class of their underlying methods.
    1.47 + * A method handle must be invoked using a symbolic type descriptor which matches
    1.48 + * the method handle's own {@linkplain #type type descriptor}.
    1.49 + * <p>
    1.50 + * Every method handle reports its type descriptor via the {@link #type type} accessor.
    1.51 + * This type descriptor is a {@link java.lang.invoke.MethodType MethodType} object,
    1.52 + * whose structure is a series of classes, one of which is
    1.53 + * the return type of the method (or {@code void.class} if none).
    1.54 + * <p>
    1.55 + * A method handle's type controls the types of invocations it accepts,
    1.56 + * and the kinds of transformations that apply to it.
    1.57 + * <p>
    1.58 + * A method handle contains a pair of special invoker methods
    1.59 + * called {@link #invokeExact invokeExact} and {@link #invoke invoke}.
    1.60 + * Both invoker methods provide direct access to the method handle's
    1.61 + * underlying method, constructor, field, or other operation,
    1.62 + * as modified by transformations of arguments and return values.
    1.63 + * Both invokers accept calls which exactly match the method handle's own type.
    1.64 + * The plain, inexact invoker also accepts a range of other call types.
    1.65 + * <p>
    1.66 + * Method handles are immutable and have no visible state.
    1.67 + * Of course, they can be bound to underlying methods or data which exhibit state.
    1.68 + * With respect to the Java Memory Model, any method handle will behave
    1.69 + * as if all of its (internal) fields are final variables.  This means that any method
    1.70 + * handle made visible to the application will always be fully formed.
    1.71 + * This is true even if the method handle is published through a shared
    1.72 + * variable in a data race.
    1.73 + * <p>
    1.74 + * Method handles cannot be subclassed by the user.
    1.75 + * Implementations may (or may not) create internal subclasses of {@code MethodHandle}
    1.76 + * which may be visible via the {@link java.lang.Object#getClass Object.getClass}
    1.77 + * operation.  The programmer should not draw conclusions about a method handle
    1.78 + * from its specific class, as the method handle class hierarchy (if any)
    1.79 + * may change from time to time or across implementations from different vendors.
    1.80 + *
    1.81 + * <h1>Method handle compilation</h1>
    1.82 + * A Java method call expression naming {@code invokeExact} or {@code invoke}
    1.83 + * can invoke a method handle from Java source code.
    1.84 + * From the viewpoint of source code, these methods can take any arguments
    1.85 + * and their result can be cast to any return type.
    1.86 + * Formally this is accomplished by giving the invoker methods
    1.87 + * {@code Object} return types and variable arity {@code Object} arguments,
    1.88 + * but they have an additional quality called <em>signature polymorphism</em>
    1.89 + * which connects this freedom of invocation directly to the JVM execution stack.
    1.90 + * <p>
    1.91 + * As is usual with virtual methods, source-level calls to {@code invokeExact}
    1.92 + * and {@code invoke} compile to an {@code invokevirtual} instruction.
    1.93 + * More unusually, the compiler must record the actual argument types,
    1.94 + * and may not perform method invocation conversions on the arguments.
    1.95 + * Instead, it must push them on the stack according to their own unconverted types.
    1.96 + * The method handle object itself is pushed on the stack before the arguments.
    1.97 + * The compiler then calls the method handle with a symbolic type descriptor which
    1.98 + * describes the argument and return types.
    1.99 + * <p>
   1.100 + * To issue a complete symbolic type descriptor, the compiler must also determine
   1.101 + * the return type.  This is based on a cast on the method invocation expression,
   1.102 + * if there is one, or else {@code Object} if the invocation is an expression
   1.103 + * or else {@code void} if the invocation is a statement.
   1.104 + * The cast may be to a primitive type (but not {@code void}).
   1.105 + * <p>
   1.106 + * As a corner case, an uncasted {@code null} argument is given
   1.107 + * a symbolic type descriptor of {@code java.lang.Void}.
   1.108 + * The ambiguity with the type {@code Void} is harmless, since there are no references of type
   1.109 + * {@code Void} except the null reference.
   1.110 + *
   1.111 + * <h1>Method handle invocation</h1>
   1.112 + * The first time a {@code invokevirtual} instruction is executed
   1.113 + * it is linked, by symbolically resolving the names in the instruction
   1.114 + * and verifying that the method call is statically legal.
   1.115 + * This is true of calls to {@code invokeExact} and {@code invoke}.
   1.116 + * In this case, the symbolic type descriptor emitted by the compiler is checked for
   1.117 + * correct syntax and names it contains are resolved.
   1.118 + * Thus, an {@code invokevirtual} instruction which invokes
   1.119 + * a method handle will always link, as long
   1.120 + * as the symbolic type descriptor is syntactically well-formed
   1.121 + * and the types exist.
   1.122 + * <p>
   1.123 + * When the {@code invokevirtual} is executed after linking,
   1.124 + * the receiving method handle's type is first checked by the JVM
   1.125 + * to ensure that it matches the symbolic type descriptor.
   1.126 + * If the type match fails, it means that the method which the
   1.127 + * caller is invoking is not present on the individual
   1.128 + * method handle being invoked.
   1.129 + * <p>
   1.130 + * In the case of {@code invokeExact}, the type descriptor of the invocation
   1.131 + * (after resolving symbolic type names) must exactly match the method type
   1.132 + * of the receiving method handle.
   1.133 + * In the case of plain, inexact {@code invoke}, the resolved type descriptor
   1.134 + * must be a valid argument to the receiver's {@link #asType asType} method.
   1.135 + * Thus, plain {@code invoke} is more permissive than {@code invokeExact}.
   1.136 + * <p>
   1.137 + * After type matching, a call to {@code invokeExact} directly
   1.138 + * and immediately invoke the method handle's underlying method
   1.139 + * (or other behavior, as the case may be).
   1.140 + * <p>
   1.141 + * A call to plain {@code invoke} works the same as a call to
   1.142 + * {@code invokeExact}, if the symbolic type descriptor specified by the caller
   1.143 + * exactly matches the method handle's own type.
   1.144 + * If there is a type mismatch, {@code invoke} attempts
   1.145 + * to adjust the type of the receiving method handle,
   1.146 + * as if by a call to {@link #asType asType},
   1.147 + * to obtain an exactly invokable method handle {@code M2}.
   1.148 + * This allows a more powerful negotiation of method type
   1.149 + * between caller and callee.
   1.150 + * <p>
   1.151 + * (<em>Note:</em> The adjusted method handle {@code M2} is not directly observable,
   1.152 + * and implementations are therefore not required to materialize it.)
   1.153 + *
   1.154 + * <h1>Invocation checking</h1>
   1.155 + * In typical programs, method handle type matching will usually succeed.
   1.156 + * But if a match fails, the JVM will throw a {@link WrongMethodTypeException},
   1.157 + * either directly (in the case of {@code invokeExact}) or indirectly as if
   1.158 + * by a failed call to {@code asType} (in the case of {@code invoke}).
   1.159 + * <p>
   1.160 + * Thus, a method type mismatch which might show up as a linkage error
   1.161 + * in a statically typed program can show up as
   1.162 + * a dynamic {@code WrongMethodTypeException}
   1.163 + * in a program which uses method handles.
   1.164 + * <p>
   1.165 + * Because method types contain "live" {@code Class} objects,
   1.166 + * method type matching takes into account both types names and class loaders.
   1.167 + * Thus, even if a method handle {@code M} is created in one
   1.168 + * class loader {@code L1} and used in another {@code L2},
   1.169 + * method handle calls are type-safe, because the caller's symbolic type
   1.170 + * descriptor, as resolved in {@code L2},
   1.171 + * is matched against the original callee method's symbolic type descriptor,
   1.172 + * as resolved in {@code L1}.
   1.173 + * The resolution in {@code L1} happens when {@code M} is created
   1.174 + * and its type is assigned, while the resolution in {@code L2} happens
   1.175 + * when the {@code invokevirtual} instruction is linked.
   1.176 + * <p>
   1.177 + * Apart from the checking of type descriptors,
   1.178 + * a method handle's capability to call its underlying method is unrestricted.
   1.179 + * If a method handle is formed on a non-public method by a class
   1.180 + * that has access to that method, the resulting handle can be used
   1.181 + * in any place by any caller who receives a reference to it.
   1.182 + * <p>
   1.183 + * Unlike with the Core Reflection API, where access is checked every time
   1.184 + * a reflective method is invoked,
   1.185 + * method handle access checking is performed
   1.186 + * <a href="MethodHandles.Lookup.html#access">when the method handle is created</a>.
   1.187 + * In the case of {@code ldc} (see below), access checking is performed as part of linking
   1.188 + * the constant pool entry underlying the constant method handle.
   1.189 + * <p>
   1.190 + * Thus, handles to non-public methods, or to methods in non-public classes,
   1.191 + * should generally be kept secret.
   1.192 + * They should not be passed to untrusted code unless their use from
   1.193 + * the untrusted code would be harmless.
   1.194 + *
   1.195 + * <h1>Method handle creation</h1>
   1.196 + * Java code can create a method handle that directly accesses
   1.197 + * any method, constructor, or field that is accessible to that code.
   1.198 + * This is done via a reflective, capability-based API called
   1.199 + * {@link java.lang.invoke.MethodHandles.Lookup MethodHandles.Lookup}
   1.200 + * For example, a static method handle can be obtained
   1.201 + * from {@link java.lang.invoke.MethodHandles.Lookup#findStatic Lookup.findStatic}.
   1.202 + * There are also conversion methods from Core Reflection API objects,
   1.203 + * such as {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
   1.204 + * <p>
   1.205 + * Like classes and strings, method handles that correspond to accessible
   1.206 + * fields, methods, and constructors can also be represented directly
   1.207 + * in a class file's constant pool as constants to be loaded by {@code ldc} bytecodes.
   1.208 + * A new type of constant pool entry, {@code CONSTANT_MethodHandle},
   1.209 + * refers directly to an associated {@code CONSTANT_Methodref},
   1.210 + * {@code CONSTANT_InterfaceMethodref}, or {@code CONSTANT_Fieldref}
   1.211 + * constant pool entry.
   1.212 + * (For full details on method handle constants,
   1.213 + * see sections 4.4.8 and 5.4.3.5 of the Java Virtual Machine Specification.)
   1.214 + * <p>
   1.215 + * Method handles produced by lookups or constant loads from methods or
   1.216 + * constructors with the variable arity modifier bit ({@code 0x0080})
   1.217 + * have a corresponding variable arity, as if they were defined with
   1.218 + * the help of {@link #asVarargsCollector asVarargsCollector}.
   1.219 + * <p>
   1.220 + * A method reference may refer either to a static or non-static method.
   1.221 + * In the non-static case, the method handle type includes an explicit
   1.222 + * receiver argument, prepended before any other arguments.
   1.223 + * In the method handle's type, the initial receiver argument is typed
   1.224 + * according to the class under which the method was initially requested.
   1.225 + * (E.g., if a non-static method handle is obtained via {@code ldc},
   1.226 + * the type of the receiver is the class named in the constant pool entry.)
   1.227 + * <p>
   1.228 + * Method handle constants are subject to the same link-time access checks
   1.229 + * their corresponding bytecode instructions, and the {@code ldc} instruction
   1.230 + * will throw corresponding linkage errors if the bytecode behaviors would
   1.231 + * throw such errors.
   1.232 + * <p>
   1.233 + * As a corollary of this, access to protected members is restricted
   1.234 + * to receivers only of the accessing class, or one of its subclasses,
   1.235 + * and the accessing class must in turn be a subclass (or package sibling)
   1.236 + * of the protected member's defining class.
   1.237 + * If a method reference refers to a protected non-static method or field
   1.238 + * of a class outside the current package, the receiver argument will
   1.239 + * be narrowed to the type of the accessing class.
   1.240 + * <p>
   1.241 + * When a method handle to a virtual method is invoked, the method is
   1.242 + * always looked up in the receiver (that is, the first argument).
   1.243 + * <p>
   1.244 + * A non-virtual method handle to a specific virtual method implementation
   1.245 + * can also be created.  These do not perform virtual lookup based on
   1.246 + * receiver type.  Such a method handle simulates the effect of
   1.247 + * an {@code invokespecial} instruction to the same method.
   1.248 + *
   1.249 + * <h1>Usage examples</h1>
   1.250 + * Here are some examples of usage:
   1.251 + * <blockquote><pre>{@code
   1.252 +Object x, y; String s; int i;
   1.253 +MethodType mt; MethodHandle mh;
   1.254 +MethodHandles.Lookup lookup = MethodHandles.lookup();
   1.255 +// mt is (char,char)String
   1.256 +mt = MethodType.methodType(String.class, char.class, char.class);
   1.257 +mh = lookup.findVirtual(String.class, "replace", mt);
   1.258 +s = (String) mh.invokeExact("daddy",'d','n');
   1.259 +// invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
   1.260 +assertEquals(s, "nanny");
   1.261 +// weakly typed invocation (using MHs.invoke)
   1.262 +s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
   1.263 +assertEquals(s, "savvy");
   1.264 +// mt is (Object[])List
   1.265 +mt = MethodType.methodType(java.util.List.class, Object[].class);
   1.266 +mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
   1.267 +assert(mh.isVarargsCollector());
   1.268 +x = mh.invoke("one", "two");
   1.269 +// invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
   1.270 +assertEquals(x, java.util.Arrays.asList("one","two"));
   1.271 +// mt is (Object,Object,Object)Object
   1.272 +mt = MethodType.genericMethodType(3);
   1.273 +mh = mh.asType(mt);
   1.274 +x = mh.invokeExact((Object)1, (Object)2, (Object)3);
   1.275 +// invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
   1.276 +assertEquals(x, java.util.Arrays.asList(1,2,3));
   1.277 +// mt is ()int
   1.278 +mt = MethodType.methodType(int.class);
   1.279 +mh = lookup.findVirtual(java.util.List.class, "size", mt);
   1.280 +i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
   1.281 +// invokeExact(Ljava/util/List;)I
   1.282 +assert(i == 3);
   1.283 +mt = MethodType.methodType(void.class, String.class);
   1.284 +mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
   1.285 +mh.invokeExact(System.out, "Hello, world.");
   1.286 +// invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
   1.287 + * }</pre></blockquote>
   1.288 + * Each of the above calls to {@code invokeExact} or plain {@code invoke}
   1.289 + * generates a single invokevirtual instruction with
   1.290 + * the symbolic type descriptor indicated in the following comment.
   1.291 + * In these examples, the helper method {@code assertEquals} is assumed to
   1.292 + * be a method which calls {@link java.util.Objects#equals(Object,Object) Objects.equals}
   1.293 + * on its arguments, and asserts that the result is true.
   1.294 + *
   1.295 + * <h1>Exceptions</h1>
   1.296 + * The methods {@code invokeExact} and {@code invoke} are declared
   1.297 + * to throw {@link java.lang.Throwable Throwable},
   1.298 + * which is to say that there is no static restriction on what a method handle
   1.299 + * can throw.  Since the JVM does not distinguish between checked
   1.300 + * and unchecked exceptions (other than by their class, of course),
   1.301 + * there is no particular effect on bytecode shape from ascribing
   1.302 + * checked exceptions to method handle invocations.  But in Java source
   1.303 + * code, methods which perform method handle calls must either explicitly
   1.304 + * throw {@code Throwable}, or else must catch all
   1.305 + * throwables locally, rethrowing only those which are legal in the context,
   1.306 + * and wrapping ones which are illegal.
   1.307 + *
   1.308 + * <h1><a name="sigpoly"></a>Signature polymorphism</h1>
   1.309 + * The unusual compilation and linkage behavior of
   1.310 + * {@code invokeExact} and plain {@code invoke}
   1.311 + * is referenced by the term <em>signature polymorphism</em>.
   1.312 + * As defined in the Java Language Specification,
   1.313 + * a signature polymorphic method is one which can operate with
   1.314 + * any of a wide range of call signatures and return types.
   1.315 + * <p>
   1.316 + * In source code, a call to a signature polymorphic method will
   1.317 + * compile, regardless of the requested symbolic type descriptor.
   1.318 + * As usual, the Java compiler emits an {@code invokevirtual}
   1.319 + * instruction with the given symbolic type descriptor against the named method.
   1.320 + * The unusual part is that the symbolic type descriptor is derived from
   1.321 + * the actual argument and return types, not from the method declaration.
   1.322 + * <p>
   1.323 + * When the JVM processes bytecode containing signature polymorphic calls,
   1.324 + * it will successfully link any such call, regardless of its symbolic type descriptor.
   1.325 + * (In order to retain type safety, the JVM will guard such calls with suitable
   1.326 + * dynamic type checks, as described elsewhere.)
   1.327 + * <p>
   1.328 + * Bytecode generators, including the compiler back end, are required to emit
   1.329 + * untransformed symbolic type descriptors for these methods.
   1.330 + * Tools which determine symbolic linkage are required to accept such
   1.331 + * untransformed descriptors, without reporting linkage errors.
   1.332 + *
   1.333 + * <h1>Interoperation between method handles and the Core Reflection API</h1>
   1.334 + * Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup Lookup} API,
   1.335 + * any class member represented by a Core Reflection API object
   1.336 + * can be converted to a behaviorally equivalent method handle.
   1.337 + * For example, a reflective {@link java.lang.reflect.Method Method} can
   1.338 + * be converted to a method handle using
   1.339 + * {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
   1.340 + * The resulting method handles generally provide more direct and efficient
   1.341 + * access to the underlying class members.
   1.342 + * <p>
   1.343 + * As a special case,
   1.344 + * when the Core Reflection API is used to view the signature polymorphic
   1.345 + * methods {@code invokeExact} or plain {@code invoke} in this class,
   1.346 + * they appear as ordinary non-polymorphic methods.
   1.347 + * Their reflective appearance, as viewed by
   1.348 + * {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod},
   1.349 + * is unaffected by their special status in this API.
   1.350 + * For example, {@link java.lang.reflect.Method#getModifiers Method.getModifiers}
   1.351 + * will report exactly those modifier bits required for any similarly
   1.352 + * declared method, including in this case {@code native} and {@code varargs} bits.
   1.353 + * <p>
   1.354 + * As with any reflected method, these methods (when reflected) may be
   1.355 + * invoked via {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.
   1.356 + * However, such reflective calls do not result in method handle invocations.
   1.357 + * Such a call, if passed the required argument
   1.358 + * (a single one, of type {@code Object[]}), will ignore the argument and
   1.359 + * will throw an {@code UnsupportedOperationException}.
   1.360 + * <p>
   1.361 + * Since {@code invokevirtual} instructions can natively
   1.362 + * invoke method handles under any symbolic type descriptor, this reflective view conflicts
   1.363 + * with the normal presentation of these methods via bytecodes.
   1.364 + * Thus, these two native methods, when reflectively viewed by
   1.365 + * {@code Class.getDeclaredMethod}, may be regarded as placeholders only.
   1.366 + * <p>
   1.367 + * In order to obtain an invoker method for a particular type descriptor,
   1.368 + * use {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker},
   1.369 + * or {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}.
   1.370 + * The {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual}
   1.371 + * API is also able to return a method handle
   1.372 + * to call {@code invokeExact} or plain {@code invoke},
   1.373 + * for any specified type descriptor .
   1.374 + *
   1.375 + * <h1>Interoperation between method handles and Java generics</h1>
   1.376 + * A method handle can be obtained on a method, constructor, or field
   1.377 + * which is declared with Java generic types.
   1.378 + * As with the Core Reflection API, the type of the method handle
   1.379 + * will constructed from the erasure of the source-level type.
   1.380 + * When a method handle is invoked, the types of its arguments
   1.381 + * or the return value cast type may be generic types or type instances.
   1.382 + * If this occurs, the compiler will replace those
   1.383 + * types by their erasures when it constructs the symbolic type descriptor
   1.384 + * for the {@code invokevirtual} instruction.
   1.385 + * <p>
   1.386 + * Method handles do not represent
   1.387 + * their function-like types in terms of Java parameterized (generic) types,
   1.388 + * because there are three mismatches between function-like types and parameterized
   1.389 + * Java types.
   1.390 + * <ul>
   1.391 + * <li>Method types range over all possible arities,
   1.392 + * from no arguments to up to the  <a href="MethodHandle.html#maxarity">maximum number</a> of allowed arguments.
   1.393 + * Generics are not variadic, and so cannot represent this.</li>
   1.394 + * <li>Method types can specify arguments of primitive types,
   1.395 + * which Java generic types cannot range over.</li>
   1.396 + * <li>Higher order functions over method handles (combinators) are
   1.397 + * often generic across a wide range of function types, including
   1.398 + * those of multiple arities.  It is impossible to represent such
   1.399 + * genericity with a Java type parameter.</li>
   1.400 + * </ul>
   1.401 + *
   1.402 + * <h1><a name="maxarity"></a>Arity limits</h1>
   1.403 + * The JVM imposes on all methods and constructors of any kind an absolute
   1.404 + * limit of 255 stacked arguments.  This limit can appear more restrictive
   1.405 + * in certain cases:
   1.406 + * <ul>
   1.407 + * <li>A {@code long} or {@code double} argument counts (for purposes of arity limits) as two argument slots.
   1.408 + * <li>A non-static method consumes an extra argument for the object on which the method is called.
   1.409 + * <li>A constructor consumes an extra argument for the object which is being constructed.
   1.410 + * <li>Since a method handle&rsquo;s {@code invoke} method (or other signature-polymorphic method) is non-virtual,
   1.411 + *     it consumes an extra argument for the method handle itself, in addition to any non-virtual receiver object.
   1.412 + * </ul>
   1.413 + * These limits imply that certain method handles cannot be created, solely because of the JVM limit on stacked arguments.
   1.414 + * For example, if a static JVM method accepts exactly 255 arguments, a method handle cannot be created for it.
   1.415 + * Attempts to create method handles with impossible method types lead to an {@link IllegalArgumentException}.
   1.416 + * In particular, a method handle&rsquo;s type must not have an arity of the exact maximum 255.
   1.417 + *
   1.418 + * @see MethodType
   1.419 + * @see MethodHandles
   1.420 + * @author John Rose, JSR 292 EG
   1.421 + */
   1.422 +public abstract class MethodHandle {
   1.423 +    /**
   1.424 +     * Internal marker interface which distinguishes (to the Java compiler)
   1.425 +     * those methods which are <a href="MethodHandle.html#sigpoly">signature polymorphic</a>.
   1.426 +     */
   1.427 +    @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
   1.428 +    @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
   1.429 +    @interface PolymorphicSignature { }
   1.430 +
   1.431 +    /**
   1.432 +     * Reports the type of this method handle.
   1.433 +     * Every invocation of this method handle via {@code invokeExact} must exactly match this type.
   1.434 +     * @return the method handle type
   1.435 +     */
   1.436 +    public MethodType type() {
   1.437 +        throw new IllegalStateException();
   1.438 +    }
   1.439 +
   1.440 +    /**
   1.441 +     * Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match.
   1.442 +     * The symbolic type descriptor at the call site of {@code invokeExact} must
   1.443 +     * exactly match this method handle's {@link #type type}.
   1.444 +     * No conversions are allowed on arguments or return values.
   1.445 +     * <p>
   1.446 +     * When this method is observed via the Core Reflection API,
   1.447 +     * it will appear as a single native method, taking an object array and returning an object.
   1.448 +     * If this native method is invoked directly via
   1.449 +     * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
   1.450 +     * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
   1.451 +     * it will throw an {@code UnsupportedOperationException}.
   1.452 +     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.453 +     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.454 +     * @throws WrongMethodTypeException if the target's type is not identical with the caller's symbolic type descriptor
   1.455 +     * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
   1.456 +     */
   1.457 +    public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable;
   1.458 +
   1.459 +    /**
   1.460 +     * Invokes the method handle, allowing any caller type descriptor,
   1.461 +     * and optionally performing conversions on arguments and return values.
   1.462 +     * <p>
   1.463 +     * If the call site's symbolic type descriptor exactly matches this method handle's {@link #type type},
   1.464 +     * the call proceeds as if by {@link #invokeExact invokeExact}.
   1.465 +     * <p>
   1.466 +     * Otherwise, the call proceeds as if this method handle were first
   1.467 +     * adjusted by calling {@link #asType asType} to adjust this method handle
   1.468 +     * to the required type, and then the call proceeds as if by
   1.469 +     * {@link #invokeExact invokeExact} on the adjusted method handle.
   1.470 +     * <p>
   1.471 +     * There is no guarantee that the {@code asType} call is actually made.
   1.472 +     * If the JVM can predict the results of making the call, it may perform
   1.473 +     * adaptations directly on the caller's arguments,
   1.474 +     * and call the target method handle according to its own exact type.
   1.475 +     * <p>
   1.476 +     * The resolved type descriptor at the call site of {@code invoke} must
   1.477 +     * be a valid argument to the receivers {@code asType} method.
   1.478 +     * In particular, the caller must specify the same argument arity
   1.479 +     * as the callee's type,
   1.480 +     * if the callee is not a {@linkplain #asVarargsCollector variable arity collector}.
   1.481 +     * <p>
   1.482 +     * When this method is observed via the Core Reflection API,
   1.483 +     * it will appear as a single native method, taking an object array and returning an object.
   1.484 +     * If this native method is invoked directly via
   1.485 +     * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
   1.486 +     * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
   1.487 +     * it will throw an {@code UnsupportedOperationException}.
   1.488 +     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.489 +     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.490 +     * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's symbolic type descriptor
   1.491 +     * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails
   1.492 +     * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
   1.493 +     */
   1.494 +    public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable;
   1.495 +
   1.496 +    /**
   1.497 +     * Private method for trusted invocation of a method handle respecting simplified signatures.
   1.498 +     * Type mismatches will not throw {@code WrongMethodTypeException}, but could crash the JVM.
   1.499 +     * <p>
   1.500 +     * The caller signature is restricted to the following basic types:
   1.501 +     * Object, int, long, float, double, and void return.
   1.502 +     * <p>
   1.503 +     * The caller is responsible for maintaining type correctness by ensuring
   1.504 +     * that the each outgoing argument value is a member of the range of the corresponding
   1.505 +     * callee argument type.
   1.506 +     * (The caller should therefore issue appropriate casts and integer narrowing
   1.507 +     * operations on outgoing argument values.)
   1.508 +     * The caller can assume that the incoming result value is part of the range
   1.509 +     * of the callee's return type.
   1.510 +     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.511 +     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.512 +     */
   1.513 +    /*non-public*/ final native @PolymorphicSignature Object invokeBasic(Object... args) throws Throwable;
   1.514 +
   1.515 +    /**
   1.516 +     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeVirtual}.
   1.517 +     * The caller signature is restricted to basic types as with {@code invokeBasic}.
   1.518 +     * The trailing (not leading) argument must be a MemberName.
   1.519 +     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.520 +     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.521 +     */
   1.522 +    /*non-public*/ static native @PolymorphicSignature Object linkToVirtual(Object... args) throws Throwable;
   1.523 +
   1.524 +    /**
   1.525 +     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeStatic}.
   1.526 +     * The caller signature is restricted to basic types as with {@code invokeBasic}.
   1.527 +     * The trailing (not leading) argument must be a MemberName.
   1.528 +     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.529 +     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.530 +     */
   1.531 +    /*non-public*/ static native @PolymorphicSignature Object linkToStatic(Object... args) throws Throwable;
   1.532 +
   1.533 +    /**
   1.534 +     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeSpecial}.
   1.535 +     * The caller signature is restricted to basic types as with {@code invokeBasic}.
   1.536 +     * The trailing (not leading) argument must be a MemberName.
   1.537 +     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.538 +     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.539 +     */
   1.540 +    /*non-public*/ static native @PolymorphicSignature Object linkToSpecial(Object... args) throws Throwable;
   1.541 +
   1.542 +    /**
   1.543 +     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeInterface}.
   1.544 +     * The caller signature is restricted to basic types as with {@code invokeBasic}.
   1.545 +     * The trailing (not leading) argument must be a MemberName.
   1.546 +     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.547 +     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.548 +     */
   1.549 +    /*non-public*/ static native @PolymorphicSignature Object linkToInterface(Object... args) throws Throwable;
   1.550 +
   1.551 +    /**
   1.552 +     * Performs a variable arity invocation, passing the arguments in the given list
   1.553 +     * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
   1.554 +     * which mentions only the type {@code Object}, and whose arity is the length
   1.555 +     * of the argument list.
   1.556 +     * <p>
   1.557 +     * Specifically, execution proceeds as if by the following steps,
   1.558 +     * although the methods are not guaranteed to be called if the JVM
   1.559 +     * can predict their effects.
   1.560 +     * <ul>
   1.561 +     * <li>Determine the length of the argument array as {@code N}.
   1.562 +     *     For a null reference, {@code N=0}. </li>
   1.563 +     * <li>Determine the general type {@code TN} of {@code N} arguments as
   1.564 +     *     as {@code TN=MethodType.genericMethodType(N)}.</li>
   1.565 +     * <li>Force the original target method handle {@code MH0} to the
   1.566 +     *     required type, as {@code MH1 = MH0.asType(TN)}. </li>
   1.567 +     * <li>Spread the array into {@code N} separate arguments {@code A0, ...}. </li>
   1.568 +     * <li>Invoke the type-adjusted method handle on the unpacked arguments:
   1.569 +     *     MH1.invokeExact(A0, ...). </li>
   1.570 +     * <li>Take the return value as an {@code Object} reference. </li>
   1.571 +     * </ul>
   1.572 +     * <p>
   1.573 +     * Because of the action of the {@code asType} step, the following argument
   1.574 +     * conversions are applied as necessary:
   1.575 +     * <ul>
   1.576 +     * <li>reference casting
   1.577 +     * <li>unboxing
   1.578 +     * <li>widening primitive conversions
   1.579 +     * </ul>
   1.580 +     * <p>
   1.581 +     * The result returned by the call is boxed if it is a primitive,
   1.582 +     * or forced to null if the return type is void.
   1.583 +     * <p>
   1.584 +     * This call is equivalent to the following code:
   1.585 +     * <blockquote><pre>{@code
   1.586 +     * MethodHandle invoker = MethodHandles.spreadInvoker(this.type(), 0);
   1.587 +     * Object result = invoker.invokeExact(this, arguments);
   1.588 +     * }</pre></blockquote>
   1.589 +     * <p>
   1.590 +     * Unlike the signature polymorphic methods {@code invokeExact} and {@code invoke},
   1.591 +     * {@code invokeWithArguments} can be accessed normally via the Core Reflection API and JNI.
   1.592 +     * It can therefore be used as a bridge between native or reflective code and method handles.
   1.593 +     *
   1.594 +     * @param arguments the arguments to pass to the target
   1.595 +     * @return the result returned by the target
   1.596 +     * @throws ClassCastException if an argument cannot be converted by reference casting
   1.597 +     * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
   1.598 +     * @throws Throwable anything thrown by the target method invocation
   1.599 +     * @see MethodHandles#spreadInvoker
   1.600 +     */
   1.601 +    public Object invokeWithArguments(Object... arguments) throws Throwable {
   1.602 +        throw new IllegalStateException();
   1.603 +    }
   1.604 +
   1.605 +    /**
   1.606 +     * Performs a variable arity invocation, passing the arguments in the given array
   1.607 +     * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
   1.608 +     * which mentions only the type {@code Object}, and whose arity is the length
   1.609 +     * of the argument array.
   1.610 +     * <p>
   1.611 +     * This method is also equivalent to the following code:
   1.612 +     * <blockquote><pre>{@code
   1.613 +     *   invokeWithArguments(arguments.toArray()
   1.614 +     * }</pre></blockquote>
   1.615 +     *
   1.616 +     * @param arguments the arguments to pass to the target
   1.617 +     * @return the result returned by the target
   1.618 +     * @throws NullPointerException if {@code arguments} is a null reference
   1.619 +     * @throws ClassCastException if an argument cannot be converted by reference casting
   1.620 +     * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
   1.621 +     * @throws Throwable anything thrown by the target method invocation
   1.622 +     */
   1.623 +    public Object invokeWithArguments(java.util.List<?> arguments) throws Throwable {
   1.624 +        return invokeWithArguments(arguments.toArray());
   1.625 +    }
   1.626 +
   1.627 +    /**
   1.628 +     * Produces an adapter method handle which adapts the type of the
   1.629 +     * current method handle to a new type.
   1.630 +     * The resulting method handle is guaranteed to report a type
   1.631 +     * which is equal to the desired new type.
   1.632 +     * <p>
   1.633 +     * If the original type and new type are equal, returns {@code this}.
   1.634 +     * <p>
   1.635 +     * The new method handle, when invoked, will perform the following
   1.636 +     * steps:
   1.637 +     * <ul>
   1.638 +     * <li>Convert the incoming argument list to match the original
   1.639 +     *     method handle's argument list.
   1.640 +     * <li>Invoke the original method handle on the converted argument list.
   1.641 +     * <li>Convert any result returned by the original method handle
   1.642 +     *     to the return type of new method handle.
   1.643 +     * </ul>
   1.644 +     * <p>
   1.645 +     * This method provides the crucial behavioral difference between
   1.646 +     * {@link #invokeExact invokeExact} and plain, inexact {@link #invoke invoke}.
   1.647 +     * The two methods
   1.648 +     * perform the same steps when the caller's type descriptor exactly m atches
   1.649 +     * the callee's, but when the types differ, plain {@link #invoke invoke}
   1.650 +     * also calls {@code asType} (or some internal equivalent) in order
   1.651 +     * to match up the caller's and callee's types.
   1.652 +     * <p>
   1.653 +     * If the current method is a variable arity method handle
   1.654 +     * argument list conversion may involve the conversion and collection
   1.655 +     * of several arguments into an array, as
   1.656 +     * {@linkplain #asVarargsCollector described elsewhere}.
   1.657 +     * In every other case, all conversions are applied <em>pairwise</em>,
   1.658 +     * which means that each argument or return value is converted to
   1.659 +     * exactly one argument or return value (or no return value).
   1.660 +     * The applied conversions are defined by consulting the
   1.661 +     * the corresponding component types of the old and new
   1.662 +     * method handle types.
   1.663 +     * <p>
   1.664 +     * Let <em>T0</em> and <em>T1</em> be corresponding new and old parameter types,
   1.665 +     * or old and new return types.  Specifically, for some valid index {@code i}, let
   1.666 +     * <em>T0</em>{@code =newType.parameterType(i)} and <em>T1</em>{@code =this.type().parameterType(i)}.
   1.667 +     * Or else, going the other way for return values, let
   1.668 +     * <em>T0</em>{@code =this.type().returnType()} and <em>T1</em>{@code =newType.returnType()}.
   1.669 +     * If the types are the same, the new method handle makes no change
   1.670 +     * to the corresponding argument or return value (if any).
   1.671 +     * Otherwise, one of the following conversions is applied
   1.672 +     * if possible:
   1.673 +     * <ul>
   1.674 +     * <li>If <em>T0</em> and <em>T1</em> are references, then a cast to <em>T1</em> is applied.
   1.675 +     *     (The types do not need to be related in any particular way.
   1.676 +     *     This is because a dynamic value of null can convert to any reference type.)
   1.677 +     * <li>If <em>T0</em> and <em>T1</em> are primitives, then a Java method invocation
   1.678 +     *     conversion (JLS 5.3) is applied, if one exists.
   1.679 +     *     (Specifically, <em>T0</em> must convert to <em>T1</em> by a widening primitive conversion.)
   1.680 +     * <li>If <em>T0</em> is a primitive and <em>T1</em> a reference,
   1.681 +     *     a Java casting conversion (JLS 5.5) is applied if one exists.
   1.682 +     *     (Specifically, the value is boxed from <em>T0</em> to its wrapper class,
   1.683 +     *     which is then widened as needed to <em>T1</em>.)
   1.684 +     * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
   1.685 +     *     conversion will be applied at runtime, possibly followed
   1.686 +     *     by a Java method invocation conversion (JLS 5.3)
   1.687 +     *     on the primitive value.  (These are the primitive widening conversions.)
   1.688 +     *     <em>T0</em> must be a wrapper class or a supertype of one.
   1.689 +     *     (In the case where <em>T0</em> is Object, these are the conversions
   1.690 +     *     allowed by {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.)
   1.691 +     *     The unboxing conversion must have a possibility of success, which means that
   1.692 +     *     if <em>T0</em> is not itself a wrapper class, there must exist at least one
   1.693 +     *     wrapper class <em>TW</em> which is a subtype of <em>T0</em> and whose unboxed
   1.694 +     *     primitive value can be widened to <em>T1</em>.
   1.695 +     * <li>If the return type <em>T1</em> is marked as void, any returned value is discarded
   1.696 +     * <li>If the return type <em>T0</em> is void and <em>T1</em> a reference, a null value is introduced.
   1.697 +     * <li>If the return type <em>T0</em> is void and <em>T1</em> a primitive,
   1.698 +     *     a zero value is introduced.
   1.699 +     * </ul>
   1.700 +    * (<em>Note:</em> Both <em>T0</em> and <em>T1</em> may be regarded as static types,
   1.701 +     * because neither corresponds specifically to the <em>dynamic type</em> of any
   1.702 +     * actual argument or return value.)
   1.703 +     * <p>
   1.704 +     * The method handle conversion cannot be made if any one of the required
   1.705 +     * pairwise conversions cannot be made.
   1.706 +     * <p>
   1.707 +     * At runtime, the conversions applied to reference arguments
   1.708 +     * or return values may require additional runtime checks which can fail.
   1.709 +     * An unboxing operation may fail because the original reference is null,
   1.710 +     * causing a {@link java.lang.NullPointerException NullPointerException}.
   1.711 +     * An unboxing operation or a reference cast may also fail on a reference
   1.712 +     * to an object of the wrong type,
   1.713 +     * causing a {@link java.lang.ClassCastException ClassCastException}.
   1.714 +     * Although an unboxing operation may accept several kinds of wrappers,
   1.715 +     * if none are available, a {@code ClassCastException} will be thrown.
   1.716 +     *
   1.717 +     * @param newType the expected type of the new method handle
   1.718 +     * @return a method handle which delegates to {@code this} after performing
   1.719 +     *           any necessary argument conversions, and arranges for any
   1.720 +     *           necessary return value conversions
   1.721 +     * @throws NullPointerException if {@code newType} is a null reference
   1.722 +     * @throws WrongMethodTypeException if the conversion cannot be made
   1.723 +     * @see MethodHandles#explicitCastArguments
   1.724 +     */
   1.725 +    public MethodHandle asType(MethodType newType) {
   1.726 +        throw new IllegalStateException();
   1.727 +    }
   1.728 +
   1.729 +    /**
   1.730 +     * Makes an <em>array-spreading</em> method handle, which accepts a trailing array argument
   1.731 +     * and spreads its elements as positional arguments.
   1.732 +     * The new method handle adapts, as its <i>target</i>,
   1.733 +     * the current method handle.  The type of the adapter will be
   1.734 +     * the same as the type of the target, except that the final
   1.735 +     * {@code arrayLength} parameters of the target's type are replaced
   1.736 +     * by a single array parameter of type {@code arrayType}.
   1.737 +     * <p>
   1.738 +     * If the array element type differs from any of the corresponding
   1.739 +     * argument types on the original target,
   1.740 +     * the original target is adapted to take the array elements directly,
   1.741 +     * as if by a call to {@link #asType asType}.
   1.742 +     * <p>
   1.743 +     * When called, the adapter replaces a trailing array argument
   1.744 +     * by the array's elements, each as its own argument to the target.
   1.745 +     * (The order of the arguments is preserved.)
   1.746 +     * They are converted pairwise by casting and/or unboxing
   1.747 +     * to the types of the trailing parameters of the target.
   1.748 +     * Finally the target is called.
   1.749 +     * What the target eventually returns is returned unchanged by the adapter.
   1.750 +     * <p>
   1.751 +     * Before calling the target, the adapter verifies that the array
   1.752 +     * contains exactly enough elements to provide a correct argument count
   1.753 +     * to the target method handle.
   1.754 +     * (The array may also be null when zero elements are required.)
   1.755 +     * <p>
   1.756 +     * If, when the adapter is called, the supplied array argument does
   1.757 +     * not have the correct number of elements, the adapter will throw
   1.758 +     * an {@link IllegalArgumentException} instead of invoking the target.
   1.759 +     * <p>
   1.760 +     * Here are some simple examples of array-spreading method handles:
   1.761 +     * <blockquote><pre>{@code
   1.762 +MethodHandle equals = publicLookup()
   1.763 +  .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
   1.764 +assert( (boolean) equals.invokeExact("me", (Object)"me"));
   1.765 +assert(!(boolean) equals.invokeExact("me", (Object)"thee"));
   1.766 +// spread both arguments from a 2-array:
   1.767 +MethodHandle eq2 = equals.asSpreader(Object[].class, 2);
   1.768 +assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" }));
   1.769 +assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
   1.770 +// try to spread from anything but a 2-array:
   1.771 +for (int n = 0; n <= 10; n++) {
   1.772 +  Object[] badArityArgs = (n == 2 ? null : new Object[n]);
   1.773 +  try { assert((boolean) eq2.invokeExact(badArityArgs) && false); }
   1.774 +  catch (IllegalArgumentException ex) { } // OK
   1.775 +}
   1.776 +// spread both arguments from a String array:
   1.777 +MethodHandle eq2s = equals.asSpreader(String[].class, 2);
   1.778 +assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" }));
   1.779 +assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" }));
   1.780 +// spread second arguments from a 1-array:
   1.781 +MethodHandle eq1 = equals.asSpreader(Object[].class, 1);
   1.782 +assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" }));
   1.783 +assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" }));
   1.784 +// spread no arguments from a 0-array or null:
   1.785 +MethodHandle eq0 = equals.asSpreader(Object[].class, 0);
   1.786 +assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0]));
   1.787 +assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null));
   1.788 +// asSpreader and asCollector are approximate inverses:
   1.789 +for (int n = 0; n <= 2; n++) {
   1.790 +    for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) {
   1.791 +        MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n);
   1.792 +        assert( (boolean) equals2.invokeWithArguments("me", "me"));
   1.793 +        assert(!(boolean) equals2.invokeWithArguments("me", "thee"));
   1.794 +    }
   1.795 +}
   1.796 +MethodHandle caToString = publicLookup()
   1.797 +  .findStatic(Arrays.class, "toString", methodType(String.class, char[].class));
   1.798 +assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray()));
   1.799 +MethodHandle caString3 = caToString.asCollector(char[].class, 3);
   1.800 +assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
   1.801 +MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
   1.802 +assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
   1.803 +     * }</pre></blockquote>
   1.804 +     * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments
   1.805 +     * @param arrayLength the number of arguments to spread from an incoming array argument
   1.806 +     * @return a new method handle which spreads its final array argument,
   1.807 +     *         before calling the original method handle
   1.808 +     * @throws NullPointerException if {@code arrayType} is a null reference
   1.809 +     * @throws IllegalArgumentException if {@code arrayType} is not an array type,
   1.810 +     *         or if target does not have at least
   1.811 +     *         {@code arrayLength} parameter types,
   1.812 +     *         or if {@code arrayLength} is negative,
   1.813 +     *         or if the resulting method handle's type would have
   1.814 +     *         <a href="MethodHandle.html#maxarity">too many parameters</a>
   1.815 +     * @throws WrongMethodTypeException if the implied {@code asType} call fails
   1.816 +     * @see #asCollector
   1.817 +     */
   1.818 +    public MethodHandle asSpreader(Class<?> arrayType, int arrayLength) {
   1.819 +        throw new IllegalStateException();
   1.820 +    }
   1.821 +
   1.822 +    /**
   1.823 +     * Makes an <em>array-collecting</em> method handle, which accepts a given number of trailing
   1.824 +     * positional arguments and collects them into an array argument.
   1.825 +     * The new method handle adapts, as its <i>target</i>,
   1.826 +     * the current method handle.  The type of the adapter will be
   1.827 +     * the same as the type of the target, except that a single trailing
   1.828 +     * parameter (usually of type {@code arrayType}) is replaced by
   1.829 +     * {@code arrayLength} parameters whose type is element type of {@code arrayType}.
   1.830 +     * <p>
   1.831 +     * If the array type differs from the final argument type on the original target,
   1.832 +     * the original target is adapted to take the array type directly,
   1.833 +     * as if by a call to {@link #asType asType}.
   1.834 +     * <p>
   1.835 +     * When called, the adapter replaces its trailing {@code arrayLength}
   1.836 +     * arguments by a single new array of type {@code arrayType}, whose elements
   1.837 +     * comprise (in order) the replaced arguments.
   1.838 +     * Finally the target is called.
   1.839 +     * What the target eventually returns is returned unchanged by the adapter.
   1.840 +     * <p>
   1.841 +     * (The array may also be a shared constant when {@code arrayLength} is zero.)
   1.842 +     * <p>
   1.843 +     * (<em>Note:</em> The {@code arrayType} is often identical to the last
   1.844 +     * parameter type of the original target.
   1.845 +     * It is an explicit argument for symmetry with {@code asSpreader}, and also
   1.846 +     * to allow the target to use a simple {@code Object} as its last parameter type.)
   1.847 +     * <p>
   1.848 +     * In order to create a collecting adapter which is not restricted to a particular
   1.849 +     * number of collected arguments, use {@link #asVarargsCollector asVarargsCollector} instead.
   1.850 +     * <p>
   1.851 +     * Here are some examples of array-collecting method handles:
   1.852 +     * <blockquote><pre>{@code
   1.853 +MethodHandle deepToString = publicLookup()
   1.854 +  .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
   1.855 +assertEquals("[won]",   (String) deepToString.invokeExact(new Object[]{"won"}));
   1.856 +MethodHandle ts1 = deepToString.asCollector(Object[].class, 1);
   1.857 +assertEquals(methodType(String.class, Object.class), ts1.type());
   1.858 +//assertEquals("[won]", (String) ts1.invokeExact(         new Object[]{"won"})); //FAIL
   1.859 +assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"}));
   1.860 +// arrayType can be a subtype of Object[]
   1.861 +MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
   1.862 +assertEquals(methodType(String.class, String.class, String.class), ts2.type());
   1.863 +assertEquals("[two, too]", (String) ts2.invokeExact("two", "too"));
   1.864 +MethodHandle ts0 = deepToString.asCollector(Object[].class, 0);
   1.865 +assertEquals("[]", (String) ts0.invokeExact());
   1.866 +// collectors can be nested, Lisp-style
   1.867 +MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2);
   1.868 +assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D")));
   1.869 +// arrayType can be any primitive array type
   1.870 +MethodHandle bytesToString = publicLookup()
   1.871 +  .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class))
   1.872 +  .asCollector(byte[].class, 3);
   1.873 +assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3));
   1.874 +MethodHandle longsToString = publicLookup()
   1.875 +  .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
   1.876 +  .asCollector(long[].class, 1);
   1.877 +assertEquals("[123]", (String) longsToString.invokeExact((long)123));
   1.878 +     * }</pre></blockquote>
   1.879 +     * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
   1.880 +     * @param arrayLength the number of arguments to collect into a new array argument
   1.881 +     * @return a new method handle which collects some trailing argument
   1.882 +     *         into an array, before calling the original method handle
   1.883 +     * @throws NullPointerException if {@code arrayType} is a null reference
   1.884 +     * @throws IllegalArgumentException if {@code arrayType} is not an array type
   1.885 +     *         or {@code arrayType} is not assignable to this method handle's trailing parameter type,
   1.886 +     *         or {@code arrayLength} is not a legal array size,
   1.887 +     *         or the resulting method handle's type would have
   1.888 +     *         <a href="MethodHandle.html#maxarity">too many parameters</a>
   1.889 +     * @throws WrongMethodTypeException if the implied {@code asType} call fails
   1.890 +     * @see #asSpreader
   1.891 +     * @see #asVarargsCollector
   1.892 +     */
   1.893 +    public MethodHandle asCollector(Class<?> arrayType, int arrayLength) {
   1.894 +        throw new IllegalStateException();
   1.895 +    }
   1.896 +
   1.897 +    /**
   1.898 +     * Makes a <em>variable arity</em> adapter which is able to accept
   1.899 +     * any number of trailing positional arguments and collect them
   1.900 +     * into an array argument.
   1.901 +     * <p>
   1.902 +     * The type and behavior of the adapter will be the same as
   1.903 +     * the type and behavior of the target, except that certain
   1.904 +     * {@code invoke} and {@code asType} requests can lead to
   1.905 +     * trailing positional arguments being collected into target's
   1.906 +     * trailing parameter.
   1.907 +     * Also, the last parameter type of the adapter will be
   1.908 +     * {@code arrayType}, even if the target has a different
   1.909 +     * last parameter type.
   1.910 +     * <p>
   1.911 +     * This transformation may return {@code this} if the method handle is
   1.912 +     * already of variable arity and its trailing parameter type
   1.913 +     * is identical to {@code arrayType}.
   1.914 +     * <p>
   1.915 +     * When called with {@link #invokeExact invokeExact}, the adapter invokes
   1.916 +     * the target with no argument changes.
   1.917 +     * (<em>Note:</em> This behavior is different from a
   1.918 +     * {@linkplain #asCollector fixed arity collector},
   1.919 +     * since it accepts a whole array of indeterminate length,
   1.920 +     * rather than a fixed number of arguments.)
   1.921 +     * <p>
   1.922 +     * When called with plain, inexact {@link #invoke invoke}, if the caller
   1.923 +     * type is the same as the adapter, the adapter invokes the target as with
   1.924 +     * {@code invokeExact}.
   1.925 +     * (This is the normal behavior for {@code invoke} when types match.)
   1.926 +     * <p>
   1.927 +     * Otherwise, if the caller and adapter arity are the same, and the
   1.928 +     * trailing parameter type of the caller is a reference type identical to
   1.929 +     * or assignable to the trailing parameter type of the adapter,
   1.930 +     * the arguments and return values are converted pairwise,
   1.931 +     * as if by {@link #asType asType} on a fixed arity
   1.932 +     * method handle.
   1.933 +     * <p>
   1.934 +     * Otherwise, the arities differ, or the adapter's trailing parameter
   1.935 +     * type is not assignable from the corresponding caller type.
   1.936 +     * In this case, the adapter replaces all trailing arguments from
   1.937 +     * the original trailing argument position onward, by
   1.938 +     * a new array of type {@code arrayType}, whose elements
   1.939 +     * comprise (in order) the replaced arguments.
   1.940 +     * <p>
   1.941 +     * The caller type must provides as least enough arguments,
   1.942 +     * and of the correct type, to satisfy the target's requirement for
   1.943 +     * positional arguments before the trailing array argument.
   1.944 +     * Thus, the caller must supply, at a minimum, {@code N-1} arguments,
   1.945 +     * where {@code N} is the arity of the target.
   1.946 +     * Also, there must exist conversions from the incoming arguments
   1.947 +     * to the target's arguments.
   1.948 +     * As with other uses of plain {@code invoke}, if these basic
   1.949 +     * requirements are not fulfilled, a {@code WrongMethodTypeException}
   1.950 +     * may be thrown.
   1.951 +     * <p>
   1.952 +     * In all cases, what the target eventually returns is returned unchanged by the adapter.
   1.953 +     * <p>
   1.954 +     * In the final case, it is exactly as if the target method handle were
   1.955 +     * temporarily adapted with a {@linkplain #asCollector fixed arity collector}
   1.956 +     * to the arity required by the caller type.
   1.957 +     * (As with {@code asCollector}, if the array length is zero,
   1.958 +     * a shared constant may be used instead of a new array.
   1.959 +     * If the implied call to {@code asCollector} would throw
   1.960 +     * an {@code IllegalArgumentException} or {@code WrongMethodTypeException},
   1.961 +     * the call to the variable arity adapter must throw
   1.962 +     * {@code WrongMethodTypeException}.)
   1.963 +     * <p>
   1.964 +     * The behavior of {@link #asType asType} is also specialized for
   1.965 +     * variable arity adapters, to maintain the invariant that
   1.966 +     * plain, inexact {@code invoke} is always equivalent to an {@code asType}
   1.967 +     * call to adjust the target type, followed by {@code invokeExact}.
   1.968 +     * Therefore, a variable arity adapter responds
   1.969 +     * to an {@code asType} request by building a fixed arity collector,
   1.970 +     * if and only if the adapter and requested type differ either
   1.971 +     * in arity or trailing argument type.
   1.972 +     * The resulting fixed arity collector has its type further adjusted
   1.973 +     * (if necessary) to the requested type by pairwise conversion,
   1.974 +     * as if by another application of {@code asType}.
   1.975 +     * <p>
   1.976 +     * When a method handle is obtained by executing an {@code ldc} instruction
   1.977 +     * of a {@code CONSTANT_MethodHandle} constant, and the target method is marked
   1.978 +     * as a variable arity method (with the modifier bit {@code 0x0080}),
   1.979 +     * the method handle will accept multiple arities, as if the method handle
   1.980 +     * constant were created by means of a call to {@code asVarargsCollector}.
   1.981 +     * <p>
   1.982 +     * In order to create a collecting adapter which collects a predetermined
   1.983 +     * number of arguments, and whose type reflects this predetermined number,
   1.984 +     * use {@link #asCollector asCollector} instead.
   1.985 +     * <p>
   1.986 +     * No method handle transformations produce new method handles with
   1.987 +     * variable arity, unless they are documented as doing so.
   1.988 +     * Therefore, besides {@code asVarargsCollector},
   1.989 +     * all methods in {@code MethodHandle} and {@code MethodHandles}
   1.990 +     * will return a method handle with fixed arity,
   1.991 +     * except in the cases where they are specified to return their original
   1.992 +     * operand (e.g., {@code asType} of the method handle's own type).
   1.993 +     * <p>
   1.994 +     * Calling {@code asVarargsCollector} on a method handle which is already
   1.995 +     * of variable arity will produce a method handle with the same type and behavior.
   1.996 +     * It may (or may not) return the original variable arity method handle.
   1.997 +     * <p>
   1.998 +     * Here is an example, of a list-making variable arity method handle:
   1.999 +     * <blockquote><pre>{@code
  1.1000 +MethodHandle deepToString = publicLookup()
  1.1001 +  .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
  1.1002 +MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
  1.1003 +assertEquals("[won]",   (String) ts1.invokeExact(    new Object[]{"won"}));
  1.1004 +assertEquals("[won]",   (String) ts1.invoke(         new Object[]{"won"}));
  1.1005 +assertEquals("[won]",   (String) ts1.invoke(                      "won" ));
  1.1006 +assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"}));
  1.1007 +// findStatic of Arrays.asList(...) produces a variable arity method handle:
  1.1008 +MethodHandle asList = publicLookup()
  1.1009 +  .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
  1.1010 +assertEquals(methodType(List.class, Object[].class), asList.type());
  1.1011 +assert(asList.isVarargsCollector());
  1.1012 +assertEquals("[]", asList.invoke().toString());
  1.1013 +assertEquals("[1]", asList.invoke(1).toString());
  1.1014 +assertEquals("[two, too]", asList.invoke("two", "too").toString());
  1.1015 +String[] argv = { "three", "thee", "tee" };
  1.1016 +assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
  1.1017 +assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString());
  1.1018 +List ls = (List) asList.invoke((Object)argv);
  1.1019 +assertEquals(1, ls.size());
  1.1020 +assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
  1.1021 +     * }</pre></blockquote>
  1.1022 +     * <p style="font-size:smaller;">
  1.1023 +     * <em>Discussion:</em>
  1.1024 +     * These rules are designed as a dynamically-typed variation
  1.1025 +     * of the Java rules for variable arity methods.
  1.1026 +     * In both cases, callers to a variable arity method or method handle
  1.1027 +     * can either pass zero or more positional arguments, or else pass
  1.1028 +     * pre-collected arrays of any length.  Users should be aware of the
  1.1029 +     * special role of the final argument, and of the effect of a
  1.1030 +     * type match on that final argument, which determines whether
  1.1031 +     * or not a single trailing argument is interpreted as a whole
  1.1032 +     * array or a single element of an array to be collected.
  1.1033 +     * Note that the dynamic type of the trailing argument has no
  1.1034 +     * effect on this decision, only a comparison between the symbolic
  1.1035 +     * type descriptor of the call site and the type descriptor of the method handle.)
  1.1036 +     *
  1.1037 +     * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
  1.1038 +     * @return a new method handle which can collect any number of trailing arguments
  1.1039 +     *         into an array, before calling the original method handle
  1.1040 +     * @throws NullPointerException if {@code arrayType} is a null reference
  1.1041 +     * @throws IllegalArgumentException if {@code arrayType} is not an array type
  1.1042 +     *         or {@code arrayType} is not assignable to this method handle's trailing parameter type
  1.1043 +     * @see #asCollector
  1.1044 +     * @see #isVarargsCollector
  1.1045 +     * @see #asFixedArity
  1.1046 +     */
  1.1047 +    public MethodHandle asVarargsCollector(Class<?> arrayType) {
  1.1048 +        throw new IllegalStateException();
  1.1049 +    }
  1.1050 +
  1.1051 +    /**
  1.1052 +     * Determines if this method handle
  1.1053 +     * supports {@linkplain #asVarargsCollector variable arity} calls.
  1.1054 +     * Such method handles arise from the following sources:
  1.1055 +     * <ul>
  1.1056 +     * <li>a call to {@linkplain #asVarargsCollector asVarargsCollector}
  1.1057 +     * <li>a call to a {@linkplain java.lang.invoke.MethodHandles.Lookup lookup method}
  1.1058 +     *     which resolves to a variable arity Java method or constructor
  1.1059 +     * <li>an {@code ldc} instruction of a {@code CONSTANT_MethodHandle}
  1.1060 +     *     which resolves to a variable arity Java method or constructor
  1.1061 +     * </ul>
  1.1062 +     * @return true if this method handle accepts more than one arity of plain, inexact {@code invoke} calls
  1.1063 +     * @see #asVarargsCollector
  1.1064 +     * @see #asFixedArity
  1.1065 +     */
  1.1066 +    public boolean isVarargsCollector() {
  1.1067 +        return false;
  1.1068 +    }
  1.1069 +
  1.1070 +    /**
  1.1071 +     * Makes a <em>fixed arity</em> method handle which is otherwise
  1.1072 +     * equivalent to the current method handle.
  1.1073 +     * <p>
  1.1074 +     * If the current method handle is not of
  1.1075 +     * {@linkplain #asVarargsCollector variable arity},
  1.1076 +     * the current method handle is returned.
  1.1077 +     * This is true even if the current method handle
  1.1078 +     * could not be a valid input to {@code asVarargsCollector}.
  1.1079 +     * <p>
  1.1080 +     * Otherwise, the resulting fixed-arity method handle has the same
  1.1081 +     * type and behavior of the current method handle,
  1.1082 +     * except that {@link #isVarargsCollector isVarargsCollector}
  1.1083 +     * will be false.
  1.1084 +     * The fixed-arity method handle may (or may not) be the
  1.1085 +     * a previous argument to {@code asVarargsCollector}.
  1.1086 +     * <p>
  1.1087 +     * Here is an example, of a list-making variable arity method handle:
  1.1088 +     * <blockquote><pre>{@code
  1.1089 +MethodHandle asListVar = publicLookup()
  1.1090 +  .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
  1.1091 +  .asVarargsCollector(Object[].class);
  1.1092 +MethodHandle asListFix = asListVar.asFixedArity();
  1.1093 +assertEquals("[1]", asListVar.invoke(1).toString());
  1.1094 +Exception caught = null;
  1.1095 +try { asListFix.invoke((Object)1); }
  1.1096 +catch (Exception ex) { caught = ex; }
  1.1097 +assert(caught instanceof ClassCastException);
  1.1098 +assertEquals("[two, too]", asListVar.invoke("two", "too").toString());
  1.1099 +try { asListFix.invoke("two", "too"); }
  1.1100 +catch (Exception ex) { caught = ex; }
  1.1101 +assert(caught instanceof WrongMethodTypeException);
  1.1102 +Object[] argv = { "three", "thee", "tee" };
  1.1103 +assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString());
  1.1104 +assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
  1.1105 +assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
  1.1106 +assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
  1.1107 +     * }</pre></blockquote>
  1.1108 +     *
  1.1109 +     * @return a new method handle which accepts only a fixed number of arguments
  1.1110 +     * @see #asVarargsCollector
  1.1111 +     * @see #isVarargsCollector
  1.1112 +     */
  1.1113 +    public MethodHandle asFixedArity() {
  1.1114 +        assert(!isVarargsCollector());
  1.1115 +        return this;
  1.1116 +    }
  1.1117 +
  1.1118 +    /**
  1.1119 +     * Binds a value {@code x} to the first argument of a method handle, without invoking it.
  1.1120 +     * The new method handle adapts, as its <i>target</i>,
  1.1121 +     * the current method handle by binding it to the given argument.
  1.1122 +     * The type of the bound handle will be
  1.1123 +     * the same as the type of the target, except that a single leading
  1.1124 +     * reference parameter will be omitted.
  1.1125 +     * <p>
  1.1126 +     * When called, the bound handle inserts the given value {@code x}
  1.1127 +     * as a new leading argument to the target.  The other arguments are
  1.1128 +     * also passed unchanged.
  1.1129 +     * What the target eventually returns is returned unchanged by the bound handle.
  1.1130 +     * <p>
  1.1131 +     * The reference {@code x} must be convertible to the first parameter
  1.1132 +     * type of the target.
  1.1133 +     * <p>
  1.1134 +     * (<em>Note:</em>  Because method handles are immutable, the target method handle
  1.1135 +     * retains its original type and behavior.)
  1.1136 +     * @param x  the value to bind to the first argument of the target
  1.1137 +     * @return a new method handle which prepends the given value to the incoming
  1.1138 +     *         argument list, before calling the original method handle
  1.1139 +     * @throws IllegalArgumentException if the target does not have a
  1.1140 +     *         leading parameter type that is a reference type
  1.1141 +     * @throws ClassCastException if {@code x} cannot be converted
  1.1142 +     *         to the leading parameter type of the target
  1.1143 +     * @see MethodHandles#insertArguments
  1.1144 +     */
  1.1145 +    public MethodHandle bindTo(Object x) {
  1.1146 +        throw new IllegalStateException();
  1.1147 +    }
  1.1148 +
  1.1149 +    /**
  1.1150 +     * Returns a string representation of the method handle,
  1.1151 +     * starting with the string {@code "MethodHandle"} and
  1.1152 +     * ending with the string representation of the method handle's type.
  1.1153 +     * In other words, this method returns a string equal to the value of:
  1.1154 +     * <blockquote><pre>{@code
  1.1155 +     * "MethodHandle" + type().toString()
  1.1156 +     * }</pre></blockquote>
  1.1157 +     * <p>
  1.1158 +     * (<em>Note:</em>  Future releases of this API may add further information
  1.1159 +     * to the string representation.
  1.1160 +     * Therefore, the present syntax should not be parsed by applications.)
  1.1161 +     *
  1.1162 +     * @return a string representation of the method handle
  1.1163 +     */
  1.1164 +    @Override
  1.1165 +    public String toString() {
  1.1166 +        return standardString();
  1.1167 +    }
  1.1168 +    String standardString() {
  1.1169 +        throw new IllegalStateException();
  1.1170 +    }
  1.1171 +}