rt/emul/compact/src/main/java/java/lang/invoke/MethodHandle.java
branchjdk8
changeset 1675 cd50c1894ce5
parent 1674 eca8e9c3ec3e
child 1678 35daab73e225
     1.1 --- a/rt/emul/compact/src/main/java/java/lang/invoke/MethodHandle.java	Sun Aug 17 20:09:05 2014 +0200
     1.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.3 @@ -1,1494 +0,0 @@
     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 -import sun.invoke.util.*;
    1.34 -
    1.35 -import static java.lang.invoke.MethodHandleStatics.*;
    1.36 -import java.util.logging.Level;
    1.37 -import java.util.logging.Logger;
    1.38 -
    1.39 -/**
    1.40 - * A method handle is a typed, directly executable reference to an underlying method,
    1.41 - * constructor, field, or similar low-level operation, with optional
    1.42 - * transformations of arguments or return values.
    1.43 - * These transformations are quite general, and include such patterns as
    1.44 - * {@linkplain #asType conversion},
    1.45 - * {@linkplain #bindTo insertion},
    1.46 - * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion},
    1.47 - * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}.
    1.48 - *
    1.49 - * <h1>Method handle contents</h1>
    1.50 - * Method handles are dynamically and strongly typed according to their parameter and return types.
    1.51 - * They are not distinguished by the name or the defining class of their underlying methods.
    1.52 - * A method handle must be invoked using a symbolic type descriptor which matches
    1.53 - * the method handle's own {@linkplain #type type descriptor}.
    1.54 - * <p>
    1.55 - * Every method handle reports its type descriptor via the {@link #type type} accessor.
    1.56 - * This type descriptor is a {@link java.lang.invoke.MethodType MethodType} object,
    1.57 - * whose structure is a series of classes, one of which is
    1.58 - * the return type of the method (or {@code void.class} if none).
    1.59 - * <p>
    1.60 - * A method handle's type controls the types of invocations it accepts,
    1.61 - * and the kinds of transformations that apply to it.
    1.62 - * <p>
    1.63 - * A method handle contains a pair of special invoker methods
    1.64 - * called {@link #invokeExact invokeExact} and {@link #invoke invoke}.
    1.65 - * Both invoker methods provide direct access to the method handle's
    1.66 - * underlying method, constructor, field, or other operation,
    1.67 - * as modified by transformations of arguments and return values.
    1.68 - * Both invokers accept calls which exactly match the method handle's own type.
    1.69 - * The plain, inexact invoker also accepts a range of other call types.
    1.70 - * <p>
    1.71 - * Method handles are immutable and have no visible state.
    1.72 - * Of course, they can be bound to underlying methods or data which exhibit state.
    1.73 - * With respect to the Java Memory Model, any method handle will behave
    1.74 - * as if all of its (internal) fields are final variables.  This means that any method
    1.75 - * handle made visible to the application will always be fully formed.
    1.76 - * This is true even if the method handle is published through a shared
    1.77 - * variable in a data race.
    1.78 - * <p>
    1.79 - * Method handles cannot be subclassed by the user.
    1.80 - * Implementations may (or may not) create internal subclasses of {@code MethodHandle}
    1.81 - * which may be visible via the {@link java.lang.Object#getClass Object.getClass}
    1.82 - * operation.  The programmer should not draw conclusions about a method handle
    1.83 - * from its specific class, as the method handle class hierarchy (if any)
    1.84 - * may change from time to time or across implementations from different vendors.
    1.85 - *
    1.86 - * <h1>Method handle compilation</h1>
    1.87 - * A Java method call expression naming {@code invokeExact} or {@code invoke}
    1.88 - * can invoke a method handle from Java source code.
    1.89 - * From the viewpoint of source code, these methods can take any arguments
    1.90 - * and their result can be cast to any return type.
    1.91 - * Formally this is accomplished by giving the invoker methods
    1.92 - * {@code Object} return types and variable arity {@code Object} arguments,
    1.93 - * but they have an additional quality called <em>signature polymorphism</em>
    1.94 - * which connects this freedom of invocation directly to the JVM execution stack.
    1.95 - * <p>
    1.96 - * As is usual with virtual methods, source-level calls to {@code invokeExact}
    1.97 - * and {@code invoke} compile to an {@code invokevirtual} instruction.
    1.98 - * More unusually, the compiler must record the actual argument types,
    1.99 - * and may not perform method invocation conversions on the arguments.
   1.100 - * Instead, it must push them on the stack according to their own unconverted types.
   1.101 - * The method handle object itself is pushed on the stack before the arguments.
   1.102 - * The compiler then calls the method handle with a symbolic type descriptor which
   1.103 - * describes the argument and return types.
   1.104 - * <p>
   1.105 - * To issue a complete symbolic type descriptor, the compiler must also determine
   1.106 - * the return type.  This is based on a cast on the method invocation expression,
   1.107 - * if there is one, or else {@code Object} if the invocation is an expression
   1.108 - * or else {@code void} if the invocation is a statement.
   1.109 - * The cast may be to a primitive type (but not {@code void}).
   1.110 - * <p>
   1.111 - * As a corner case, an uncasted {@code null} argument is given
   1.112 - * a symbolic type descriptor of {@code java.lang.Void}.
   1.113 - * The ambiguity with the type {@code Void} is harmless, since there are no references of type
   1.114 - * {@code Void} except the null reference.
   1.115 - *
   1.116 - * <h1>Method handle invocation</h1>
   1.117 - * The first time a {@code invokevirtual} instruction is executed
   1.118 - * it is linked, by symbolically resolving the names in the instruction
   1.119 - * and verifying that the method call is statically legal.
   1.120 - * This is true of calls to {@code invokeExact} and {@code invoke}.
   1.121 - * In this case, the symbolic type descriptor emitted by the compiler is checked for
   1.122 - * correct syntax and names it contains are resolved.
   1.123 - * Thus, an {@code invokevirtual} instruction which invokes
   1.124 - * a method handle will always link, as long
   1.125 - * as the symbolic type descriptor is syntactically well-formed
   1.126 - * and the types exist.
   1.127 - * <p>
   1.128 - * When the {@code invokevirtual} is executed after linking,
   1.129 - * the receiving method handle's type is first checked by the JVM
   1.130 - * to ensure that it matches the symbolic type descriptor.
   1.131 - * If the type match fails, it means that the method which the
   1.132 - * caller is invoking is not present on the individual
   1.133 - * method handle being invoked.
   1.134 - * <p>
   1.135 - * In the case of {@code invokeExact}, the type descriptor of the invocation
   1.136 - * (after resolving symbolic type names) must exactly match the method type
   1.137 - * of the receiving method handle.
   1.138 - * In the case of plain, inexact {@code invoke}, the resolved type descriptor
   1.139 - * must be a valid argument to the receiver's {@link #asType asType} method.
   1.140 - * Thus, plain {@code invoke} is more permissive than {@code invokeExact}.
   1.141 - * <p>
   1.142 - * After type matching, a call to {@code invokeExact} directly
   1.143 - * and immediately invoke the method handle's underlying method
   1.144 - * (or other behavior, as the case may be).
   1.145 - * <p>
   1.146 - * A call to plain {@code invoke} works the same as a call to
   1.147 - * {@code invokeExact}, if the symbolic type descriptor specified by the caller
   1.148 - * exactly matches the method handle's own type.
   1.149 - * If there is a type mismatch, {@code invoke} attempts
   1.150 - * to adjust the type of the receiving method handle,
   1.151 - * as if by a call to {@link #asType asType},
   1.152 - * to obtain an exactly invokable method handle {@code M2}.
   1.153 - * This allows a more powerful negotiation of method type
   1.154 - * between caller and callee.
   1.155 - * <p>
   1.156 - * (<em>Note:</em> The adjusted method handle {@code M2} is not directly observable,
   1.157 - * and implementations are therefore not required to materialize it.)
   1.158 - *
   1.159 - * <h1>Invocation checking</h1>
   1.160 - * In typical programs, method handle type matching will usually succeed.
   1.161 - * But if a match fails, the JVM will throw a {@link WrongMethodTypeException},
   1.162 - * either directly (in the case of {@code invokeExact}) or indirectly as if
   1.163 - * by a failed call to {@code asType} (in the case of {@code invoke}).
   1.164 - * <p>
   1.165 - * Thus, a method type mismatch which might show up as a linkage error
   1.166 - * in a statically typed program can show up as
   1.167 - * a dynamic {@code WrongMethodTypeException}
   1.168 - * in a program which uses method handles.
   1.169 - * <p>
   1.170 - * Because method types contain "live" {@code Class} objects,
   1.171 - * method type matching takes into account both types names and class loaders.
   1.172 - * Thus, even if a method handle {@code M} is created in one
   1.173 - * class loader {@code L1} and used in another {@code L2},
   1.174 - * method handle calls are type-safe, because the caller's symbolic type
   1.175 - * descriptor, as resolved in {@code L2},
   1.176 - * is matched against the original callee method's symbolic type descriptor,
   1.177 - * as resolved in {@code L1}.
   1.178 - * The resolution in {@code L1} happens when {@code M} is created
   1.179 - * and its type is assigned, while the resolution in {@code L2} happens
   1.180 - * when the {@code invokevirtual} instruction is linked.
   1.181 - * <p>
   1.182 - * Apart from the checking of type descriptors,
   1.183 - * a method handle's capability to call its underlying method is unrestricted.
   1.184 - * If a method handle is formed on a non-public method by a class
   1.185 - * that has access to that method, the resulting handle can be used
   1.186 - * in any place by any caller who receives a reference to it.
   1.187 - * <p>
   1.188 - * Unlike with the Core Reflection API, where access is checked every time
   1.189 - * a reflective method is invoked,
   1.190 - * method handle access checking is performed
   1.191 - * <a href="MethodHandles.Lookup.html#access">when the method handle is created</a>.
   1.192 - * In the case of {@code ldc} (see below), access checking is performed as part of linking
   1.193 - * the constant pool entry underlying the constant method handle.
   1.194 - * <p>
   1.195 - * Thus, handles to non-public methods, or to methods in non-public classes,
   1.196 - * should generally be kept secret.
   1.197 - * They should not be passed to untrusted code unless their use from
   1.198 - * the untrusted code would be harmless.
   1.199 - *
   1.200 - * <h1>Method handle creation</h1>
   1.201 - * Java code can create a method handle that directly accesses
   1.202 - * any method, constructor, or field that is accessible to that code.
   1.203 - * This is done via a reflective, capability-based API called
   1.204 - * {@link java.lang.invoke.MethodHandles.Lookup MethodHandles.Lookup}
   1.205 - * For example, a static method handle can be obtained
   1.206 - * from {@link java.lang.invoke.MethodHandles.Lookup#findStatic Lookup.findStatic}.
   1.207 - * There are also conversion methods from Core Reflection API objects,
   1.208 - * such as {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
   1.209 - * <p>
   1.210 - * Like classes and strings, method handles that correspond to accessible
   1.211 - * fields, methods, and constructors can also be represented directly
   1.212 - * in a class file's constant pool as constants to be loaded by {@code ldc} bytecodes.
   1.213 - * A new type of constant pool entry, {@code CONSTANT_MethodHandle},
   1.214 - * refers directly to an associated {@code CONSTANT_Methodref},
   1.215 - * {@code CONSTANT_InterfaceMethodref}, or {@code CONSTANT_Fieldref}
   1.216 - * constant pool entry.
   1.217 - * (For full details on method handle constants,
   1.218 - * see sections 4.4.8 and 5.4.3.5 of the Java Virtual Machine Specification.)
   1.219 - * <p>
   1.220 - * Method handles produced by lookups or constant loads from methods or
   1.221 - * constructors with the variable arity modifier bit ({@code 0x0080})
   1.222 - * have a corresponding variable arity, as if they were defined with
   1.223 - * the help of {@link #asVarargsCollector asVarargsCollector}.
   1.224 - * <p>
   1.225 - * A method reference may refer either to a static or non-static method.
   1.226 - * In the non-static case, the method handle type includes an explicit
   1.227 - * receiver argument, prepended before any other arguments.
   1.228 - * In the method handle's type, the initial receiver argument is typed
   1.229 - * according to the class under which the method was initially requested.
   1.230 - * (E.g., if a non-static method handle is obtained via {@code ldc},
   1.231 - * the type of the receiver is the class named in the constant pool entry.)
   1.232 - * <p>
   1.233 - * Method handle constants are subject to the same link-time access checks
   1.234 - * their corresponding bytecode instructions, and the {@code ldc} instruction
   1.235 - * will throw corresponding linkage errors if the bytecode behaviors would
   1.236 - * throw such errors.
   1.237 - * <p>
   1.238 - * As a corollary of this, access to protected members is restricted
   1.239 - * to receivers only of the accessing class, or one of its subclasses,
   1.240 - * and the accessing class must in turn be a subclass (or package sibling)
   1.241 - * of the protected member's defining class.
   1.242 - * If a method reference refers to a protected non-static method or field
   1.243 - * of a class outside the current package, the receiver argument will
   1.244 - * be narrowed to the type of the accessing class.
   1.245 - * <p>
   1.246 - * When a method handle to a virtual method is invoked, the method is
   1.247 - * always looked up in the receiver (that is, the first argument).
   1.248 - * <p>
   1.249 - * A non-virtual method handle to a specific virtual method implementation
   1.250 - * can also be created.  These do not perform virtual lookup based on
   1.251 - * receiver type.  Such a method handle simulates the effect of
   1.252 - * an {@code invokespecial} instruction to the same method.
   1.253 - *
   1.254 - * <h1>Usage examples</h1>
   1.255 - * Here are some examples of usage:
   1.256 - * <blockquote><pre>{@code
   1.257 -Object x, y; String s; int i;
   1.258 -MethodType mt; MethodHandle mh;
   1.259 -MethodHandles.Lookup lookup = MethodHandles.lookup();
   1.260 -// mt is (char,char)String
   1.261 -mt = MethodType.methodType(String.class, char.class, char.class);
   1.262 -mh = lookup.findVirtual(String.class, "replace", mt);
   1.263 -s = (String) mh.invokeExact("daddy",'d','n');
   1.264 -// invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
   1.265 -assertEquals(s, "nanny");
   1.266 -// weakly typed invocation (using MHs.invoke)
   1.267 -s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
   1.268 -assertEquals(s, "savvy");
   1.269 -// mt is (Object[])List
   1.270 -mt = MethodType.methodType(java.util.List.class, Object[].class);
   1.271 -mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
   1.272 -assert(mh.isVarargsCollector());
   1.273 -x = mh.invoke("one", "two");
   1.274 -// invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
   1.275 -assertEquals(x, java.util.Arrays.asList("one","two"));
   1.276 -// mt is (Object,Object,Object)Object
   1.277 -mt = MethodType.genericMethodType(3);
   1.278 -mh = mh.asType(mt);
   1.279 -x = mh.invokeExact((Object)1, (Object)2, (Object)3);
   1.280 -// invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
   1.281 -assertEquals(x, java.util.Arrays.asList(1,2,3));
   1.282 -// mt is ()int
   1.283 -mt = MethodType.methodType(int.class);
   1.284 -mh = lookup.findVirtual(java.util.List.class, "size", mt);
   1.285 -i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
   1.286 -// invokeExact(Ljava/util/List;)I
   1.287 -assert(i == 3);
   1.288 -mt = MethodType.methodType(void.class, String.class);
   1.289 -mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
   1.290 -mh.invokeExact(System.out, "Hello, world.");
   1.291 -// invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
   1.292 - * }</pre></blockquote>
   1.293 - * Each of the above calls to {@code invokeExact} or plain {@code invoke}
   1.294 - * generates a single invokevirtual instruction with
   1.295 - * the symbolic type descriptor indicated in the following comment.
   1.296 - * In these examples, the helper method {@code assertEquals} is assumed to
   1.297 - * be a method which calls {@link java.util.Objects#equals(Object,Object) Objects.equals}
   1.298 - * on its arguments, and asserts that the result is true.
   1.299 - *
   1.300 - * <h1>Exceptions</h1>
   1.301 - * The methods {@code invokeExact} and {@code invoke} are declared
   1.302 - * to throw {@link java.lang.Throwable Throwable},
   1.303 - * which is to say that there is no static restriction on what a method handle
   1.304 - * can throw.  Since the JVM does not distinguish between checked
   1.305 - * and unchecked exceptions (other than by their class, of course),
   1.306 - * there is no particular effect on bytecode shape from ascribing
   1.307 - * checked exceptions to method handle invocations.  But in Java source
   1.308 - * code, methods which perform method handle calls must either explicitly
   1.309 - * throw {@code Throwable}, or else must catch all
   1.310 - * throwables locally, rethrowing only those which are legal in the context,
   1.311 - * and wrapping ones which are illegal.
   1.312 - *
   1.313 - * <h1><a name="sigpoly"></a>Signature polymorphism</h1>
   1.314 - * The unusual compilation and linkage behavior of
   1.315 - * {@code invokeExact} and plain {@code invoke}
   1.316 - * is referenced by the term <em>signature polymorphism</em>.
   1.317 - * As defined in the Java Language Specification,
   1.318 - * a signature polymorphic method is one which can operate with
   1.319 - * any of a wide range of call signatures and return types.
   1.320 - * <p>
   1.321 - * In source code, a call to a signature polymorphic method will
   1.322 - * compile, regardless of the requested symbolic type descriptor.
   1.323 - * As usual, the Java compiler emits an {@code invokevirtual}
   1.324 - * instruction with the given symbolic type descriptor against the named method.
   1.325 - * The unusual part is that the symbolic type descriptor is derived from
   1.326 - * the actual argument and return types, not from the method declaration.
   1.327 - * <p>
   1.328 - * When the JVM processes bytecode containing signature polymorphic calls,
   1.329 - * it will successfully link any such call, regardless of its symbolic type descriptor.
   1.330 - * (In order to retain type safety, the JVM will guard such calls with suitable
   1.331 - * dynamic type checks, as described elsewhere.)
   1.332 - * <p>
   1.333 - * Bytecode generators, including the compiler back end, are required to emit
   1.334 - * untransformed symbolic type descriptors for these methods.
   1.335 - * Tools which determine symbolic linkage are required to accept such
   1.336 - * untransformed descriptors, without reporting linkage errors.
   1.337 - *
   1.338 - * <h1>Interoperation between method handles and the Core Reflection API</h1>
   1.339 - * Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup Lookup} API,
   1.340 - * any class member represented by a Core Reflection API object
   1.341 - * can be converted to a behaviorally equivalent method handle.
   1.342 - * For example, a reflective {@link java.lang.reflect.Method Method} can
   1.343 - * be converted to a method handle using
   1.344 - * {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
   1.345 - * The resulting method handles generally provide more direct and efficient
   1.346 - * access to the underlying class members.
   1.347 - * <p>
   1.348 - * As a special case,
   1.349 - * when the Core Reflection API is used to view the signature polymorphic
   1.350 - * methods {@code invokeExact} or plain {@code invoke} in this class,
   1.351 - * they appear as ordinary non-polymorphic methods.
   1.352 - * Their reflective appearance, as viewed by
   1.353 - * {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod},
   1.354 - * is unaffected by their special status in this API.
   1.355 - * For example, {@link java.lang.reflect.Method#getModifiers Method.getModifiers}
   1.356 - * will report exactly those modifier bits required for any similarly
   1.357 - * declared method, including in this case {@code native} and {@code varargs} bits.
   1.358 - * <p>
   1.359 - * As with any reflected method, these methods (when reflected) may be
   1.360 - * invoked via {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.
   1.361 - * However, such reflective calls do not result in method handle invocations.
   1.362 - * Such a call, if passed the required argument
   1.363 - * (a single one, of type {@code Object[]}), will ignore the argument and
   1.364 - * will throw an {@code UnsupportedOperationException}.
   1.365 - * <p>
   1.366 - * Since {@code invokevirtual} instructions can natively
   1.367 - * invoke method handles under any symbolic type descriptor, this reflective view conflicts
   1.368 - * with the normal presentation of these methods via bytecodes.
   1.369 - * Thus, these two native methods, when reflectively viewed by
   1.370 - * {@code Class.getDeclaredMethod}, may be regarded as placeholders only.
   1.371 - * <p>
   1.372 - * In order to obtain an invoker method for a particular type descriptor,
   1.373 - * use {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker},
   1.374 - * or {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}.
   1.375 - * The {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual}
   1.376 - * API is also able to return a method handle
   1.377 - * to call {@code invokeExact} or plain {@code invoke},
   1.378 - * for any specified type descriptor .
   1.379 - *
   1.380 - * <h1>Interoperation between method handles and Java generics</h1>
   1.381 - * A method handle can be obtained on a method, constructor, or field
   1.382 - * which is declared with Java generic types.
   1.383 - * As with the Core Reflection API, the type of the method handle
   1.384 - * will constructed from the erasure of the source-level type.
   1.385 - * When a method handle is invoked, the types of its arguments
   1.386 - * or the return value cast type may be generic types or type instances.
   1.387 - * If this occurs, the compiler will replace those
   1.388 - * types by their erasures when it constructs the symbolic type descriptor
   1.389 - * for the {@code invokevirtual} instruction.
   1.390 - * <p>
   1.391 - * Method handles do not represent
   1.392 - * their function-like types in terms of Java parameterized (generic) types,
   1.393 - * because there are three mismatches between function-like types and parameterized
   1.394 - * Java types.
   1.395 - * <ul>
   1.396 - * <li>Method types range over all possible arities,
   1.397 - * from no arguments to up to the  <a href="MethodHandle.html#maxarity">maximum number</a> of allowed arguments.
   1.398 - * Generics are not variadic, and so cannot represent this.</li>
   1.399 - * <li>Method types can specify arguments of primitive types,
   1.400 - * which Java generic types cannot range over.</li>
   1.401 - * <li>Higher order functions over method handles (combinators) are
   1.402 - * often generic across a wide range of function types, including
   1.403 - * those of multiple arities.  It is impossible to represent such
   1.404 - * genericity with a Java type parameter.</li>
   1.405 - * </ul>
   1.406 - *
   1.407 - * <h1><a name="maxarity"></a>Arity limits</h1>
   1.408 - * The JVM imposes on all methods and constructors of any kind an absolute
   1.409 - * limit of 255 stacked arguments.  This limit can appear more restrictive
   1.410 - * in certain cases:
   1.411 - * <ul>
   1.412 - * <li>A {@code long} or {@code double} argument counts (for purposes of arity limits) as two argument slots.
   1.413 - * <li>A non-static method consumes an extra argument for the object on which the method is called.
   1.414 - * <li>A constructor consumes an extra argument for the object which is being constructed.
   1.415 - * <li>Since a method handle&rsquo;s {@code invoke} method (or other signature-polymorphic method) is non-virtual,
   1.416 - *     it consumes an extra argument for the method handle itself, in addition to any non-virtual receiver object.
   1.417 - * </ul>
   1.418 - * These limits imply that certain method handles cannot be created, solely because of the JVM limit on stacked arguments.
   1.419 - * For example, if a static JVM method accepts exactly 255 arguments, a method handle cannot be created for it.
   1.420 - * Attempts to create method handles with impossible method types lead to an {@link IllegalArgumentException}.
   1.421 - * In particular, a method handle&rsquo;s type must not have an arity of the exact maximum 255.
   1.422 - *
   1.423 - * @see MethodType
   1.424 - * @see MethodHandles
   1.425 - * @author John Rose, JSR 292 EG
   1.426 - */
   1.427 -public abstract class MethodHandle {
   1.428 -    static { MethodHandleImpl.initStatics(); }
   1.429 -
   1.430 -    /**
   1.431 -     * Internal marker interface which distinguishes (to the Java compiler)
   1.432 -     * those methods which are <a href="MethodHandle.html#sigpoly">signature polymorphic</a>.
   1.433 -     */
   1.434 -    @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
   1.435 -    @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
   1.436 -    @interface PolymorphicSignature { }
   1.437 -
   1.438 -    private final MethodType type;
   1.439 -    /*private*/ LambdaForm form;
   1.440 -    // form is not private so that invokers can easily fetch it
   1.441 -    /*private*/ MethodHandle asTypeCache;
   1.442 -    // asTypeCache is not private so that invokers can easily fetch it
   1.443 -
   1.444 -    /**
   1.445 -     * Reports the type of this method handle.
   1.446 -     * Every invocation of this method handle via {@code invokeExact} must exactly match this type.
   1.447 -     * @return the method handle type
   1.448 -     */
   1.449 -    public MethodType type() {
   1.450 -        return type;
   1.451 -    }
   1.452 -
   1.453 -    /**
   1.454 -     * Package-private constructor for the method handle implementation hierarchy.
   1.455 -     * Method handle inheritance will be contained completely within
   1.456 -     * the {@code java.lang.invoke} package.
   1.457 -     */
   1.458 -    // @param type type (permanently assigned) of the new method handle
   1.459 -    /*non-public*/ MethodHandle(MethodType type, LambdaForm form) {
   1.460 -        type.getClass();  // explicit NPE
   1.461 -        form.getClass();  // explicit NPE
   1.462 -        this.type = type;
   1.463 -        this.form = form;
   1.464 -
   1.465 -        form.prepare();  // TO DO:  Try to delay this step until just before invocation.
   1.466 -    }
   1.467 -
   1.468 -    /**
   1.469 -     * Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match.
   1.470 -     * The symbolic type descriptor at the call site of {@code invokeExact} must
   1.471 -     * exactly match this method handle's {@link #type type}.
   1.472 -     * No conversions are allowed on arguments or return values.
   1.473 -     * <p>
   1.474 -     * When this method is observed via the Core Reflection API,
   1.475 -     * it will appear as a single native method, taking an object array and returning an object.
   1.476 -     * If this native method is invoked directly via
   1.477 -     * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
   1.478 -     * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
   1.479 -     * it will throw an {@code UnsupportedOperationException}.
   1.480 -     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.481 -     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.482 -     * @throws WrongMethodTypeException if the target's type is not identical with the caller's symbolic type descriptor
   1.483 -     * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
   1.484 -     */
   1.485 -    public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable;
   1.486 -
   1.487 -    /**
   1.488 -     * Invokes the method handle, allowing any caller type descriptor,
   1.489 -     * and optionally performing conversions on arguments and return values.
   1.490 -     * <p>
   1.491 -     * If the call site's symbolic type descriptor exactly matches this method handle's {@link #type type},
   1.492 -     * the call proceeds as if by {@link #invokeExact invokeExact}.
   1.493 -     * <p>
   1.494 -     * Otherwise, the call proceeds as if this method handle were first
   1.495 -     * adjusted by calling {@link #asType asType} to adjust this method handle
   1.496 -     * to the required type, and then the call proceeds as if by
   1.497 -     * {@link #invokeExact invokeExact} on the adjusted method handle.
   1.498 -     * <p>
   1.499 -     * There is no guarantee that the {@code asType} call is actually made.
   1.500 -     * If the JVM can predict the results of making the call, it may perform
   1.501 -     * adaptations directly on the caller's arguments,
   1.502 -     * and call the target method handle according to its own exact type.
   1.503 -     * <p>
   1.504 -     * The resolved type descriptor at the call site of {@code invoke} must
   1.505 -     * be a valid argument to the receivers {@code asType} method.
   1.506 -     * In particular, the caller must specify the same argument arity
   1.507 -     * as the callee's type,
   1.508 -     * if the callee is not a {@linkplain #asVarargsCollector variable arity collector}.
   1.509 -     * <p>
   1.510 -     * When this method is observed via the Core Reflection API,
   1.511 -     * it will appear as a single native method, taking an object array and returning an object.
   1.512 -     * If this native method is invoked directly via
   1.513 -     * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
   1.514 -     * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
   1.515 -     * it will throw an {@code UnsupportedOperationException}.
   1.516 -     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.517 -     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.518 -     * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's symbolic type descriptor
   1.519 -     * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails
   1.520 -     * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
   1.521 -     */
   1.522 -    public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable;
   1.523 -
   1.524 -    /**
   1.525 -     * Private method for trusted invocation of a method handle respecting simplified signatures.
   1.526 -     * Type mismatches will not throw {@code WrongMethodTypeException}, but could crash the JVM.
   1.527 -     * <p>
   1.528 -     * The caller signature is restricted to the following basic types:
   1.529 -     * Object, int, long, float, double, and void return.
   1.530 -     * <p>
   1.531 -     * The caller is responsible for maintaining type correctness by ensuring
   1.532 -     * that the each outgoing argument value is a member of the range of the corresponding
   1.533 -     * callee argument type.
   1.534 -     * (The caller should therefore issue appropriate casts and integer narrowing
   1.535 -     * operations on outgoing argument values.)
   1.536 -     * The caller can assume that the incoming result value is part of the range
   1.537 -     * of the callee's return type.
   1.538 -     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.539 -     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.540 -     */
   1.541 -    /*non-public*/ final native @PolymorphicSignature Object invokeBasic(Object... args) throws Throwable;
   1.542 -
   1.543 -    /**
   1.544 -     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeVirtual}.
   1.545 -     * The caller signature is restricted to basic types as with {@code invokeBasic}.
   1.546 -     * The trailing (not leading) argument must be a MemberName.
   1.547 -     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.548 -     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.549 -     */
   1.550 -    /*non-public*/ static native @PolymorphicSignature Object linkToVirtual(Object... args) throws Throwable;
   1.551 -
   1.552 -    /**
   1.553 -     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeStatic}.
   1.554 -     * The caller signature is restricted to basic types as with {@code invokeBasic}.
   1.555 -     * The trailing (not leading) argument must be a MemberName.
   1.556 -     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.557 -     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.558 -     */
   1.559 -    /*non-public*/ static native @PolymorphicSignature Object linkToStatic(Object... args) throws Throwable;
   1.560 -
   1.561 -    /**
   1.562 -     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeSpecial}.
   1.563 -     * The caller signature is restricted to basic types as with {@code invokeBasic}.
   1.564 -     * The trailing (not leading) argument must be a MemberName.
   1.565 -     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.566 -     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.567 -     */
   1.568 -    /*non-public*/ static native @PolymorphicSignature Object linkToSpecial(Object... args) throws Throwable;
   1.569 -
   1.570 -    /**
   1.571 -     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeInterface}.
   1.572 -     * The caller signature is restricted to basic types as with {@code invokeBasic}.
   1.573 -     * The trailing (not leading) argument must be a MemberName.
   1.574 -     * @param args the signature-polymorphic parameter list, statically represented using varargs
   1.575 -     * @return the signature-polymorphic result, statically represented using {@code Object}
   1.576 -     */
   1.577 -    /*non-public*/ static native @PolymorphicSignature Object linkToInterface(Object... args) throws Throwable;
   1.578 -
   1.579 -    /**
   1.580 -     * Performs a variable arity invocation, passing the arguments in the given list
   1.581 -     * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
   1.582 -     * which mentions only the type {@code Object}, and whose arity is the length
   1.583 -     * of the argument list.
   1.584 -     * <p>
   1.585 -     * Specifically, execution proceeds as if by the following steps,
   1.586 -     * although the methods are not guaranteed to be called if the JVM
   1.587 -     * can predict their effects.
   1.588 -     * <ul>
   1.589 -     * <li>Determine the length of the argument array as {@code N}.
   1.590 -     *     For a null reference, {@code N=0}. </li>
   1.591 -     * <li>Determine the general type {@code TN} of {@code N} arguments as
   1.592 -     *     as {@code TN=MethodType.genericMethodType(N)}.</li>
   1.593 -     * <li>Force the original target method handle {@code MH0} to the
   1.594 -     *     required type, as {@code MH1 = MH0.asType(TN)}. </li>
   1.595 -     * <li>Spread the array into {@code N} separate arguments {@code A0, ...}. </li>
   1.596 -     * <li>Invoke the type-adjusted method handle on the unpacked arguments:
   1.597 -     *     MH1.invokeExact(A0, ...). </li>
   1.598 -     * <li>Take the return value as an {@code Object} reference. </li>
   1.599 -     * </ul>
   1.600 -     * <p>
   1.601 -     * Because of the action of the {@code asType} step, the following argument
   1.602 -     * conversions are applied as necessary:
   1.603 -     * <ul>
   1.604 -     * <li>reference casting
   1.605 -     * <li>unboxing
   1.606 -     * <li>widening primitive conversions
   1.607 -     * </ul>
   1.608 -     * <p>
   1.609 -     * The result returned by the call is boxed if it is a primitive,
   1.610 -     * or forced to null if the return type is void.
   1.611 -     * <p>
   1.612 -     * This call is equivalent to the following code:
   1.613 -     * <blockquote><pre>{@code
   1.614 -     * MethodHandle invoker = MethodHandles.spreadInvoker(this.type(), 0);
   1.615 -     * Object result = invoker.invokeExact(this, arguments);
   1.616 -     * }</pre></blockquote>
   1.617 -     * <p>
   1.618 -     * Unlike the signature polymorphic methods {@code invokeExact} and {@code invoke},
   1.619 -     * {@code invokeWithArguments} can be accessed normally via the Core Reflection API and JNI.
   1.620 -     * It can therefore be used as a bridge between native or reflective code and method handles.
   1.621 -     *
   1.622 -     * @param arguments the arguments to pass to the target
   1.623 -     * @return the result returned by the target
   1.624 -     * @throws ClassCastException if an argument cannot be converted by reference casting
   1.625 -     * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
   1.626 -     * @throws Throwable anything thrown by the target method invocation
   1.627 -     * @see MethodHandles#spreadInvoker
   1.628 -     */
   1.629 -    public Object invokeWithArguments(Object... arguments) throws Throwable {
   1.630 -        int argc = arguments == null ? 0 : arguments.length;
   1.631 -        @SuppressWarnings("LocalVariableHidesMemberVariable")
   1.632 -        MethodType type = type();
   1.633 -        if (type.parameterCount() != argc || isVarargsCollector()) {
   1.634 -            // simulate invoke
   1.635 -            return asType(MethodType.genericMethodType(argc)).invokeWithArguments(arguments);
   1.636 -        }
   1.637 -        MethodHandle invoker = type.invokers().varargsInvoker();
   1.638 -        return invoker.invokeExact(this, arguments);
   1.639 -    }
   1.640 -
   1.641 -    /**
   1.642 -     * Performs a variable arity invocation, passing the arguments in the given array
   1.643 -     * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
   1.644 -     * which mentions only the type {@code Object}, and whose arity is the length
   1.645 -     * of the argument array.
   1.646 -     * <p>
   1.647 -     * This method is also equivalent to the following code:
   1.648 -     * <blockquote><pre>{@code
   1.649 -     *   invokeWithArguments(arguments.toArray()
   1.650 -     * }</pre></blockquote>
   1.651 -     *
   1.652 -     * @param arguments the arguments to pass to the target
   1.653 -     * @return the result returned by the target
   1.654 -     * @throws NullPointerException if {@code arguments} is a null reference
   1.655 -     * @throws ClassCastException if an argument cannot be converted by reference casting
   1.656 -     * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
   1.657 -     * @throws Throwable anything thrown by the target method invocation
   1.658 -     */
   1.659 -    public Object invokeWithArguments(java.util.List<?> arguments) throws Throwable {
   1.660 -        return invokeWithArguments(arguments.toArray());
   1.661 -    }
   1.662 -
   1.663 -    /**
   1.664 -     * Produces an adapter method handle which adapts the type of the
   1.665 -     * current method handle to a new type.
   1.666 -     * The resulting method handle is guaranteed to report a type
   1.667 -     * which is equal to the desired new type.
   1.668 -     * <p>
   1.669 -     * If the original type and new type are equal, returns {@code this}.
   1.670 -     * <p>
   1.671 -     * The new method handle, when invoked, will perform the following
   1.672 -     * steps:
   1.673 -     * <ul>
   1.674 -     * <li>Convert the incoming argument list to match the original
   1.675 -     *     method handle's argument list.
   1.676 -     * <li>Invoke the original method handle on the converted argument list.
   1.677 -     * <li>Convert any result returned by the original method handle
   1.678 -     *     to the return type of new method handle.
   1.679 -     * </ul>
   1.680 -     * <p>
   1.681 -     * This method provides the crucial behavioral difference between
   1.682 -     * {@link #invokeExact invokeExact} and plain, inexact {@link #invoke invoke}.
   1.683 -     * The two methods
   1.684 -     * perform the same steps when the caller's type descriptor exactly m atches
   1.685 -     * the callee's, but when the types differ, plain {@link #invoke invoke}
   1.686 -     * also calls {@code asType} (or some internal equivalent) in order
   1.687 -     * to match up the caller's and callee's types.
   1.688 -     * <p>
   1.689 -     * If the current method is a variable arity method handle
   1.690 -     * argument list conversion may involve the conversion and collection
   1.691 -     * of several arguments into an array, as
   1.692 -     * {@linkplain #asVarargsCollector described elsewhere}.
   1.693 -     * In every other case, all conversions are applied <em>pairwise</em>,
   1.694 -     * which means that each argument or return value is converted to
   1.695 -     * exactly one argument or return value (or no return value).
   1.696 -     * The applied conversions are defined by consulting the
   1.697 -     * the corresponding component types of the old and new
   1.698 -     * method handle types.
   1.699 -     * <p>
   1.700 -     * Let <em>T0</em> and <em>T1</em> be corresponding new and old parameter types,
   1.701 -     * or old and new return types.  Specifically, for some valid index {@code i}, let
   1.702 -     * <em>T0</em>{@code =newType.parameterType(i)} and <em>T1</em>{@code =this.type().parameterType(i)}.
   1.703 -     * Or else, going the other way for return values, let
   1.704 -     * <em>T0</em>{@code =this.type().returnType()} and <em>T1</em>{@code =newType.returnType()}.
   1.705 -     * If the types are the same, the new method handle makes no change
   1.706 -     * to the corresponding argument or return value (if any).
   1.707 -     * Otherwise, one of the following conversions is applied
   1.708 -     * if possible:
   1.709 -     * <ul>
   1.710 -     * <li>If <em>T0</em> and <em>T1</em> are references, then a cast to <em>T1</em> is applied.
   1.711 -     *     (The types do not need to be related in any particular way.
   1.712 -     *     This is because a dynamic value of null can convert to any reference type.)
   1.713 -     * <li>If <em>T0</em> and <em>T1</em> are primitives, then a Java method invocation
   1.714 -     *     conversion (JLS 5.3) is applied, if one exists.
   1.715 -     *     (Specifically, <em>T0</em> must convert to <em>T1</em> by a widening primitive conversion.)
   1.716 -     * <li>If <em>T0</em> is a primitive and <em>T1</em> a reference,
   1.717 -     *     a Java casting conversion (JLS 5.5) is applied if one exists.
   1.718 -     *     (Specifically, the value is boxed from <em>T0</em> to its wrapper class,
   1.719 -     *     which is then widened as needed to <em>T1</em>.)
   1.720 -     * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
   1.721 -     *     conversion will be applied at runtime, possibly followed
   1.722 -     *     by a Java method invocation conversion (JLS 5.3)
   1.723 -     *     on the primitive value.  (These are the primitive widening conversions.)
   1.724 -     *     <em>T0</em> must be a wrapper class or a supertype of one.
   1.725 -     *     (In the case where <em>T0</em> is Object, these are the conversions
   1.726 -     *     allowed by {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.)
   1.727 -     *     The unboxing conversion must have a possibility of success, which means that
   1.728 -     *     if <em>T0</em> is not itself a wrapper class, there must exist at least one
   1.729 -     *     wrapper class <em>TW</em> which is a subtype of <em>T0</em> and whose unboxed
   1.730 -     *     primitive value can be widened to <em>T1</em>.
   1.731 -     * <li>If the return type <em>T1</em> is marked as void, any returned value is discarded
   1.732 -     * <li>If the return type <em>T0</em> is void and <em>T1</em> a reference, a null value is introduced.
   1.733 -     * <li>If the return type <em>T0</em> is void and <em>T1</em> a primitive,
   1.734 -     *     a zero value is introduced.
   1.735 -     * </ul>
   1.736 -    * (<em>Note:</em> Both <em>T0</em> and <em>T1</em> may be regarded as static types,
   1.737 -     * because neither corresponds specifically to the <em>dynamic type</em> of any
   1.738 -     * actual argument or return value.)
   1.739 -     * <p>
   1.740 -     * The method handle conversion cannot be made if any one of the required
   1.741 -     * pairwise conversions cannot be made.
   1.742 -     * <p>
   1.743 -     * At runtime, the conversions applied to reference arguments
   1.744 -     * or return values may require additional runtime checks which can fail.
   1.745 -     * An unboxing operation may fail because the original reference is null,
   1.746 -     * causing a {@link java.lang.NullPointerException NullPointerException}.
   1.747 -     * An unboxing operation or a reference cast may also fail on a reference
   1.748 -     * to an object of the wrong type,
   1.749 -     * causing a {@link java.lang.ClassCastException ClassCastException}.
   1.750 -     * Although an unboxing operation may accept several kinds of wrappers,
   1.751 -     * if none are available, a {@code ClassCastException} will be thrown.
   1.752 -     *
   1.753 -     * @param newType the expected type of the new method handle
   1.754 -     * @return a method handle which delegates to {@code this} after performing
   1.755 -     *           any necessary argument conversions, and arranges for any
   1.756 -     *           necessary return value conversions
   1.757 -     * @throws NullPointerException if {@code newType} is a null reference
   1.758 -     * @throws WrongMethodTypeException if the conversion cannot be made
   1.759 -     * @see MethodHandles#explicitCastArguments
   1.760 -     */
   1.761 -    public MethodHandle asType(MethodType newType) {
   1.762 -        // Fast path alternative to a heavyweight {@code asType} call.
   1.763 -        // Return 'this' if the conversion will be a no-op.
   1.764 -        if (newType == type) {
   1.765 -            return this;
   1.766 -        }
   1.767 -        // Return 'this.asTypeCache' if the conversion is already memoized.
   1.768 -        MethodHandle atc = asTypeCache;
   1.769 -        if (atc != null && newType == atc.type) {
   1.770 -            return atc;
   1.771 -        }
   1.772 -        return asTypeUncached(newType);
   1.773 -    }
   1.774 -
   1.775 -    /** Override this to change asType behavior. */
   1.776 -    /*non-public*/ MethodHandle asTypeUncached(MethodType newType) {
   1.777 -        if (!type.isConvertibleTo(newType))
   1.778 -            throw new WrongMethodTypeException("cannot convert "+this+" to "+newType);
   1.779 -        return asTypeCache = convertArguments(newType);
   1.780 -    }
   1.781 -
   1.782 -    /**
   1.783 -     * Makes an <em>array-spreading</em> method handle, which accepts a trailing array argument
   1.784 -     * and spreads its elements as positional arguments.
   1.785 -     * The new method handle adapts, as its <i>target</i>,
   1.786 -     * the current method handle.  The type of the adapter will be
   1.787 -     * the same as the type of the target, except that the final
   1.788 -     * {@code arrayLength} parameters of the target's type are replaced
   1.789 -     * by a single array parameter of type {@code arrayType}.
   1.790 -     * <p>
   1.791 -     * If the array element type differs from any of the corresponding
   1.792 -     * argument types on the original target,
   1.793 -     * the original target is adapted to take the array elements directly,
   1.794 -     * as if by a call to {@link #asType asType}.
   1.795 -     * <p>
   1.796 -     * When called, the adapter replaces a trailing array argument
   1.797 -     * by the array's elements, each as its own argument to the target.
   1.798 -     * (The order of the arguments is preserved.)
   1.799 -     * They are converted pairwise by casting and/or unboxing
   1.800 -     * to the types of the trailing parameters of the target.
   1.801 -     * Finally the target is called.
   1.802 -     * What the target eventually returns is returned unchanged by the adapter.
   1.803 -     * <p>
   1.804 -     * Before calling the target, the adapter verifies that the array
   1.805 -     * contains exactly enough elements to provide a correct argument count
   1.806 -     * to the target method handle.
   1.807 -     * (The array may also be null when zero elements are required.)
   1.808 -     * <p>
   1.809 -     * If, when the adapter is called, the supplied array argument does
   1.810 -     * not have the correct number of elements, the adapter will throw
   1.811 -     * an {@link IllegalArgumentException} instead of invoking the target.
   1.812 -     * <p>
   1.813 -     * Here are some simple examples of array-spreading method handles:
   1.814 -     * <blockquote><pre>{@code
   1.815 -MethodHandle equals = publicLookup()
   1.816 -  .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
   1.817 -assert( (boolean) equals.invokeExact("me", (Object)"me"));
   1.818 -assert(!(boolean) equals.invokeExact("me", (Object)"thee"));
   1.819 -// spread both arguments from a 2-array:
   1.820 -MethodHandle eq2 = equals.asSpreader(Object[].class, 2);
   1.821 -assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" }));
   1.822 -assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
   1.823 -// try to spread from anything but a 2-array:
   1.824 -for (int n = 0; n <= 10; n++) {
   1.825 -  Object[] badArityArgs = (n == 2 ? null : new Object[n]);
   1.826 -  try { assert((boolean) eq2.invokeExact(badArityArgs) && false); }
   1.827 -  catch (IllegalArgumentException ex) { } // OK
   1.828 -}
   1.829 -// spread both arguments from a String array:
   1.830 -MethodHandle eq2s = equals.asSpreader(String[].class, 2);
   1.831 -assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" }));
   1.832 -assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" }));
   1.833 -// spread second arguments from a 1-array:
   1.834 -MethodHandle eq1 = equals.asSpreader(Object[].class, 1);
   1.835 -assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" }));
   1.836 -assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" }));
   1.837 -// spread no arguments from a 0-array or null:
   1.838 -MethodHandle eq0 = equals.asSpreader(Object[].class, 0);
   1.839 -assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0]));
   1.840 -assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null));
   1.841 -// asSpreader and asCollector are approximate inverses:
   1.842 -for (int n = 0; n <= 2; n++) {
   1.843 -    for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) {
   1.844 -        MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n);
   1.845 -        assert( (boolean) equals2.invokeWithArguments("me", "me"));
   1.846 -        assert(!(boolean) equals2.invokeWithArguments("me", "thee"));
   1.847 -    }
   1.848 -}
   1.849 -MethodHandle caToString = publicLookup()
   1.850 -  .findStatic(Arrays.class, "toString", methodType(String.class, char[].class));
   1.851 -assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray()));
   1.852 -MethodHandle caString3 = caToString.asCollector(char[].class, 3);
   1.853 -assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
   1.854 -MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
   1.855 -assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
   1.856 -     * }</pre></blockquote>
   1.857 -     * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments
   1.858 -     * @param arrayLength the number of arguments to spread from an incoming array argument
   1.859 -     * @return a new method handle which spreads its final array argument,
   1.860 -     *         before calling the original method handle
   1.861 -     * @throws NullPointerException if {@code arrayType} is a null reference
   1.862 -     * @throws IllegalArgumentException if {@code arrayType} is not an array type,
   1.863 -     *         or if target does not have at least
   1.864 -     *         {@code arrayLength} parameter types,
   1.865 -     *         or if {@code arrayLength} is negative,
   1.866 -     *         or if the resulting method handle's type would have
   1.867 -     *         <a href="MethodHandle.html#maxarity">too many parameters</a>
   1.868 -     * @throws WrongMethodTypeException if the implied {@code asType} call fails
   1.869 -     * @see #asCollector
   1.870 -     */
   1.871 -    public MethodHandle asSpreader(Class<?> arrayType, int arrayLength) {
   1.872 -        asSpreaderChecks(arrayType, arrayLength);
   1.873 -        int spreadArgPos = type.parameterCount() - arrayLength;
   1.874 -        return MethodHandleImpl.makeSpreadArguments(this, arrayType, spreadArgPos, arrayLength);
   1.875 -    }
   1.876 -
   1.877 -    private void asSpreaderChecks(Class<?> arrayType, int arrayLength) {
   1.878 -        spreadArrayChecks(arrayType, arrayLength);
   1.879 -        int nargs = type().parameterCount();
   1.880 -        if (nargs < arrayLength || arrayLength < 0)
   1.881 -            throw newIllegalArgumentException("bad spread array length");
   1.882 -        if (arrayType != Object[].class && arrayLength != 0) {
   1.883 -            boolean sawProblem = false;
   1.884 -            Class<?> arrayElement = arrayType.getComponentType();
   1.885 -            for (int i = nargs - arrayLength; i < nargs; i++) {
   1.886 -                if (!MethodType.canConvert(arrayElement, type().parameterType(i))) {
   1.887 -                    sawProblem = true;
   1.888 -                    break;
   1.889 -                }
   1.890 -            }
   1.891 -            if (sawProblem) {
   1.892 -                ArrayList<Class<?>> ptypes = new ArrayList<>(type().parameterList());
   1.893 -                for (int i = nargs - arrayLength; i < nargs; i++) {
   1.894 -                    ptypes.set(i, arrayElement);
   1.895 -                }
   1.896 -                // elicit an error:
   1.897 -                this.asType(MethodType.methodType(type().returnType(), ptypes));
   1.898 -            }
   1.899 -        }
   1.900 -    }
   1.901 -
   1.902 -    private void spreadArrayChecks(Class<?> arrayType, int arrayLength) {
   1.903 -        Class<?> arrayElement = arrayType.getComponentType();
   1.904 -        if (arrayElement == null)
   1.905 -            throw newIllegalArgumentException("not an array type", arrayType);
   1.906 -        if ((arrayLength & 0x7F) != arrayLength) {
   1.907 -            if ((arrayLength & 0xFF) != arrayLength)
   1.908 -                throw newIllegalArgumentException("array length is not legal", arrayLength);
   1.909 -            assert(arrayLength >= 128);
   1.910 -            if (arrayElement == long.class ||
   1.911 -                arrayElement == double.class)
   1.912 -                throw newIllegalArgumentException("array length is not legal for long[] or double[]", arrayLength);
   1.913 -        }
   1.914 -    }
   1.915 -
   1.916 -    /**
   1.917 -     * Makes an <em>array-collecting</em> method handle, which accepts a given number of trailing
   1.918 -     * positional arguments and collects them into an array argument.
   1.919 -     * The new method handle adapts, as its <i>target</i>,
   1.920 -     * the current method handle.  The type of the adapter will be
   1.921 -     * the same as the type of the target, except that a single trailing
   1.922 -     * parameter (usually of type {@code arrayType}) is replaced by
   1.923 -     * {@code arrayLength} parameters whose type is element type of {@code arrayType}.
   1.924 -     * <p>
   1.925 -     * If the array type differs from the final argument type on the original target,
   1.926 -     * the original target is adapted to take the array type directly,
   1.927 -     * as if by a call to {@link #asType asType}.
   1.928 -     * <p>
   1.929 -     * When called, the adapter replaces its trailing {@code arrayLength}
   1.930 -     * arguments by a single new array of type {@code arrayType}, whose elements
   1.931 -     * comprise (in order) the replaced arguments.
   1.932 -     * Finally the target is called.
   1.933 -     * What the target eventually returns is returned unchanged by the adapter.
   1.934 -     * <p>
   1.935 -     * (The array may also be a shared constant when {@code arrayLength} is zero.)
   1.936 -     * <p>
   1.937 -     * (<em>Note:</em> The {@code arrayType} is often identical to the last
   1.938 -     * parameter type of the original target.
   1.939 -     * It is an explicit argument for symmetry with {@code asSpreader}, and also
   1.940 -     * to allow the target to use a simple {@code Object} as its last parameter type.)
   1.941 -     * <p>
   1.942 -     * In order to create a collecting adapter which is not restricted to a particular
   1.943 -     * number of collected arguments, use {@link #asVarargsCollector asVarargsCollector} instead.
   1.944 -     * <p>
   1.945 -     * Here are some examples of array-collecting method handles:
   1.946 -     * <blockquote><pre>{@code
   1.947 -MethodHandle deepToString = publicLookup()
   1.948 -  .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
   1.949 -assertEquals("[won]",   (String) deepToString.invokeExact(new Object[]{"won"}));
   1.950 -MethodHandle ts1 = deepToString.asCollector(Object[].class, 1);
   1.951 -assertEquals(methodType(String.class, Object.class), ts1.type());
   1.952 -//assertEquals("[won]", (String) ts1.invokeExact(         new Object[]{"won"})); //FAIL
   1.953 -assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"}));
   1.954 -// arrayType can be a subtype of Object[]
   1.955 -MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
   1.956 -assertEquals(methodType(String.class, String.class, String.class), ts2.type());
   1.957 -assertEquals("[two, too]", (String) ts2.invokeExact("two", "too"));
   1.958 -MethodHandle ts0 = deepToString.asCollector(Object[].class, 0);
   1.959 -assertEquals("[]", (String) ts0.invokeExact());
   1.960 -// collectors can be nested, Lisp-style
   1.961 -MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2);
   1.962 -assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D")));
   1.963 -// arrayType can be any primitive array type
   1.964 -MethodHandle bytesToString = publicLookup()
   1.965 -  .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class))
   1.966 -  .asCollector(byte[].class, 3);
   1.967 -assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3));
   1.968 -MethodHandle longsToString = publicLookup()
   1.969 -  .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
   1.970 -  .asCollector(long[].class, 1);
   1.971 -assertEquals("[123]", (String) longsToString.invokeExact((long)123));
   1.972 -     * }</pre></blockquote>
   1.973 -     * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
   1.974 -     * @param arrayLength the number of arguments to collect into a new array argument
   1.975 -     * @return a new method handle which collects some trailing argument
   1.976 -     *         into an array, before calling the original method handle
   1.977 -     * @throws NullPointerException if {@code arrayType} is a null reference
   1.978 -     * @throws IllegalArgumentException if {@code arrayType} is not an array type
   1.979 -     *         or {@code arrayType} is not assignable to this method handle's trailing parameter type,
   1.980 -     *         or {@code arrayLength} is not a legal array size,
   1.981 -     *         or the resulting method handle's type would have
   1.982 -     *         <a href="MethodHandle.html#maxarity">too many parameters</a>
   1.983 -     * @throws WrongMethodTypeException if the implied {@code asType} call fails
   1.984 -     * @see #asSpreader
   1.985 -     * @see #asVarargsCollector
   1.986 -     */
   1.987 -    public MethodHandle asCollector(Class<?> arrayType, int arrayLength) {
   1.988 -        asCollectorChecks(arrayType, arrayLength);
   1.989 -        int collectArgPos = type().parameterCount()-1;
   1.990 -        MethodHandle target = this;
   1.991 -        if (arrayType != type().parameterType(collectArgPos))
   1.992 -            target = convertArguments(type().changeParameterType(collectArgPos, arrayType));
   1.993 -        MethodHandle collector = ValueConversions.varargsArray(arrayType, arrayLength);
   1.994 -        return MethodHandles.collectArguments(target, collectArgPos, collector);
   1.995 -    }
   1.996 -
   1.997 -    // private API: return true if last param exactly matches arrayType
   1.998 -    private boolean asCollectorChecks(Class<?> arrayType, int arrayLength) {
   1.999 -        spreadArrayChecks(arrayType, arrayLength);
  1.1000 -        int nargs = type().parameterCount();
  1.1001 -        if (nargs != 0) {
  1.1002 -            Class<?> lastParam = type().parameterType(nargs-1);
  1.1003 -            if (lastParam == arrayType)  return true;
  1.1004 -            if (lastParam.isAssignableFrom(arrayType))  return false;
  1.1005 -        }
  1.1006 -        throw newIllegalArgumentException("array type not assignable to trailing argument", this, arrayType);
  1.1007 -    }
  1.1008 -
  1.1009 -    /**
  1.1010 -     * Makes a <em>variable arity</em> adapter which is able to accept
  1.1011 -     * any number of trailing positional arguments and collect them
  1.1012 -     * into an array argument.
  1.1013 -     * <p>
  1.1014 -     * The type and behavior of the adapter will be the same as
  1.1015 -     * the type and behavior of the target, except that certain
  1.1016 -     * {@code invoke} and {@code asType} requests can lead to
  1.1017 -     * trailing positional arguments being collected into target's
  1.1018 -     * trailing parameter.
  1.1019 -     * Also, the last parameter type of the adapter will be
  1.1020 -     * {@code arrayType}, even if the target has a different
  1.1021 -     * last parameter type.
  1.1022 -     * <p>
  1.1023 -     * This transformation may return {@code this} if the method handle is
  1.1024 -     * already of variable arity and its trailing parameter type
  1.1025 -     * is identical to {@code arrayType}.
  1.1026 -     * <p>
  1.1027 -     * When called with {@link #invokeExact invokeExact}, the adapter invokes
  1.1028 -     * the target with no argument changes.
  1.1029 -     * (<em>Note:</em> This behavior is different from a
  1.1030 -     * {@linkplain #asCollector fixed arity collector},
  1.1031 -     * since it accepts a whole array of indeterminate length,
  1.1032 -     * rather than a fixed number of arguments.)
  1.1033 -     * <p>
  1.1034 -     * When called with plain, inexact {@link #invoke invoke}, if the caller
  1.1035 -     * type is the same as the adapter, the adapter invokes the target as with
  1.1036 -     * {@code invokeExact}.
  1.1037 -     * (This is the normal behavior for {@code invoke} when types match.)
  1.1038 -     * <p>
  1.1039 -     * Otherwise, if the caller and adapter arity are the same, and the
  1.1040 -     * trailing parameter type of the caller is a reference type identical to
  1.1041 -     * or assignable to the trailing parameter type of the adapter,
  1.1042 -     * the arguments and return values are converted pairwise,
  1.1043 -     * as if by {@link #asType asType} on a fixed arity
  1.1044 -     * method handle.
  1.1045 -     * <p>
  1.1046 -     * Otherwise, the arities differ, or the adapter's trailing parameter
  1.1047 -     * type is not assignable from the corresponding caller type.
  1.1048 -     * In this case, the adapter replaces all trailing arguments from
  1.1049 -     * the original trailing argument position onward, by
  1.1050 -     * a new array of type {@code arrayType}, whose elements
  1.1051 -     * comprise (in order) the replaced arguments.
  1.1052 -     * <p>
  1.1053 -     * The caller type must provides as least enough arguments,
  1.1054 -     * and of the correct type, to satisfy the target's requirement for
  1.1055 -     * positional arguments before the trailing array argument.
  1.1056 -     * Thus, the caller must supply, at a minimum, {@code N-1} arguments,
  1.1057 -     * where {@code N} is the arity of the target.
  1.1058 -     * Also, there must exist conversions from the incoming arguments
  1.1059 -     * to the target's arguments.
  1.1060 -     * As with other uses of plain {@code invoke}, if these basic
  1.1061 -     * requirements are not fulfilled, a {@code WrongMethodTypeException}
  1.1062 -     * may be thrown.
  1.1063 -     * <p>
  1.1064 -     * In all cases, what the target eventually returns is returned unchanged by the adapter.
  1.1065 -     * <p>
  1.1066 -     * In the final case, it is exactly as if the target method handle were
  1.1067 -     * temporarily adapted with a {@linkplain #asCollector fixed arity collector}
  1.1068 -     * to the arity required by the caller type.
  1.1069 -     * (As with {@code asCollector}, if the array length is zero,
  1.1070 -     * a shared constant may be used instead of a new array.
  1.1071 -     * If the implied call to {@code asCollector} would throw
  1.1072 -     * an {@code IllegalArgumentException} or {@code WrongMethodTypeException},
  1.1073 -     * the call to the variable arity adapter must throw
  1.1074 -     * {@code WrongMethodTypeException}.)
  1.1075 -     * <p>
  1.1076 -     * The behavior of {@link #asType asType} is also specialized for
  1.1077 -     * variable arity adapters, to maintain the invariant that
  1.1078 -     * plain, inexact {@code invoke} is always equivalent to an {@code asType}
  1.1079 -     * call to adjust the target type, followed by {@code invokeExact}.
  1.1080 -     * Therefore, a variable arity adapter responds
  1.1081 -     * to an {@code asType} request by building a fixed arity collector,
  1.1082 -     * if and only if the adapter and requested type differ either
  1.1083 -     * in arity or trailing argument type.
  1.1084 -     * The resulting fixed arity collector has its type further adjusted
  1.1085 -     * (if necessary) to the requested type by pairwise conversion,
  1.1086 -     * as if by another application of {@code asType}.
  1.1087 -     * <p>
  1.1088 -     * When a method handle is obtained by executing an {@code ldc} instruction
  1.1089 -     * of a {@code CONSTANT_MethodHandle} constant, and the target method is marked
  1.1090 -     * as a variable arity method (with the modifier bit {@code 0x0080}),
  1.1091 -     * the method handle will accept multiple arities, as if the method handle
  1.1092 -     * constant were created by means of a call to {@code asVarargsCollector}.
  1.1093 -     * <p>
  1.1094 -     * In order to create a collecting adapter which collects a predetermined
  1.1095 -     * number of arguments, and whose type reflects this predetermined number,
  1.1096 -     * use {@link #asCollector asCollector} instead.
  1.1097 -     * <p>
  1.1098 -     * No method handle transformations produce new method handles with
  1.1099 -     * variable arity, unless they are documented as doing so.
  1.1100 -     * Therefore, besides {@code asVarargsCollector},
  1.1101 -     * all methods in {@code MethodHandle} and {@code MethodHandles}
  1.1102 -     * will return a method handle with fixed arity,
  1.1103 -     * except in the cases where they are specified to return their original
  1.1104 -     * operand (e.g., {@code asType} of the method handle's own type).
  1.1105 -     * <p>
  1.1106 -     * Calling {@code asVarargsCollector} on a method handle which is already
  1.1107 -     * of variable arity will produce a method handle with the same type and behavior.
  1.1108 -     * It may (or may not) return the original variable arity method handle.
  1.1109 -     * <p>
  1.1110 -     * Here is an example, of a list-making variable arity method handle:
  1.1111 -     * <blockquote><pre>{@code
  1.1112 -MethodHandle deepToString = publicLookup()
  1.1113 -  .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
  1.1114 -MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
  1.1115 -assertEquals("[won]",   (String) ts1.invokeExact(    new Object[]{"won"}));
  1.1116 -assertEquals("[won]",   (String) ts1.invoke(         new Object[]{"won"}));
  1.1117 -assertEquals("[won]",   (String) ts1.invoke(                      "won" ));
  1.1118 -assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"}));
  1.1119 -// findStatic of Arrays.asList(...) produces a variable arity method handle:
  1.1120 -MethodHandle asList = publicLookup()
  1.1121 -  .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
  1.1122 -assertEquals(methodType(List.class, Object[].class), asList.type());
  1.1123 -assert(asList.isVarargsCollector());
  1.1124 -assertEquals("[]", asList.invoke().toString());
  1.1125 -assertEquals("[1]", asList.invoke(1).toString());
  1.1126 -assertEquals("[two, too]", asList.invoke("two", "too").toString());
  1.1127 -String[] argv = { "three", "thee", "tee" };
  1.1128 -assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
  1.1129 -assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString());
  1.1130 -List ls = (List) asList.invoke((Object)argv);
  1.1131 -assertEquals(1, ls.size());
  1.1132 -assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
  1.1133 -     * }</pre></blockquote>
  1.1134 -     * <p style="font-size:smaller;">
  1.1135 -     * <em>Discussion:</em>
  1.1136 -     * These rules are designed as a dynamically-typed variation
  1.1137 -     * of the Java rules for variable arity methods.
  1.1138 -     * In both cases, callers to a variable arity method or method handle
  1.1139 -     * can either pass zero or more positional arguments, or else pass
  1.1140 -     * pre-collected arrays of any length.  Users should be aware of the
  1.1141 -     * special role of the final argument, and of the effect of a
  1.1142 -     * type match on that final argument, which determines whether
  1.1143 -     * or not a single trailing argument is interpreted as a whole
  1.1144 -     * array or a single element of an array to be collected.
  1.1145 -     * Note that the dynamic type of the trailing argument has no
  1.1146 -     * effect on this decision, only a comparison between the symbolic
  1.1147 -     * type descriptor of the call site and the type descriptor of the method handle.)
  1.1148 -     *
  1.1149 -     * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
  1.1150 -     * @return a new method handle which can collect any number of trailing arguments
  1.1151 -     *         into an array, before calling the original method handle
  1.1152 -     * @throws NullPointerException if {@code arrayType} is a null reference
  1.1153 -     * @throws IllegalArgumentException if {@code arrayType} is not an array type
  1.1154 -     *         or {@code arrayType} is not assignable to this method handle's trailing parameter type
  1.1155 -     * @see #asCollector
  1.1156 -     * @see #isVarargsCollector
  1.1157 -     * @see #asFixedArity
  1.1158 -     */
  1.1159 -    public MethodHandle asVarargsCollector(Class<?> arrayType) {
  1.1160 -        Class<?> arrayElement = arrayType.getComponentType();
  1.1161 -        boolean lastMatch = asCollectorChecks(arrayType, 0);
  1.1162 -        if (isVarargsCollector() && lastMatch)
  1.1163 -            return this;
  1.1164 -        return MethodHandleImpl.makeVarargsCollector(this, arrayType);
  1.1165 -    }
  1.1166 -
  1.1167 -    /**
  1.1168 -     * Determines if this method handle
  1.1169 -     * supports {@linkplain #asVarargsCollector variable arity} calls.
  1.1170 -     * Such method handles arise from the following sources:
  1.1171 -     * <ul>
  1.1172 -     * <li>a call to {@linkplain #asVarargsCollector asVarargsCollector}
  1.1173 -     * <li>a call to a {@linkplain java.lang.invoke.MethodHandles.Lookup lookup method}
  1.1174 -     *     which resolves to a variable arity Java method or constructor
  1.1175 -     * <li>an {@code ldc} instruction of a {@code CONSTANT_MethodHandle}
  1.1176 -     *     which resolves to a variable arity Java method or constructor
  1.1177 -     * </ul>
  1.1178 -     * @return true if this method handle accepts more than one arity of plain, inexact {@code invoke} calls
  1.1179 -     * @see #asVarargsCollector
  1.1180 -     * @see #asFixedArity
  1.1181 -     */
  1.1182 -    public boolean isVarargsCollector() {
  1.1183 -        return false;
  1.1184 -    }
  1.1185 -
  1.1186 -    /**
  1.1187 -     * Makes a <em>fixed arity</em> method handle which is otherwise
  1.1188 -     * equivalent to the current method handle.
  1.1189 -     * <p>
  1.1190 -     * If the current method handle is not of
  1.1191 -     * {@linkplain #asVarargsCollector variable arity},
  1.1192 -     * the current method handle is returned.
  1.1193 -     * This is true even if the current method handle
  1.1194 -     * could not be a valid input to {@code asVarargsCollector}.
  1.1195 -     * <p>
  1.1196 -     * Otherwise, the resulting fixed-arity method handle has the same
  1.1197 -     * type and behavior of the current method handle,
  1.1198 -     * except that {@link #isVarargsCollector isVarargsCollector}
  1.1199 -     * will be false.
  1.1200 -     * The fixed-arity method handle may (or may not) be the
  1.1201 -     * a previous argument to {@code asVarargsCollector}.
  1.1202 -     * <p>
  1.1203 -     * Here is an example, of a list-making variable arity method handle:
  1.1204 -     * <blockquote><pre>{@code
  1.1205 -MethodHandle asListVar = publicLookup()
  1.1206 -  .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
  1.1207 -  .asVarargsCollector(Object[].class);
  1.1208 -MethodHandle asListFix = asListVar.asFixedArity();
  1.1209 -assertEquals("[1]", asListVar.invoke(1).toString());
  1.1210 -Exception caught = null;
  1.1211 -try { asListFix.invoke((Object)1); }
  1.1212 -catch (Exception ex) { caught = ex; }
  1.1213 -assert(caught instanceof ClassCastException);
  1.1214 -assertEquals("[two, too]", asListVar.invoke("two", "too").toString());
  1.1215 -try { asListFix.invoke("two", "too"); }
  1.1216 -catch (Exception ex) { caught = ex; }
  1.1217 -assert(caught instanceof WrongMethodTypeException);
  1.1218 -Object[] argv = { "three", "thee", "tee" };
  1.1219 -assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString());
  1.1220 -assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
  1.1221 -assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
  1.1222 -assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
  1.1223 -     * }</pre></blockquote>
  1.1224 -     *
  1.1225 -     * @return a new method handle which accepts only a fixed number of arguments
  1.1226 -     * @see #asVarargsCollector
  1.1227 -     * @see #isVarargsCollector
  1.1228 -     */
  1.1229 -    public MethodHandle asFixedArity() {
  1.1230 -        assert(!isVarargsCollector());
  1.1231 -        return this;
  1.1232 -    }
  1.1233 -
  1.1234 -    /**
  1.1235 -     * Binds a value {@code x} to the first argument of a method handle, without invoking it.
  1.1236 -     * The new method handle adapts, as its <i>target</i>,
  1.1237 -     * the current method handle by binding it to the given argument.
  1.1238 -     * The type of the bound handle will be
  1.1239 -     * the same as the type of the target, except that a single leading
  1.1240 -     * reference parameter will be omitted.
  1.1241 -     * <p>
  1.1242 -     * When called, the bound handle inserts the given value {@code x}
  1.1243 -     * as a new leading argument to the target.  The other arguments are
  1.1244 -     * also passed unchanged.
  1.1245 -     * What the target eventually returns is returned unchanged by the bound handle.
  1.1246 -     * <p>
  1.1247 -     * The reference {@code x} must be convertible to the first parameter
  1.1248 -     * type of the target.
  1.1249 -     * <p>
  1.1250 -     * (<em>Note:</em>  Because method handles are immutable, the target method handle
  1.1251 -     * retains its original type and behavior.)
  1.1252 -     * @param x  the value to bind to the first argument of the target
  1.1253 -     * @return a new method handle which prepends the given value to the incoming
  1.1254 -     *         argument list, before calling the original method handle
  1.1255 -     * @throws IllegalArgumentException if the target does not have a
  1.1256 -     *         leading parameter type that is a reference type
  1.1257 -     * @throws ClassCastException if {@code x} cannot be converted
  1.1258 -     *         to the leading parameter type of the target
  1.1259 -     * @see MethodHandles#insertArguments
  1.1260 -     */
  1.1261 -    public MethodHandle bindTo(Object x) {
  1.1262 -        Class<?> ptype;
  1.1263 -        @SuppressWarnings("LocalVariableHidesMemberVariable")
  1.1264 -        MethodType type = type();
  1.1265 -        if (type.parameterCount() == 0 ||
  1.1266 -            (ptype = type.parameterType(0)).isPrimitive())
  1.1267 -            throw newIllegalArgumentException("no leading reference parameter", x);
  1.1268 -        x = ptype.cast(x);  // throw CCE if needed
  1.1269 -        return bindReceiver(x);
  1.1270 -    }
  1.1271 -
  1.1272 -    /**
  1.1273 -     * Returns a string representation of the method handle,
  1.1274 -     * starting with the string {@code "MethodHandle"} and
  1.1275 -     * ending with the string representation of the method handle's type.
  1.1276 -     * In other words, this method returns a string equal to the value of:
  1.1277 -     * <blockquote><pre>{@code
  1.1278 -     * "MethodHandle" + type().toString()
  1.1279 -     * }</pre></blockquote>
  1.1280 -     * <p>
  1.1281 -     * (<em>Note:</em>  Future releases of this API may add further information
  1.1282 -     * to the string representation.
  1.1283 -     * Therefore, the present syntax should not be parsed by applications.)
  1.1284 -     *
  1.1285 -     * @return a string representation of the method handle
  1.1286 -     */
  1.1287 -    @Override
  1.1288 -    public String toString() {
  1.1289 -        if (DEBUG_METHOD_HANDLE_NAMES)  return debugString();
  1.1290 -        return standardString();
  1.1291 -    }
  1.1292 -    String standardString() {
  1.1293 -        return "MethodHandle"+type;
  1.1294 -    }
  1.1295 -    String debugString() {
  1.1296 -        return standardString()+"/LF="+internalForm()+internalProperties();
  1.1297 -    }
  1.1298 -
  1.1299 -    //// Implementation methods.
  1.1300 -    //// Sub-classes can override these default implementations.
  1.1301 -    //// All these methods assume arguments are already validated.
  1.1302 -
  1.1303 -    // Other transforms to do:  convert, explicitCast, permute, drop, filter, fold, GWT, catch
  1.1304 -
  1.1305 -    /*non-public*/
  1.1306 -    MethodHandle setVarargs(MemberName member) throws IllegalAccessException {
  1.1307 -        if (!member.isVarargs())  return this;
  1.1308 -        int argc = type().parameterCount();
  1.1309 -        if (argc != 0) {
  1.1310 -            Class<?> arrayType = type().parameterType(argc-1);
  1.1311 -            if (arrayType.isArray()) {
  1.1312 -                return MethodHandleImpl.makeVarargsCollector(this, arrayType);
  1.1313 -            }
  1.1314 -        }
  1.1315 -        throw member.makeAccessException("cannot make variable arity", null);
  1.1316 -    }
  1.1317 -    /*non-public*/
  1.1318 -    MethodHandle viewAsType(MethodType newType) {
  1.1319 -        // No actual conversions, just a new view of the same method.
  1.1320 -        return MethodHandleImpl.makePairwiseConvert(this, newType, 0);
  1.1321 -    }
  1.1322 -
  1.1323 -    // Decoding
  1.1324 -
  1.1325 -    /*non-public*/
  1.1326 -    LambdaForm internalForm() {
  1.1327 -        return form;
  1.1328 -    }
  1.1329 -
  1.1330 -    /*non-public*/
  1.1331 -    MemberName internalMemberName() {
  1.1332 -        return null;  // DMH returns DMH.member
  1.1333 -    }
  1.1334 -
  1.1335 -    /*non-public*/
  1.1336 -    Class<?> internalCallerClass() {
  1.1337 -        return null;  // caller-bound MH for @CallerSensitive method returns caller
  1.1338 -    }
  1.1339 -
  1.1340 -    /*non-public*/
  1.1341 -    MethodHandle withInternalMemberName(MemberName member) {
  1.1342 -        if (member != null) {
  1.1343 -            return MethodHandleImpl.makeWrappedMember(this, member);
  1.1344 -        } else if (internalMemberName() == null) {
  1.1345 -            // The required internaMemberName is null, and this MH (like most) doesn't have one.
  1.1346 -            return this;
  1.1347 -        } else {
  1.1348 -            // The following case is rare. Mask the internalMemberName by wrapping the MH in a BMH.
  1.1349 -            MethodHandle result = rebind();
  1.1350 -            assert (result.internalMemberName() == null);
  1.1351 -            return result;
  1.1352 -        }
  1.1353 -    }
  1.1354 -
  1.1355 -    /*non-public*/
  1.1356 -    boolean isInvokeSpecial() {
  1.1357 -        return false;  // DMH.Special returns true
  1.1358 -    }
  1.1359 -
  1.1360 -    /*non-public*/
  1.1361 -    Object internalValues() {
  1.1362 -        return null;
  1.1363 -    }
  1.1364 -
  1.1365 -    /*non-public*/
  1.1366 -    Object internalProperties() {
  1.1367 -        // Override to something like "/FOO=bar"
  1.1368 -        return "";
  1.1369 -    }
  1.1370 -
  1.1371 -    //// Method handle implementation methods.
  1.1372 -    //// Sub-classes can override these default implementations.
  1.1373 -    //// All these methods assume arguments are already validated.
  1.1374 -
  1.1375 -    /*non-public*/ MethodHandle convertArguments(MethodType newType) {
  1.1376 -        // Override this if it can be improved.
  1.1377 -        return MethodHandleImpl.makePairwiseConvert(this, newType, 1);
  1.1378 -    }
  1.1379 -
  1.1380 -    /*non-public*/
  1.1381 -    MethodHandle bindArgument(int pos, char basicType, Object value) {
  1.1382 -        // Override this if it can be improved.
  1.1383 -        return rebind().bindArgument(pos, basicType, value);
  1.1384 -    }
  1.1385 -
  1.1386 -    /*non-public*/
  1.1387 -    MethodHandle bindReceiver(Object receiver) {
  1.1388 -        // Override this if it can be improved.
  1.1389 -        return bindArgument(0, 'L', receiver);
  1.1390 -    }
  1.1391 -
  1.1392 -    /*non-public*/
  1.1393 -    MethodHandle bindImmediate(int pos, char basicType, Object value) {
  1.1394 -        // Bind an immediate value to a position in the arguments.
  1.1395 -        // This means, elide the respective argument,
  1.1396 -        // and replace all references to it in NamedFunction args with the specified value.
  1.1397 -
  1.1398 -        // CURRENT RESTRICTIONS
  1.1399 -        // * only for pos 0 and UNSAFE (position is adjusted in MHImpl to make API usable for others)
  1.1400 -//        assert pos == 0 && basicType == 'L' && value instanceof Unsafe;
  1.1401 -        MethodType type2 = type.dropParameterTypes(pos, pos + 1); // adjustment: ignore receiver!
  1.1402 -        LambdaForm form2 = form.bindImmediate(pos + 1, basicType, value); // adjust pos to form-relative pos
  1.1403 -        return copyWith(type2, form2);
  1.1404 -    }
  1.1405 -
  1.1406 -    /*non-public*/
  1.1407 -    MethodHandle copyWith(MethodType mt, LambdaForm lf) {
  1.1408 -        throw new InternalError("copyWith: " + this.getClass());
  1.1409 -    }
  1.1410 -
  1.1411 -    /*non-public*/
  1.1412 -    MethodHandle dropArguments(MethodType srcType, int pos, int drops) {
  1.1413 -        // Override this if it can be improved.
  1.1414 -        return rebind().dropArguments(srcType, pos, drops);
  1.1415 -    }
  1.1416 -
  1.1417 -    /*non-public*/
  1.1418 -    MethodHandle permuteArguments(MethodType newType, int[] reorder) {
  1.1419 -        // Override this if it can be improved.
  1.1420 -        return rebind().permuteArguments(newType, reorder);
  1.1421 -    }
  1.1422 -
  1.1423 -    /*non-public*/
  1.1424 -    MethodHandle rebind() {
  1.1425 -        // Bind 'this' into a new invoker, of the known class BMH.
  1.1426 -        MethodType type2 = type();
  1.1427 -        LambdaForm form2 = reinvokerForm(this);
  1.1428 -        // form2 = lambda (bmh, arg*) { thismh = bmh[0]; invokeBasic(thismh, arg*) }
  1.1429 -        return BoundMethodHandle.bindSingle(type2, form2, this);
  1.1430 -    }
  1.1431 -
  1.1432 -    /*non-public*/
  1.1433 -    MethodHandle reinvokerTarget() {
  1.1434 -        throw new InternalError("not a reinvoker MH: "+this.getClass().getName()+": "+this);
  1.1435 -    }
  1.1436 -
  1.1437 -    /** Create a LF which simply reinvokes a target of the given basic type.
  1.1438 -     *  The target MH must override {@link #reinvokerTarget} to provide the target.
  1.1439 -     */
  1.1440 -    static LambdaForm reinvokerForm(MethodHandle target) {
  1.1441 -        MethodType mtype = target.type().basicType();
  1.1442 -        LambdaForm reinvoker = mtype.form().cachedLambdaForm(MethodTypeForm.LF_REINVOKE);
  1.1443 -        if (reinvoker != null)  return reinvoker;
  1.1444 -        if (mtype.parameterSlotCount() >= MethodType.MAX_MH_ARITY)
  1.1445 -            return makeReinvokerForm(target.type(), target);  // cannot cache this
  1.1446 -        reinvoker = makeReinvokerForm(mtype, null);
  1.1447 -        return mtype.form().setCachedLambdaForm(MethodTypeForm.LF_REINVOKE, reinvoker);
  1.1448 -    }
  1.1449 -    private static LambdaForm makeReinvokerForm(MethodType mtype, MethodHandle customTargetOrNull) {
  1.1450 -        boolean customized = (customTargetOrNull != null);
  1.1451 -        MethodHandle MH_invokeBasic = customized ? null : MethodHandles.basicInvoker(mtype);
  1.1452 -        final int THIS_BMH    = 0;
  1.1453 -        final int ARG_BASE    = 1;
  1.1454 -        final int ARG_LIMIT   = ARG_BASE + mtype.parameterCount();
  1.1455 -        int nameCursor = ARG_LIMIT;
  1.1456 -        final int NEXT_MH     = customized ? -1 : nameCursor++;
  1.1457 -        final int REINVOKE    = nameCursor++;
  1.1458 -        LambdaForm.Name[] names = LambdaForm.arguments(nameCursor - ARG_LIMIT, mtype.invokerType());
  1.1459 -        Object[] targetArgs;
  1.1460 -        MethodHandle targetMH;
  1.1461 -        if (customized) {
  1.1462 -            targetArgs = Arrays.copyOfRange(names, ARG_BASE, ARG_LIMIT, Object[].class);
  1.1463 -            targetMH = customTargetOrNull;
  1.1464 -        } else {
  1.1465 -            names[NEXT_MH] = new LambdaForm.Name(NF_reinvokerTarget, names[THIS_BMH]);
  1.1466 -            targetArgs = Arrays.copyOfRange(names, THIS_BMH, ARG_LIMIT, Object[].class);
  1.1467 -            targetArgs[0] = names[NEXT_MH];  // overwrite this MH with next MH
  1.1468 -            targetMH = MethodHandles.basicInvoker(mtype);
  1.1469 -        }
  1.1470 -        names[REINVOKE] = new LambdaForm.Name(targetMH, targetArgs);
  1.1471 -        return new LambdaForm("BMH.reinvoke", ARG_LIMIT, names);
  1.1472 -    }
  1.1473 -
  1.1474 -    private static final LambdaForm.NamedFunction NF_reinvokerTarget;
  1.1475 -    static {
  1.1476 -        try {
  1.1477 -            NF_reinvokerTarget = new LambdaForm.NamedFunction(MethodHandle.class
  1.1478 -                .getDeclaredMethod("reinvokerTarget"));
  1.1479 -        } catch (ReflectiveOperationException ex) {
  1.1480 -            throw newInternalError(ex);
  1.1481 -        }
  1.1482 -    }
  1.1483 -
  1.1484 -    /**
  1.1485 -     * Replace the old lambda form of this method handle with a new one.
  1.1486 -     * The new one must be functionally equivalent to the old one.
  1.1487 -     * Threads may continue running the old form indefinitely,
  1.1488 -     * but it is likely that the new one will be preferred for new executions.
  1.1489 -     * Use with discretion.
  1.1490 -     */
  1.1491 -    /*non-public*/
  1.1492 -    void updateForm(LambdaForm newForm) {
  1.1493 -        if (form == newForm)  return;
  1.1494 -        this.form = newForm;
  1.1495 -        this.form.prepare();  // as in MethodHandle.<init>
  1.1496 -    }
  1.1497 -}