1 /*
   2  * Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 
  29 import jdk.internal.HotSpotIntrinsicCandidate;
  30 
  31 import java.util.Arrays;
  32 import java.util.Objects;
  33 
  34 import static java.lang.invoke.MethodHandleStatics.*;
  35 
  36 /**
  37  * A method handle is a typed, directly executable reference to an underlying method,
  38  * constructor, field, or similar low-level operation, with optional
  39  * transformations of arguments or return values.
  40  * These transformations are quite general, and include such patterns as
  41  * {@linkplain #asType conversion},
  42  * {@linkplain #bindTo insertion},
  43  * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion},
  44  * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}.
  45  *
  46  * <h1>Method handle contents</h1>
  47  * Method handles are dynamically and strongly typed according to their parameter and return types.
  48  * They are not distinguished by the name or the defining class of their underlying methods.
  49  * A method handle must be invoked using a symbolic type descriptor which matches
  50  * the method handle's own {@linkplain #type() type descriptor}.
  51  * <p>
  52  * Every method handle reports its type descriptor via the {@link #type() type} accessor.
  53  * This type descriptor is a {@link java.lang.invoke.MethodType MethodType} object,
  54  * whose structure is a series of classes, one of which is
  55  * the return type of the method (or {@code void.class} if none).
  56  * <p>
  57  * A method handle's type controls the types of invocations it accepts,
  58  * and the kinds of transformations that apply to it.
  59  * <p>
  60  * A method handle contains a pair of special invoker methods
  61  * called {@link #invokeExact invokeExact} and {@link #invoke invoke}.
  62  * Both invoker methods provide direct access to the method handle's
  63  * underlying method, constructor, field, or other operation,
  64  * as modified by transformations of arguments and return values.
  65  * Both invokers accept calls which exactly match the method handle's own type.
  66  * The plain, inexact invoker also accepts a range of other call types.
  67  * <p>
  68  * Method handles are immutable and have no visible state.
  69  * Of course, they can be bound to underlying methods or data which exhibit state.
  70  * With respect to the Java Memory Model, any method handle will behave
  71  * as if all of its (internal) fields are final variables.  This means that any method
  72  * handle made visible to the application will always be fully formed.
  73  * This is true even if the method handle is published through a shared
  74  * variable in a data race.
  75  * <p>
  76  * Method handles cannot be subclassed by the user.
  77  * Implementations may (or may not) create internal subclasses of {@code MethodHandle}
  78  * which may be visible via the {@link java.lang.Object#getClass Object.getClass}
  79  * operation.  The programmer should not draw conclusions about a method handle
  80  * from its specific class, as the method handle class hierarchy (if any)
  81  * may change from time to time or across implementations from different vendors.
  82  *
  83  * <h1>Method handle compilation</h1>
  84  * A Java method call expression naming {@code invokeExact} or {@code invoke}
  85  * can invoke a method handle from Java source code.
  86  * From the viewpoint of source code, these methods can take any arguments
  87  * and their result can be cast to any return type.
  88  * Formally this is accomplished by giving the invoker methods
  89  * {@code Object} return types and variable arity {@code Object} arguments,
  90  * but they have an additional quality called <em>signature polymorphism</em>
  91  * which connects this freedom of invocation directly to the JVM execution stack.
  92  * <p>
  93  * As is usual with virtual methods, source-level calls to {@code invokeExact}
  94  * and {@code invoke} compile to an {@code invokevirtual} instruction.
  95  * More unusually, the compiler must record the actual argument types,
  96  * and may not perform method invocation conversions on the arguments.
  97  * Instead, it must generate instructions that push them on the stack according
  98  * to their own unconverted types.  The method handle object itself is pushed on
  99  * the stack before the arguments.
 100  * The compiler then generates an {@code invokevirtual} instruction that invokes
 101  * the method handle with a symbolic type descriptor which describes the argument
 102  * and return types.
 103  * <p>
 104  * To issue a complete symbolic type descriptor, the compiler must also determine
 105  * the return type.  This is based on a cast on the method invocation expression,
 106  * if there is one, or else {@code Object} if the invocation is an expression,
 107  * or else {@code void} if the invocation is a statement.
 108  * The cast may be to a primitive type (but not {@code void}).
 109  * <p>
 110  * As a corner case, an uncasted {@code null} argument is given
 111  * a symbolic type descriptor of {@code java.lang.Void}.
 112  * The ambiguity with the type {@code Void} is harmless, since there are no references of type
 113  * {@code Void} except the null reference.
 114  *
 115  * <h1>Method handle invocation</h1>
 116  * The first time an {@code invokevirtual} instruction is executed
 117  * it is linked by symbolically resolving the names in the instruction
 118  * and verifying that the method call is statically legal.
 119  * This also holds for calls to {@code invokeExact} and {@code invoke}.
 120  * In this case, the symbolic type descriptor emitted by the compiler is checked for
 121  * correct syntax, and names it contains are resolved.
 122  * Thus, an {@code invokevirtual} instruction which invokes
 123  * a method handle will always link, as long
 124  * as the symbolic type descriptor is syntactically well-formed
 125  * and the types exist.
 126  * <p>
 127  * When the {@code invokevirtual} is executed after linking,
 128  * the receiving method handle's type is first checked by the JVM
 129  * to ensure that it matches the symbolic type descriptor.
 130  * If the type match fails, it means that the method which the
 131  * caller is invoking is not present on the individual
 132  * method handle being invoked.
 133  * <p>
 134  * In the case of {@code invokeExact}, the type descriptor of the invocation
 135  * (after resolving symbolic type names) must exactly match the method type
 136  * of the receiving method handle.
 137  * In the case of plain, inexact {@code invoke}, the resolved type descriptor
 138  * must be a valid argument to the receiver's {@link #asType asType} method.
 139  * Thus, plain {@code invoke} is more permissive than {@code invokeExact}.
 140  * <p>
 141  * After type matching, a call to {@code invokeExact} directly
 142  * and immediately invoke the method handle's underlying method
 143  * (or other behavior, as the case may be).
 144  * <p>
 145  * A call to plain {@code invoke} works the same as a call to
 146  * {@code invokeExact}, if the symbolic type descriptor specified by the caller
 147  * exactly matches the method handle's own type.
 148  * If there is a type mismatch, {@code invoke} attempts
 149  * to adjust the type of the receiving method handle,
 150  * as if by a call to {@link #asType asType},
 151  * to obtain an exactly invokable method handle {@code M2}.
 152  * This allows a more powerful negotiation of method type
 153  * between caller and callee.
 154  * <p>
 155  * (<em>Note:</em> The adjusted method handle {@code M2} is not directly observable,
 156  * and implementations are therefore not required to materialize it.)
 157  *
 158  * <h1>Invocation checking</h1>
 159  * In typical programs, method handle type matching will usually succeed.
 160  * But if a match fails, the JVM will throw a {@link WrongMethodTypeException},
 161  * either directly (in the case of {@code invokeExact}) or indirectly as if
 162  * by a failed call to {@code asType} (in the case of {@code invoke}).
 163  * <p>
 164  * Thus, a method type mismatch which might show up as a linkage error
 165  * in a statically typed program can show up as
 166  * a dynamic {@code WrongMethodTypeException}
 167  * in a program which uses method handles.
 168  * <p>
 169  * Because method types contain "live" {@code Class} objects,
 170  * method type matching takes into account both type names and class loaders.
 171  * Thus, even if a method handle {@code M} is created in one
 172  * class loader {@code L1} and used in another {@code L2},
 173  * method handle calls are type-safe, because the caller's symbolic type
 174  * descriptor, as resolved in {@code L2},
 175  * is matched against the original callee method's symbolic type descriptor,
 176  * as resolved in {@code L1}.
 177  * The resolution in {@code L1} happens when {@code M} is created
 178  * and its type is assigned, while the resolution in {@code L2} happens
 179  * when the {@code invokevirtual} instruction is linked.
 180  * <p>
 181  * Apart from type descriptor checks,
 182  * a method handle's capability to call its underlying method is unrestricted.
 183  * If a method handle is formed on a non-public method by a class
 184  * that has access to that method, the resulting handle can be used
 185  * in any place by any caller who receives a reference to it.
 186  * <p>
 187  * Unlike with the Core Reflection API, where access is checked every time
 188  * a reflective method is invoked,
 189  * method handle access checking is performed
 190  * <a href="MethodHandles.Lookup.html#access">when the method handle is created</a>.
 191  * In the case of {@code ldc} (see below), access checking is performed as part of linking
 192  * the constant pool entry underlying the constant method handle.
 193  * <p>
 194  * Thus, handles to non-public methods, or to methods in non-public classes,
 195  * should generally be kept secret.
 196  * They should not be passed to untrusted code unless their use from
 197  * the untrusted code would be harmless.
 198  *
 199  * <h1>Method handle creation</h1>
 200  * Java code can create a method handle that directly accesses
 201  * any method, constructor, or field that is accessible to that code.
 202  * This is done via a reflective, capability-based API called
 203  * {@link java.lang.invoke.MethodHandles.Lookup MethodHandles.Lookup}.
 204  * For example, a static method handle can be obtained
 205  * from {@link java.lang.invoke.MethodHandles.Lookup#findStatic Lookup.findStatic}.
 206  * There are also conversion methods from Core Reflection API objects,
 207  * such as {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
 208  * <p>
 209  * Like classes and strings, method handles that correspond to accessible
 210  * fields, methods, and constructors can also be represented directly
 211  * in a class file's constant pool as constants to be loaded by {@code ldc} bytecodes.
 212  * A new type of constant pool entry, {@code CONSTANT_MethodHandle},
 213  * refers directly to an associated {@code CONSTANT_Methodref},
 214  * {@code CONSTANT_InterfaceMethodref}, or {@code CONSTANT_Fieldref}
 215  * constant pool entry.
 216  * (For full details on method handle constants,
 217  * see sections 4.4.8 and 5.4.3.5 of the Java Virtual Machine Specification.)
 218  * <p>
 219  * Method handles produced by lookups or constant loads from methods or
 220  * constructors with the variable arity modifier bit ({@code 0x0080})
 221  * have a corresponding variable arity, as if they were defined with
 222  * the help of {@link #asVarargsCollector asVarargsCollector}
 223  * or {@link #withVarargs withVarargs}.
 224  * <p>
 225  * A method reference may refer either to a static or non-static method.
 226  * In the non-static case, the method handle type includes an explicit
 227  * receiver argument, prepended before any other arguments.
 228  * In the method handle's type, the initial receiver argument is typed
 229  * according to the class under which the method was initially requested.
 230  * (E.g., if a non-static method handle is obtained via {@code ldc},
 231  * the type of the receiver is the class named in the constant pool entry.)
 232  * <p>
 233  * Method handle constants are subject to the same link-time access checks
 234  * their corresponding bytecode instructions, and the {@code ldc} instruction
 235  * will throw corresponding linkage errors if the bytecode behaviors would
 236  * throw such errors.
 237  * <p>
 238  * As a corollary of this, access to protected members is restricted
 239  * to receivers only of the accessing class, or one of its subclasses,
 240  * and the accessing class must in turn be a subclass (or package sibling)
 241  * of the protected member's defining class.
 242  * If a method reference refers to a protected non-static method or field
 243  * of a class outside the current package, the receiver argument will
 244  * be narrowed to the type of the accessing class.
 245  * <p>
 246  * When a method handle to a virtual method is invoked, the method is
 247  * always looked up in the receiver (that is, the first argument).
 248  * <p>
 249  * A non-virtual method handle to a specific virtual method implementation
 250  * can also be created.  These do not perform virtual lookup based on
 251  * receiver type.  Such a method handle simulates the effect of
 252  * an {@code invokespecial} instruction to the same method.
 253  *
 254  * <h1>Usage examples</h1>
 255  * Here are some examples of usage:
 256  * <blockquote><pre>{@code
 257 Object x, y; String s; int i;
 258 MethodType mt; MethodHandle mh;
 259 MethodHandles.Lookup lookup = MethodHandles.lookup();
 260 // mt is (char,char)String
 261 mt = MethodType.methodType(String.class, char.class, char.class);
 262 mh = lookup.findVirtual(String.class, "replace", mt);
 263 s = (String) mh.invokeExact("daddy",'d','n');
 264 // invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
 265 assertEquals(s, "nanny");
 266 // weakly typed invocation (using MHs.invoke)
 267 s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
 268 assertEquals(s, "savvy");
 269 // mt is (Object[])List
 270 mt = MethodType.methodType(java.util.List.class, Object[].class);
 271 mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
 272 assert(mh.isVarargsCollector());
 273 x = mh.invoke("one", "two");
 274 // invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
 275 assertEquals(x, java.util.Arrays.asList("one","two"));
 276 // mt is (Object,Object,Object)Object
 277 mt = MethodType.genericMethodType(3);
 278 mh = mh.asType(mt);
 279 x = mh.invokeExact((Object)1, (Object)2, (Object)3);
 280 // invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
 281 assertEquals(x, java.util.Arrays.asList(1,2,3));
 282 // mt is ()int
 283 mt = MethodType.methodType(int.class);
 284 mh = lookup.findVirtual(java.util.List.class, "size", mt);
 285 i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
 286 // invokeExact(Ljava/util/List;)I
 287 assert(i == 3);
 288 mt = MethodType.methodType(void.class, String.class);
 289 mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
 290 mh.invokeExact(System.out, "Hello, world.");
 291 // invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
 292  * }</pre></blockquote>
 293  * Each of the above calls to {@code invokeExact} or plain {@code invoke}
 294  * generates a single invokevirtual instruction with
 295  * the symbolic type descriptor indicated in the following comment.
 296  * In these examples, the helper method {@code assertEquals} is assumed to
 297  * be a method which calls {@link java.util.Objects#equals(Object,Object) Objects.equals}
 298  * on its arguments, and asserts that the result is true.
 299  *
 300  * <h1>Exceptions</h1>
 301  * The methods {@code invokeExact} and {@code invoke} are declared
 302  * to throw {@link java.lang.Throwable Throwable},
 303  * which is to say that there is no static restriction on what a method handle
 304  * can throw.  Since the JVM does not distinguish between checked
 305  * and unchecked exceptions (other than by their class, of course),
 306  * there is no particular effect on bytecode shape from ascribing
 307  * checked exceptions to method handle invocations.  But in Java source
 308  * code, methods which perform method handle calls must either explicitly
 309  * throw {@code Throwable}, or else must catch all
 310  * throwables locally, rethrowing only those which are legal in the context,
 311  * and wrapping ones which are illegal.
 312  *
 313  * <h1><a id="sigpoly"></a>Signature polymorphism</h1>
 314  * The unusual compilation and linkage behavior of
 315  * {@code invokeExact} and plain {@code invoke}
 316  * is referenced by the term <em>signature polymorphism</em>.
 317  * As defined in the Java Language Specification,
 318  * a signature polymorphic method is one which can operate with
 319  * any of a wide range of call signatures and return types.
 320  * <p>
 321  * In source code, a call to a signature polymorphic method will
 322  * compile, regardless of the requested symbolic type descriptor.
 323  * As usual, the Java compiler emits an {@code invokevirtual}
 324  * instruction with the given symbolic type descriptor against the named method.
 325  * The unusual part is that the symbolic type descriptor is derived from
 326  * the actual argument and return types, not from the method declaration.
 327  * <p>
 328  * When the JVM processes bytecode containing signature polymorphic calls,
 329  * it will successfully link any such call, regardless of its symbolic type descriptor.
 330  * (In order to retain type safety, the JVM will guard such calls with suitable
 331  * dynamic type checks, as described elsewhere.)
 332  * <p>
 333  * Bytecode generators, including the compiler back end, are required to emit
 334  * untransformed symbolic type descriptors for these methods.
 335  * Tools which determine symbolic linkage are required to accept such
 336  * untransformed descriptors, without reporting linkage errors.
 337  *
 338  * <h1>Interoperation between method handles and the Core Reflection API</h1>
 339  * Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup Lookup} API,
 340  * any class member represented by a Core Reflection API object
 341  * can be converted to a behaviorally equivalent method handle.
 342  * For example, a reflective {@link java.lang.reflect.Method Method} can
 343  * be converted to a method handle using
 344  * {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
 345  * The resulting method handles generally provide more direct and efficient
 346  * access to the underlying class members.
 347  * <p>
 348  * As a special case,
 349  * when the Core Reflection API is used to view the signature polymorphic
 350  * methods {@code invokeExact} or plain {@code invoke} in this class,
 351  * they appear as ordinary non-polymorphic methods.
 352  * Their reflective appearance, as viewed by
 353  * {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod},
 354  * is unaffected by their special status in this API.
 355  * For example, {@link java.lang.reflect.Method#getModifiers Method.getModifiers}
 356  * will report exactly those modifier bits required for any similarly
 357  * declared method, including in this case {@code native} and {@code varargs} bits.
 358  * <p>
 359  * As with any reflected method, these methods (when reflected) may be
 360  * invoked via {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.
 361  * However, such reflective calls do not result in method handle invocations.
 362  * Such a call, if passed the required argument
 363  * (a single one, of type {@code Object[]}), will ignore the argument and
 364  * will throw an {@code UnsupportedOperationException}.
 365  * <p>
 366  * Since {@code invokevirtual} instructions can natively
 367  * invoke method handles under any symbolic type descriptor, this reflective view conflicts
 368  * with the normal presentation of these methods via bytecodes.
 369  * Thus, these two native methods, when reflectively viewed by
 370  * {@code Class.getDeclaredMethod}, may be regarded as placeholders only.
 371  * <p>
 372  * In order to obtain an invoker method for a particular type descriptor,
 373  * use {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker},
 374  * or {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}.
 375  * The {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual}
 376  * API is also able to return a method handle
 377  * to call {@code invokeExact} or plain {@code invoke},
 378  * for any specified type descriptor .
 379  *
 380  * <h1>Interoperation between method handles and Java generics</h1>
 381  * A method handle can be obtained on a method, constructor, or field
 382  * which is declared with Java generic types.
 383  * As with the Core Reflection API, the type of the method handle
 384  * will constructed from the erasure of the source-level type.
 385  * When a method handle is invoked, the types of its arguments
 386  * or the return value cast type may be generic types or type instances.
 387  * If this occurs, the compiler will replace those
 388  * types by their erasures when it constructs the symbolic type descriptor
 389  * for the {@code invokevirtual} instruction.
 390  * <p>
 391  * Method handles do not represent
 392  * their function-like types in terms of Java parameterized (generic) types,
 393  * because there are three mismatches between function-like types and parameterized
 394  * Java types.
 395  * <ul>
 396  * <li>Method types range over all possible arities,
 397  * from no arguments to up to the  <a href="MethodHandle.html#maxarity">maximum number</a> of allowed arguments.
 398  * Generics are not variadic, and so cannot represent this.</li>
 399  * <li>Method types can specify arguments of primitive types,
 400  * which Java generic types cannot range over.</li>
 401  * <li>Higher order functions over method handles (combinators) are
 402  * often generic across a wide range of function types, including
 403  * those of multiple arities.  It is impossible to represent such
 404  * genericity with a Java type parameter.</li>
 405  * </ul>
 406  *
 407  * <h1><a id="maxarity"></a>Arity limits</h1>
 408  * The JVM imposes on all methods and constructors of any kind an absolute
 409  * limit of 255 stacked arguments.  This limit can appear more restrictive
 410  * in certain cases:
 411  * <ul>
 412  * <li>A {@code long} or {@code double} argument counts (for purposes of arity limits) as two argument slots.
 413  * <li>A non-static method consumes an extra argument for the object on which the method is called.
 414  * <li>A constructor consumes an extra argument for the object which is being constructed.
 415  * <li>Since a method handle&rsquo;s {@code invoke} method (or other signature-polymorphic method) is non-virtual,
 416  *     it consumes an extra argument for the method handle itself, in addition to any non-virtual receiver object.
 417  * </ul>
 418  * These limits imply that certain method handles cannot be created, solely because of the JVM limit on stacked arguments.
 419  * For example, if a static JVM method accepts exactly 255 arguments, a method handle cannot be created for it.
 420  * Attempts to create method handles with impossible method types lead to an {@link IllegalArgumentException}.
 421  * In particular, a method handle&rsquo;s type must not have an arity of the exact maximum 255.
 422  *
 423  * @see MethodType
 424  * @see MethodHandles
 425  * @author John Rose, JSR 292 EG
 426  * @since 1.7
 427  */
 428 public abstract class MethodHandle {
 429 
 430     /**
 431      * Internal marker interface which distinguishes (to the Java compiler)
 432      * those methods which are <a href="MethodHandle.html#sigpoly">signature polymorphic</a>.
 433      */
 434     @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
 435     @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
 436     @interface PolymorphicSignature { }
 437 
 438     private final MethodType type;
 439     /*private*/ final LambdaForm form;
 440     // form is not private so that invokers can easily fetch it
 441     /*private*/ MethodHandle asTypeCache;
 442     // asTypeCache is not private so that invokers can easily fetch it
 443     /*non-public*/ byte customizationCount;
 444     // customizationCount should be accessible from invokers
 445 
 446     /**
 447      * Reports the type of this method handle.
 448      * Every invocation of this method handle via {@code invokeExact} must exactly match this type.
 449      * @return the method handle type
 450      */
 451     public MethodType type() {
 452         return type;
 453     }
 454 
 455     /**
 456      * Package-private constructor for the method handle implementation hierarchy.
 457      * Method handle inheritance will be contained completely within
 458      * the {@code java.lang.invoke} package.
 459      */
 460     // @param type type (permanently assigned) of the new method handle
 461     /*non-public*/ MethodHandle(MethodType type, LambdaForm form) {
 462         this.type = Objects.requireNonNull(type);
 463         this.form = Objects.requireNonNull(form).uncustomize();
 464 
 465         this.form.prepare();  // TO DO:  Try to delay this step until just before invocation.
 466     }
 467 
 468     /**
 469      * Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match.
 470      * The symbolic type descriptor at the call site of {@code invokeExact} must
 471      * exactly match this method handle's {@link #type() type}.
 472      * No conversions are allowed on arguments or return values.
 473      * <p>
 474      * When this method is observed via the Core Reflection API,
 475      * it will appear as a single native method, taking an object array and returning an object.
 476      * If this native method is invoked directly via
 477      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
 478      * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
 479      * it will throw an {@code UnsupportedOperationException}.
 480      * @param args the signature-polymorphic parameter list, statically represented using varargs
 481      * @return the signature-polymorphic result, statically represented using {@code Object}
 482      * @throws WrongMethodTypeException if the target's type is not identical with the caller's symbolic type descriptor
 483      * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
 484      */
 485     @HotSpotIntrinsicCandidate
 486     public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable;
 487 
 488     /**
 489      * Invokes the method handle, allowing any caller type descriptor,
 490      * and optionally performing conversions on arguments and return values.
 491      * <p>
 492      * If the call site's symbolic type descriptor exactly matches this method handle's {@link #type() type},
 493      * the call proceeds as if by {@link #invokeExact invokeExact}.
 494      * <p>
 495      * Otherwise, the call proceeds as if this method handle were first
 496      * adjusted by calling {@link #asType asType} to adjust this method handle
 497      * to the required type, and then the call proceeds as if by
 498      * {@link #invokeExact invokeExact} on the adjusted method handle.
 499      * <p>
 500      * There is no guarantee that the {@code asType} call is actually made.
 501      * If the JVM can predict the results of making the call, it may perform
 502      * adaptations directly on the caller's arguments,
 503      * and call the target method handle according to its own exact type.
 504      * <p>
 505      * The resolved type descriptor at the call site of {@code invoke} must
 506      * be a valid argument to the receivers {@code asType} method.
 507      * In particular, the caller must specify the same argument arity
 508      * as the callee's type,
 509      * if the callee is not a {@linkplain #asVarargsCollector variable arity collector}.
 510      * <p>
 511      * When this method is observed via the Core Reflection API,
 512      * it will appear as a single native method, taking an object array and returning an object.
 513      * If this native method is invoked directly via
 514      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
 515      * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
 516      * it will throw an {@code UnsupportedOperationException}.
 517      * @param args the signature-polymorphic parameter list, statically represented using varargs
 518      * @return the signature-polymorphic result, statically represented using {@code Object}
 519      * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's symbolic type descriptor
 520      * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails
 521      * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
 522      */
 523     @HotSpotIntrinsicCandidate
 524     public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable;
 525 
 526     /**
 527      * Private method for trusted invocation of a method handle respecting simplified signatures.
 528      * Type mismatches will not throw {@code WrongMethodTypeException}, but could crash the JVM.
 529      * <p>
 530      * The caller signature is restricted to the following basic types:
 531      * Object, int, long, float, double, and void return.
 532      * <p>
 533      * The caller is responsible for maintaining type correctness by ensuring
 534      * that the each outgoing argument value is a member of the range of the corresponding
 535      * callee argument type.
 536      * (The caller should therefore issue appropriate casts and integer narrowing
 537      * operations on outgoing argument values.)
 538      * The caller can assume that the incoming result value is part of the range
 539      * of the callee's return type.
 540      * @param args the signature-polymorphic parameter list, statically represented using varargs
 541      * @return the signature-polymorphic result, statically represented using {@code Object}
 542      */
 543     @HotSpotIntrinsicCandidate
 544     /*non-public*/ final native @PolymorphicSignature Object invokeBasic(Object... args) throws Throwable;
 545 
 546     /**
 547      * Private method for trusted invocation of a MemberName of kind {@code REF_invokeVirtual}.
 548      * The caller signature is restricted to basic types as with {@code invokeBasic}.
 549      * The trailing (not leading) argument must be a MemberName.
 550      * @param args the signature-polymorphic parameter list, statically represented using varargs
 551      * @return the signature-polymorphic result, statically represented using {@code Object}
 552      */
 553     @HotSpotIntrinsicCandidate
 554     /*non-public*/ static native @PolymorphicSignature Object linkToVirtual(Object... args) throws Throwable;
 555 
 556     /**
 557      * Private method for trusted invocation of a MemberName of kind {@code REF_invokeStatic}.
 558      * The caller signature is restricted to basic types as with {@code invokeBasic}.
 559      * The trailing (not leading) argument must be a MemberName.
 560      * @param args the signature-polymorphic parameter list, statically represented using varargs
 561      * @return the signature-polymorphic result, statically represented using {@code Object}
 562      */
 563     @HotSpotIntrinsicCandidate
 564     /*non-public*/ static native @PolymorphicSignature Object linkToStatic(Object... args) throws Throwable;
 565 
 566     /**
 567      * Private method for trusted invocation of a MemberName of kind {@code REF_invokeSpecial}.
 568      * The caller signature is restricted to basic types as with {@code invokeBasic}.
 569      * The trailing (not leading) argument must be a MemberName.
 570      * @param args the signature-polymorphic parameter list, statically represented using varargs
 571      * @return the signature-polymorphic result, statically represented using {@code Object}
 572      */
 573     @HotSpotIntrinsicCandidate
 574     /*non-public*/ static native @PolymorphicSignature Object linkToSpecial(Object... args) throws Throwable;
 575 
 576     /**
 577      * Private method for trusted invocation of a MemberName of kind {@code REF_invokeInterface}.
 578      * The caller signature is restricted to basic types as with {@code invokeBasic}.
 579      * The trailing (not leading) argument must be a MemberName.
 580      * @param args the signature-polymorphic parameter list, statically represented using varargs
 581      * @return the signature-polymorphic result, statically represented using {@code Object}
 582      */
 583     @HotSpotIntrinsicCandidate
 584     /*non-public*/ static native @PolymorphicSignature Object linkToInterface(Object... args) throws Throwable;
 585 
 586     /**
 587      * Performs a variable arity invocation, passing the arguments in the given array
 588      * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
 589      * which mentions only the type {@code Object}, and whose actual argument count is the length
 590      * of the argument array.
 591      * <p>
 592      * Specifically, execution proceeds as if by the following steps,
 593      * although the methods are not guaranteed to be called if the JVM
 594      * can predict their effects.
 595      * <ul>
 596      * <li>Determine the length of the argument array as {@code N}.
 597      *     For a null reference, {@code N=0}. </li>
 598      * <li>Collect the {@code N} elements of the array as a logical
 599      *     argument list, each argument statically typed as an {@code Object}. </li>
 600      * <li>Determine, as {@code M}, the parameter count of the type of this
 601      *     method handle. </li>
 602      * <li>Determine the general type {@code TN} of {@code N} arguments or
 603      *     {@code M} arguments, if smaller than {@code N}, as
 604      *     {@code TN=MethodType.genericMethodType(Math.min(N, M))}.</li>
 605      * <li>If {@code N} is greater than {@code M}, perform the following
 606      *     checks and actions to shorten the logical argument list: <ul>
 607      *     <li>Check that this method handle has variable arity with a
 608      *         {@linkplain MethodType#lastParameterType trailing parameter}
 609      *         of some array type {@code A[]}.  If not, fail with a
 610      *         {@code WrongMethodTypeException}. </li>
 611      *     <li>Collect the trailing elements (there are {@code N-M+1} of them)
 612      *         from the logical argument list into a single array of
 613      *         type {@code A[]}, using {@code asType} conversions to
 614      *         convert each trailing argument to type {@code A}. </li>
 615      *     <li>If any of these conversions proves impossible, fail with either
 616      *         a {@code ClassCastException} if any trailing element cannot be
 617      *         cast to {@code A} or a {@code NullPointerException} if any
 618      *         trailing element is {@code null} and {@code A} is not a reference
 619      *         type. </li>
 620      *     <li>Replace the logical arguments gathered into the array of
 621      *         type {@code A[]} with the array itself, thus shortening
 622      *         the argument list to length {@code M}. This final argument
 623      *         retains the static type {@code A[]}.</li>
 624      *     <li>Adjust the type {@code TN} by changing the {@code N}th
 625      *         parameter type from {@code Object} to {@code A[]}.
 626      *     </ul>
 627      * <li>Force the original target method handle {@code MH0} to the
 628      *     required type, as {@code MH1 = MH0.asType(TN)}. </li>
 629      * <li>Spread the argument list into {@code N} separate arguments {@code A0, ...}. </li>
 630      * <li>Invoke the type-adjusted method handle on the unpacked arguments:
 631      *     MH1.invokeExact(A0, ...). </li>
 632      * <li>Take the return value as an {@code Object} reference. </li>
 633      * </ul>
 634      * <p>
 635      * If the target method handle has variable arity, and the argument list is longer
 636      * than that arity, the excess arguments, starting at the position of the trailing
 637      * array argument, will be gathered (if possible, as if by {@code asType} conversions)
 638      * into an array of the appropriate type, and invocation will proceed on the
 639      * shortened argument list.
 640      * In this way, <em>jumbo argument lists</em> which would spread into more
 641      * than 254 slots can still be processed uniformly.
 642      * <p>
 643      * Unlike the {@link #invoke(Object...) generic} invocation mode, which can
 644      * "recycle" an array argument, passing it directly to the target method,
 645      * this invocation mode <em>always</em> creates a new array parameter, even
 646      * if the original array passed to {@code invokeWithArguments} would have
 647      * been acceptable as a direct argument to the target method.
 648      * Even if the number {@code M} of actual arguments is the arity {@code N},
 649      * and the last argument is dynamically a suitable array of type {@code A[]},
 650      * it will still be boxed into a new one-element array, since the call
 651      * site statically types the argument as {@code Object}, not an array type.
 652      * This is not a special rule for this method, but rather a regular effect
 653      * of the {@linkplain #asVarargsCollector rules for variable-arity invocation}.
 654      * <p>
 655      * Because of the action of the {@code asType} step, the following argument
 656      * conversions are applied as necessary:
 657      * <ul>
 658      * <li>reference casting
 659      * <li>unboxing
 660      * <li>widening primitive conversions
 661      * <li>variable arity conversion
 662      * </ul>
 663      * <p>
 664      * The result returned by the call is boxed if it is a primitive,
 665      * or forced to null if the return type is void.
 666      * <p>
 667      * Unlike the signature polymorphic methods {@code invokeExact} and {@code invoke},
 668      * {@code invokeWithArguments} can be accessed normally via the Core Reflection API and JNI.
 669      * It can therefore be used as a bridge between native or reflective code and method handles.
 670      * @apiNote
 671      * This call is approximately equivalent to the following code:
 672      * <blockquote><pre>{@code
 673      * // for jumbo argument lists, adapt varargs explicitly:
 674      * int N = (arguments == null? 0: arguments.length);
 675      * int M = this.type.parameterCount();
 676      * int MAX_SAFE = 127;  // 127 longs require 254 slots, which is OK
 677      * if (N > MAX_SAFE && N > M && this.isVarargsCollector()) {
 678      *   Class<?> arrayType = this.type().lastParameterType();
 679      *   Class<?> elemType = arrayType.getComponentType();
 680      *   if (elemType != null) {
 681      *     Object args2 = Array.newInstance(elemType, M);
 682      *     MethodHandle arraySetter = MethodHandles.arrayElementSetter(arrayType);
 683      *     for (int i = 0; i < M; i++) {
 684      *       arraySetter.invoke(args2, i, arguments[M-1 + i]);
 685      *     }
 686      *     arguments = Arrays.copyOf(arguments, M);
 687      *     arguments[M-1] = args2;
 688      *     return this.asFixedArity().invokeWithArguments(arguments);
 689      *   }
 690      * } // done with explicit varargs processing
 691      *
 692      * // Handle fixed arity and non-jumbo variable arity invocation.
 693      * MethodHandle invoker = MethodHandles.spreadInvoker(this.type(), 0);
 694      * Object result = invoker.invokeExact(this, arguments);
 695      * }</pre></blockquote>
 696      *
 697      * @param arguments the arguments to pass to the target
 698      * @return the result returned by the target
 699      * @throws ClassCastException if an argument cannot be converted by reference casting
 700      * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
 701      * @throws Throwable anything thrown by the target method invocation
 702      * @see MethodHandles#spreadInvoker
 703      */
 704     public Object invokeWithArguments(Object... arguments) throws Throwable {
 705         // Note: Jumbo argument lists are handled in the variable-arity subclass.
 706         MethodType invocationType = MethodType.genericMethodType(arguments == null ? 0 : arguments.length);
 707         return invocationType.invokers().spreadInvoker(0).invokeExact(asType(invocationType), arguments);
 708     }
 709 
 710     /**
 711      * Performs a variable arity invocation, passing the arguments in the given list
 712      * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
 713      * which mentions only the type {@code Object}, and whose actual argument count is the length
 714      * of the argument list.
 715      * <p>
 716      * This method is also equivalent to the following code:
 717      * <blockquote><pre>{@code
 718      *   invokeWithArguments(arguments.toArray())
 719      * }</pre></blockquote>
 720      * <p>
 721      * Jumbo-sized lists are acceptable if this method handle has variable arity.
 722      * See {@link #invokeWithArguments(Object[])} for details.
 723      *
 724      * @param arguments the arguments to pass to the target
 725      * @return the result returned by the target
 726      * @throws NullPointerException if {@code arguments} is a null reference
 727      * @throws ClassCastException if an argument cannot be converted by reference casting
 728      * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
 729      * @throws Throwable anything thrown by the target method invocation
 730      */
 731     public Object invokeWithArguments(java.util.List<?> arguments) throws Throwable {
 732         return invokeWithArguments(arguments.toArray());
 733     }
 734 
 735     /**
 736      * Produces an adapter method handle which adapts the type of the
 737      * current method handle to a new type.
 738      * The resulting method handle is guaranteed to report a type
 739      * which is equal to the desired new type.
 740      * <p>
 741      * If the original type and new type are equal, returns {@code this}.
 742      * <p>
 743      * The new method handle, when invoked, will perform the following
 744      * steps:
 745      * <ul>
 746      * <li>Convert the incoming argument list to match the original
 747      *     method handle's argument list.
 748      * <li>Invoke the original method handle on the converted argument list.
 749      * <li>Convert any result returned by the original method handle
 750      *     to the return type of new method handle.
 751      * </ul>
 752      * <p>
 753      * This method provides the crucial behavioral difference between
 754      * {@link #invokeExact invokeExact} and plain, inexact {@link #invoke invoke}.
 755      * The two methods
 756      * perform the same steps when the caller's type descriptor exactly matches
 757      * the callee's, but when the types differ, plain {@link #invoke invoke}
 758      * also calls {@code asType} (or some internal equivalent) in order
 759      * to match up the caller's and callee's types.
 760      * <p>
 761      * If the current method is a variable arity method handle
 762      * argument list conversion may involve the conversion and collection
 763      * of several arguments into an array, as
 764      * {@linkplain #asVarargsCollector described elsewhere}.
 765      * In every other case, all conversions are applied <em>pairwise</em>,
 766      * which means that each argument or return value is converted to
 767      * exactly one argument or return value (or no return value).
 768      * The applied conversions are defined by consulting
 769      * the corresponding component types of the old and new
 770      * method handle types.
 771      * <p>
 772      * Let <em>T0</em> and <em>T1</em> be corresponding new and old parameter types,
 773      * or old and new return types.  Specifically, for some valid index {@code i}, let
 774      * <em>T0</em>{@code =newType.parameterType(i)} and <em>T1</em>{@code =this.type().parameterType(i)}.
 775      * Or else, going the other way for return values, let
 776      * <em>T0</em>{@code =this.type().returnType()} and <em>T1</em>{@code =newType.returnType()}.
 777      * If the types are the same, the new method handle makes no change
 778      * to the corresponding argument or return value (if any).
 779      * Otherwise, one of the following conversions is applied
 780      * if possible:
 781      * <ul>
 782      * <li>If <em>T0</em> and <em>T1</em> are references, then a cast to <em>T1</em> is applied.
 783      *     (The types do not need to be related in any particular way.
 784      *     This is because a dynamic value of null can convert to any reference type.)
 785      * <li>If <em>T0</em> and <em>T1</em> are primitives, then a Java method invocation
 786      *     conversion (JLS 5.3) is applied, if one exists.
 787      *     (Specifically, <em>T0</em> must convert to <em>T1</em> by a widening primitive conversion.)
 788      * <li>If <em>T0</em> is a primitive and <em>T1</em> a reference,
 789      *     a Java casting conversion (JLS 5.5) is applied if one exists.
 790      *     (Specifically, the value is boxed from <em>T0</em> to its wrapper class,
 791      *     which is then widened as needed to <em>T1</em>.)
 792      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
 793      *     conversion will be applied at runtime, possibly followed
 794      *     by a Java method invocation conversion (JLS 5.3)
 795      *     on the primitive value.  (These are the primitive widening conversions.)
 796      *     <em>T0</em> must be a wrapper class or a supertype of one.
 797      *     (In the case where <em>T0</em> is Object, these are the conversions
 798      *     allowed by {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.)
 799      *     The unboxing conversion must have a possibility of success, which means that
 800      *     if <em>T0</em> is not itself a wrapper class, there must exist at least one
 801      *     wrapper class <em>TW</em> which is a subtype of <em>T0</em> and whose unboxed
 802      *     primitive value can be widened to <em>T1</em>.
 803      * <li>If the return type <em>T1</em> is marked as void, any returned value is discarded
 804      * <li>If the return type <em>T0</em> is void and <em>T1</em> a reference, a null value is introduced.
 805      * <li>If the return type <em>T0</em> is void and <em>T1</em> a primitive,
 806      *     a zero value is introduced.
 807      * </ul>
 808      * (<em>Note:</em> Both <em>T0</em> and <em>T1</em> may be regarded as static types,
 809      * because neither corresponds specifically to the <em>dynamic type</em> of any
 810      * actual argument or return value.)
 811      * <p>
 812      * The method handle conversion cannot be made if any one of the required
 813      * pairwise conversions cannot be made.
 814      * <p>
 815      * At runtime, the conversions applied to reference arguments
 816      * or return values may require additional runtime checks which can fail.
 817      * An unboxing operation may fail because the original reference is null,
 818      * causing a {@link java.lang.NullPointerException NullPointerException}.
 819      * An unboxing operation or a reference cast may also fail on a reference
 820      * to an object of the wrong type,
 821      * causing a {@link java.lang.ClassCastException ClassCastException}.
 822      * Although an unboxing operation may accept several kinds of wrappers,
 823      * if none are available, a {@code ClassCastException} will be thrown.
 824      *
 825      * @param newType the expected type of the new method handle
 826      * @return a method handle which delegates to {@code this} after performing
 827      *           any necessary argument conversions, and arranges for any
 828      *           necessary return value conversions
 829      * @throws NullPointerException if {@code newType} is a null reference
 830      * @throws WrongMethodTypeException if the conversion cannot be made
 831      * @see MethodHandles#explicitCastArguments
 832      */
 833     public MethodHandle asType(MethodType newType) {
 834         // Fast path alternative to a heavyweight {@code asType} call.
 835         // Return 'this' if the conversion will be a no-op.
 836         if (newType == type) {
 837             return this;
 838         }
 839         // Return 'this.asTypeCache' if the conversion is already memoized.
 840         MethodHandle atc = asTypeCached(newType);
 841         if (atc != null) {
 842             return atc;
 843         }
 844         return asTypeUncached(newType);
 845     }
 846 
 847     private MethodHandle asTypeCached(MethodType newType) {
 848         MethodHandle atc = asTypeCache;
 849         if (atc != null && newType == atc.type) {
 850             return atc;
 851         }
 852         return null;
 853     }
 854 
 855     /** Override this to change asType behavior. */
 856     /*non-public*/ MethodHandle asTypeUncached(MethodType newType) {
 857         if (!type.isConvertibleTo(newType))
 858             throw new WrongMethodTypeException("cannot convert "+this+" to "+newType);
 859         return asTypeCache = MethodHandleImpl.makePairwiseConvert(this, newType, true);
 860     }
 861 
 862     /**
 863      * Makes an <em>array-spreading</em> method handle, which accepts a trailing array argument
 864      * and spreads its elements as positional arguments.
 865      * The new method handle adapts, as its <i>target</i>,
 866      * the current method handle.  The type of the adapter will be
 867      * the same as the type of the target, except that the final
 868      * {@code arrayLength} parameters of the target's type are replaced
 869      * by a single array parameter of type {@code arrayType}.
 870      * <p>
 871      * If the array element type differs from any of the corresponding
 872      * argument types on the original target,
 873      * the original target is adapted to take the array elements directly,
 874      * as if by a call to {@link #asType asType}.
 875      * <p>
 876      * When called, the adapter replaces a trailing array argument
 877      * by the array's elements, each as its own argument to the target.
 878      * (The order of the arguments is preserved.)
 879      * They are converted pairwise by casting and/or unboxing
 880      * to the types of the trailing parameters of the target.
 881      * Finally the target is called.
 882      * What the target eventually returns is returned unchanged by the adapter.
 883      * <p>
 884      * Before calling the target, the adapter verifies that the array
 885      * contains exactly enough elements to provide a correct argument count
 886      * to the target method handle.
 887      * (The array may also be null when zero elements are required.)
 888      * <p>
 889      * When the adapter is called, the length of the supplied {@code array}
 890      * argument is queried as if by {@code array.length} or {@code arraylength}
 891      * bytecode. If the adapter accepts a zero-length trailing array argument,
 892      * the supplied {@code array} argument can either be a zero-length array or
 893      * {@code null}; otherwise, the adapter will throw a {@code NullPointerException}
 894      * if the array is {@code null} and throw an {@link IllegalArgumentException}
 895      * if the array does not have the correct number of elements.
 896      * <p>
 897      * Here are some simple examples of array-spreading method handles:
 898      * <blockquote><pre>{@code
 899 MethodHandle equals = publicLookup()
 900   .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
 901 assert( (boolean) equals.invokeExact("me", (Object)"me"));
 902 assert(!(boolean) equals.invokeExact("me", (Object)"thee"));
 903 // spread both arguments from a 2-array:
 904 MethodHandle eq2 = equals.asSpreader(Object[].class, 2);
 905 assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" }));
 906 assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
 907 // try to spread from anything but a 2-array:
 908 for (int n = 0; n <= 10; n++) {
 909   Object[] badArityArgs = (n == 2 ? new Object[0] : new Object[n]);
 910   try { assert((boolean) eq2.invokeExact(badArityArgs) && false); }
 911   catch (IllegalArgumentException ex) { } // OK
 912 }
 913 // spread both arguments from a String array:
 914 MethodHandle eq2s = equals.asSpreader(String[].class, 2);
 915 assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" }));
 916 assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" }));
 917 // spread second arguments from a 1-array:
 918 MethodHandle eq1 = equals.asSpreader(Object[].class, 1);
 919 assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" }));
 920 assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" }));
 921 // spread no arguments from a 0-array or null:
 922 MethodHandle eq0 = equals.asSpreader(Object[].class, 0);
 923 assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0]));
 924 assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null));
 925 // asSpreader and asCollector are approximate inverses:
 926 for (int n = 0; n <= 2; n++) {
 927     for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) {
 928         MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n);
 929         assert( (boolean) equals2.invokeWithArguments("me", "me"));
 930         assert(!(boolean) equals2.invokeWithArguments("me", "thee"));
 931     }
 932 }
 933 MethodHandle caToString = publicLookup()
 934   .findStatic(Arrays.class, "toString", methodType(String.class, char[].class));
 935 assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray()));
 936 MethodHandle caString3 = caToString.asCollector(char[].class, 3);
 937 assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
 938 MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
 939 assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
 940      * }</pre></blockquote>
 941      * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments
 942      * @param arrayLength the number of arguments to spread from an incoming array argument
 943      * @return a new method handle which spreads its final array argument,
 944      *         before calling the original method handle
 945      * @throws NullPointerException if {@code arrayType} is a null reference
 946      * @throws IllegalArgumentException if {@code arrayType} is not an array type,
 947      *         or if target does not have at least
 948      *         {@code arrayLength} parameter types,
 949      *         or if {@code arrayLength} is negative,
 950      *         or if the resulting method handle's type would have
 951      *         <a href="MethodHandle.html#maxarity">too many parameters</a>
 952      * @throws WrongMethodTypeException if the implied {@code asType} call fails
 953      * @see #asCollector
 954      */
 955     public MethodHandle asSpreader(Class<?> arrayType, int arrayLength) {
 956         return asSpreader(type().parameterCount() - arrayLength, arrayType, arrayLength);
 957     }
 958 
 959     /**
 960      * Makes an <em>array-spreading</em> method handle, which accepts an array argument at a given position and spreads
 961      * its elements as positional arguments in place of the array. The new method handle adapts, as its <i>target</i>,
 962      * the current method handle. The type of the adapter will be the same as the type of the target, except that the
 963      * {@code arrayLength} parameters of the target's type, starting at the zero-based position {@code spreadArgPos},
 964      * are replaced by a single array parameter of type {@code arrayType}.
 965      * <p>
 966      * This method behaves very much like {@link #asSpreader(Class, int)}, but accepts an additional {@code spreadArgPos}
 967      * argument to indicate at which position in the parameter list the spreading should take place.
 968      *
 969      * @apiNote Example:
 970      * <blockquote><pre>{@code
 971     MethodHandle compare = LOOKUP.findStatic(Objects.class, "compare", methodType(int.class, Object.class, Object.class, Comparator.class));
 972     MethodHandle compare2FromArray = compare.asSpreader(0, Object[].class, 2);
 973     Object[] ints = new Object[]{3, 9, 7, 7};
 974     Comparator<Integer> cmp = (a, b) -> a - b;
 975     assertTrue((int) compare2FromArray.invoke(Arrays.copyOfRange(ints, 0, 2), cmp) < 0);
 976     assertTrue((int) compare2FromArray.invoke(Arrays.copyOfRange(ints, 1, 3), cmp) > 0);
 977     assertTrue((int) compare2FromArray.invoke(Arrays.copyOfRange(ints, 2, 4), cmp) == 0);
 978      * }</pre></blockquote>
 979      * @param spreadArgPos the position (zero-based index) in the argument list at which spreading should start.
 980      * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments
 981      * @param arrayLength the number of arguments to spread from an incoming array argument
 982      * @return a new method handle which spreads an array argument at a given position,
 983      *         before calling the original method handle
 984      * @throws NullPointerException if {@code arrayType} is a null reference
 985      * @throws IllegalArgumentException if {@code arrayType} is not an array type,
 986      *         or if target does not have at least
 987      *         {@code arrayLength} parameter types,
 988      *         or if {@code arrayLength} is negative,
 989      *         or if {@code spreadArgPos} has an illegal value (negative, or together with arrayLength exceeding the
 990      *         number of arguments),
 991      *         or if the resulting method handle's type would have
 992      *         <a href="MethodHandle.html#maxarity">too many parameters</a>
 993      * @throws WrongMethodTypeException if the implied {@code asType} call fails
 994      *
 995      * @see #asSpreader(Class, int)
 996      * @since 9
 997      */
 998     public MethodHandle asSpreader(int spreadArgPos, Class<?> arrayType, int arrayLength) {
 999         MethodType postSpreadType = asSpreaderChecks(arrayType, spreadArgPos, arrayLength);
1000         MethodHandle afterSpread = this.asType(postSpreadType);
1001         BoundMethodHandle mh = afterSpread.rebind();
1002         LambdaForm lform = mh.editor().spreadArgumentsForm(1 + spreadArgPos, arrayType, arrayLength);
1003         MethodType preSpreadType = postSpreadType.replaceParameterTypes(spreadArgPos, spreadArgPos + arrayLength, arrayType);
1004         return mh.copyWith(preSpreadType, lform);
1005     }
1006 
1007     /**
1008      * See if {@code asSpreader} can be validly called with the given arguments.
1009      * Return the type of the method handle call after spreading but before conversions.
1010      */
1011     private MethodType asSpreaderChecks(Class<?> arrayType, int pos, int arrayLength) {
1012         spreadArrayChecks(arrayType, arrayLength);
1013         int nargs = type().parameterCount();
1014         if (nargs < arrayLength || arrayLength < 0)
1015             throw newIllegalArgumentException("bad spread array length");
1016         if (pos < 0 || pos + arrayLength > nargs) {
1017             throw newIllegalArgumentException("bad spread position");
1018         }
1019         Class<?> arrayElement = arrayType.getComponentType();
1020         MethodType mtype = type();
1021         boolean match = true, fail = false;
1022         for (int i = pos; i < pos + arrayLength; i++) {
1023             Class<?> ptype = mtype.parameterType(i);
1024             if (ptype != arrayElement) {
1025                 match = false;
1026                 if (!MethodType.canConvert(arrayElement, ptype)) {
1027                     fail = true;
1028                     break;
1029                 }
1030             }
1031         }
1032         if (match)  return mtype;
1033         MethodType needType = mtype.asSpreaderType(arrayType, pos, arrayLength);
1034         if (!fail)  return needType;
1035         // elicit an error:
1036         this.asType(needType);
1037         throw newInternalError("should not return");
1038     }
1039 
1040     private void spreadArrayChecks(Class<?> arrayType, int arrayLength) {
1041         Class<?> arrayElement = arrayType.getComponentType();
1042         if (arrayElement == null)
1043             throw newIllegalArgumentException("not an array type", arrayType);
1044         if ((arrayLength & 0x7F) != arrayLength) {
1045             if ((arrayLength & 0xFF) != arrayLength)
1046                 throw newIllegalArgumentException("array length is not legal", arrayLength);
1047             assert(arrayLength >= 128);
1048             if (arrayElement == long.class ||
1049                 arrayElement == double.class)
1050                 throw newIllegalArgumentException("array length is not legal for long[] or double[]", arrayLength);
1051         }
1052     }
1053     /**
1054       * Adapts this method handle to be {@linkplain #asVarargsCollector variable arity}
1055       * if the boolean flag is true, else {@linkplain #asFixedArity fixed arity}.
1056       * If the method handle is already of the proper arity mode, it is returned
1057       * unchanged.
1058       * @apiNote
1059       * <p>This method is sometimes useful when adapting a method handle that
1060       * may be variable arity, to ensure that the resulting adapter is also
1061       * variable arity if and only if the original handle was.  For example,
1062       * this code changes the first argument of a handle {@code mh} to {@code int} without
1063       * disturbing its variable arity property:
1064       * {@code mh.asType(mh.type().changeParameterType(0,int.class))
1065       *     .withVarargs(mh.isVarargsCollector())}
1066       * <p>
1067       * This call is approximately equivalent to the following code:
1068       * <blockquote><pre>{@code
1069       * if (makeVarargs == isVarargsCollector())
1070       *   return this;
1071       * else if (makeVarargs)
1072       *   return asVarargsCollector(type().lastParameterType());
1073       * else
1074       *   return return asFixedArity();
1075       * }</pre></blockquote>
1076       * @param makeVarargs true if the return method handle should have variable arity behavior
1077       * @return a method handle of the same type, with possibly adjusted variable arity behavior
1078       * @throws IllegalArgumentException if {@code makeVarargs} is true and
1079       *         this method handle does not have a trailing array parameter
1080       * @since 9
1081       * @see #asVarargsCollector
1082       * @see #asFixedArity
1083      */
1084     public MethodHandle withVarargs(boolean makeVarargs) {
1085         assert(!isVarargsCollector());  // subclass responsibility
1086         if (makeVarargs) {
1087            return asVarargsCollector(type().lastParameterType());
1088         } else {
1089             return this;
1090         }
1091     }
1092 
1093     /**
1094      * Makes an <em>array-collecting</em> method handle, which accepts a given number of trailing
1095      * positional arguments and collects them into an array argument.
1096      * The new method handle adapts, as its <i>target</i>,
1097      * the current method handle.  The type of the adapter will be
1098      * the same as the type of the target, except that a single trailing
1099      * parameter (usually of type {@code arrayType}) is replaced by
1100      * {@code arrayLength} parameters whose type is element type of {@code arrayType}.
1101      * <p>
1102      * If the array type differs from the final argument type on the original target,
1103      * the original target is adapted to take the array type directly,
1104      * as if by a call to {@link #asType asType}.
1105      * <p>
1106      * When called, the adapter replaces its trailing {@code arrayLength}
1107      * arguments by a single new array of type {@code arrayType}, whose elements
1108      * comprise (in order) the replaced arguments.
1109      * Finally the target is called.
1110      * What the target eventually returns is returned unchanged by the adapter.
1111      * <p>
1112      * (The array may also be a shared constant when {@code arrayLength} is zero.)
1113      * <p>
1114      * (<em>Note:</em> The {@code arrayType} is often identical to the
1115      * {@linkplain MethodType#lastParameterType last parameter type}
1116      * of the original target.
1117      * It is an explicit argument for symmetry with {@code asSpreader}, and also
1118      * to allow the target to use a simple {@code Object} as its last parameter type.)
1119      * <p>
1120      * In order to create a collecting adapter which is not restricted to a particular
1121      * number of collected arguments, use {@link #asVarargsCollector asVarargsCollector}
1122      * or {@link #withVarargs withVarargs} instead.
1123      * <p>
1124      * Here are some examples of array-collecting method handles:
1125      * <blockquote><pre>{@code
1126 MethodHandle deepToString = publicLookup()
1127   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
1128 assertEquals("[won]",   (String) deepToString.invokeExact(new Object[]{"won"}));
1129 MethodHandle ts1 = deepToString.asCollector(Object[].class, 1);
1130 assertEquals(methodType(String.class, Object.class), ts1.type());
1131 //assertEquals("[won]", (String) ts1.invokeExact(         new Object[]{"won"})); //FAIL
1132 assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"}));
1133 // arrayType can be a subtype of Object[]
1134 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
1135 assertEquals(methodType(String.class, String.class, String.class), ts2.type());
1136 assertEquals("[two, too]", (String) ts2.invokeExact("two", "too"));
1137 MethodHandle ts0 = deepToString.asCollector(Object[].class, 0);
1138 assertEquals("[]", (String) ts0.invokeExact());
1139 // collectors can be nested, Lisp-style
1140 MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2);
1141 assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D")));
1142 // arrayType can be any primitive array type
1143 MethodHandle bytesToString = publicLookup()
1144   .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class))
1145   .asCollector(byte[].class, 3);
1146 assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3));
1147 MethodHandle longsToString = publicLookup()
1148   .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
1149   .asCollector(long[].class, 1);
1150 assertEquals("[123]", (String) longsToString.invokeExact((long)123));
1151      * }</pre></blockquote>
1152      * <p>
1153      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
1154      * variable-arity method handle}, even if the original target method handle was.
1155      * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
1156      * @param arrayLength the number of arguments to collect into a new array argument
1157      * @return a new method handle which collects some trailing argument
1158      *         into an array, before calling the original method handle
1159      * @throws NullPointerException if {@code arrayType} is a null reference
1160      * @throws IllegalArgumentException if {@code arrayType} is not an array type
1161      *         or {@code arrayType} is not assignable to this method handle's trailing parameter type,
1162      *         or {@code arrayLength} is not a legal array size,
1163      *         or the resulting method handle's type would have
1164      *         <a href="MethodHandle.html#maxarity">too many parameters</a>
1165      * @throws WrongMethodTypeException if the implied {@code asType} call fails
1166      * @see #asSpreader
1167      * @see #asVarargsCollector
1168      */
1169     public MethodHandle asCollector(Class<?> arrayType, int arrayLength) {
1170         return asCollector(type().parameterCount() - 1, arrayType, arrayLength);
1171     }
1172 
1173     /**
1174      * Makes an <em>array-collecting</em> method handle, which accepts a given number of positional arguments starting
1175      * at a given position, and collects them into an array argument. The new method handle adapts, as its
1176      * <i>target</i>, the current method handle. The type of the adapter will be the same as the type of the target,
1177      * except that the parameter at the position indicated by {@code collectArgPos} (usually of type {@code arrayType})
1178      * is replaced by {@code arrayLength} parameters whose type is element type of {@code arrayType}.
1179      * <p>
1180      * This method behaves very much like {@link #asCollector(Class, int)}, but differs in that its {@code
1181      * collectArgPos} argument indicates at which position in the parameter list arguments should be collected. This
1182      * index is zero-based.
1183      *
1184      * @apiNote Examples:
1185      * <blockquote><pre>{@code
1186     StringWriter swr = new StringWriter();
1187     MethodHandle swWrite = LOOKUP.findVirtual(StringWriter.class, "write", methodType(void.class, char[].class, int.class, int.class)).bindTo(swr);
1188     MethodHandle swWrite4 = swWrite.asCollector(0, char[].class, 4);
1189     swWrite4.invoke('A', 'B', 'C', 'D', 1, 2);
1190     assertEquals("BC", swr.toString());
1191     swWrite4.invoke('P', 'Q', 'R', 'S', 0, 4);
1192     assertEquals("BCPQRS", swr.toString());
1193     swWrite4.invoke('W', 'X', 'Y', 'Z', 3, 1);
1194     assertEquals("BCPQRSZ", swr.toString());
1195      * }</pre></blockquote>
1196      * <p>
1197      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
1198      * variable-arity method handle}, even if the original target method handle was.
1199      * @param collectArgPos the zero-based position in the parameter list at which to start collecting.
1200      * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
1201      * @param arrayLength the number of arguments to collect into a new array argument
1202      * @return a new method handle which collects some arguments
1203      *         into an array, before calling the original method handle
1204      * @throws NullPointerException if {@code arrayType} is a null reference
1205      * @throws IllegalArgumentException if {@code arrayType} is not an array type
1206      *         or {@code arrayType} is not assignable to this method handle's array parameter type,
1207      *         or {@code arrayLength} is not a legal array size,
1208      *         or {@code collectArgPos} has an illegal value (negative, or greater than the number of arguments),
1209      *         or the resulting method handle's type would have
1210      *         <a href="MethodHandle.html#maxarity">too many parameters</a>
1211      * @throws WrongMethodTypeException if the implied {@code asType} call fails
1212      *
1213      * @see #asCollector(Class, int)
1214      * @since 9
1215      */
1216     public MethodHandle asCollector(int collectArgPos, Class<?> arrayType, int arrayLength) {
1217         asCollectorChecks(arrayType, collectArgPos, arrayLength);
1218         BoundMethodHandle mh = rebind();
1219         MethodType resultType = type().asCollectorType(arrayType, collectArgPos, arrayLength);
1220         MethodHandle newArray = MethodHandleImpl.varargsArray(arrayType, arrayLength);
1221         LambdaForm lform = mh.editor().collectArgumentArrayForm(1 + collectArgPos, newArray);
1222         if (lform != null) {
1223             return mh.copyWith(resultType, lform);
1224         }
1225         lform = mh.editor().collectArgumentsForm(1 + collectArgPos, newArray.type().basicType());
1226         return mh.copyWithExtendL(resultType, lform, newArray);
1227     }
1228 
1229     /**
1230      * See if {@code asCollector} can be validly called with the given arguments.
1231      * Return false if the last parameter is not an exact match to arrayType.
1232      */
1233     /*non-public*/ boolean asCollectorChecks(Class<?> arrayType, int pos, int arrayLength) {
1234         spreadArrayChecks(arrayType, arrayLength);
1235         int nargs = type().parameterCount();
1236         if (pos < 0 || pos >= nargs) {
1237             throw newIllegalArgumentException("bad collect position");
1238         }
1239         if (nargs != 0) {
1240             Class<?> param = type().parameterType(pos);
1241             if (param == arrayType)  return true;
1242             if (param.isAssignableFrom(arrayType))  return false;
1243         }
1244         throw newIllegalArgumentException("array type not assignable to argument", this, arrayType);
1245     }
1246 
1247     /**
1248      * Makes a <em>variable arity</em> adapter which is able to accept
1249      * any number of trailing positional arguments and collect them
1250      * into an array argument.
1251      * <p>
1252      * The type and behavior of the adapter will be the same as
1253      * the type and behavior of the target, except that certain
1254      * {@code invoke} and {@code asType} requests can lead to
1255      * trailing positional arguments being collected into target's
1256      * trailing parameter.
1257      * Also, the
1258      * {@linkplain MethodType#lastParameterType last parameter type}
1259      * of the adapter will be
1260      * {@code arrayType}, even if the target has a different
1261      * last parameter type.
1262      * <p>
1263      * This transformation may return {@code this} if the method handle is
1264      * already of variable arity and its trailing parameter type
1265      * is identical to {@code arrayType}.
1266      * <p>
1267      * When called with {@link #invokeExact invokeExact}, the adapter invokes
1268      * the target with no argument changes.
1269      * (<em>Note:</em> This behavior is different from a
1270      * {@linkplain #asCollector fixed arity collector},
1271      * since it accepts a whole array of indeterminate length,
1272      * rather than a fixed number of arguments.)
1273      * <p>
1274      * When called with plain, inexact {@link #invoke invoke}, if the caller
1275      * type is the same as the adapter, the adapter invokes the target as with
1276      * {@code invokeExact}.
1277      * (This is the normal behavior for {@code invoke} when types match.)
1278      * <p>
1279      * Otherwise, if the caller and adapter arity are the same, and the
1280      * trailing parameter type of the caller is a reference type identical to
1281      * or assignable to the trailing parameter type of the adapter,
1282      * the arguments and return values are converted pairwise,
1283      * as if by {@link #asType asType} on a fixed arity
1284      * method handle.
1285      * <p>
1286      * Otherwise, the arities differ, or the adapter's trailing parameter
1287      * type is not assignable from the corresponding caller type.
1288      * In this case, the adapter replaces all trailing arguments from
1289      * the original trailing argument position onward, by
1290      * a new array of type {@code arrayType}, whose elements
1291      * comprise (in order) the replaced arguments.
1292      * <p>
1293      * The caller type must provides as least enough arguments,
1294      * and of the correct type, to satisfy the target's requirement for
1295      * positional arguments before the trailing array argument.
1296      * Thus, the caller must supply, at a minimum, {@code N-1} arguments,
1297      * where {@code N} is the arity of the target.
1298      * Also, there must exist conversions from the incoming arguments
1299      * to the target's arguments.
1300      * As with other uses of plain {@code invoke}, if these basic
1301      * requirements are not fulfilled, a {@code WrongMethodTypeException}
1302      * may be thrown.
1303      * <p>
1304      * In all cases, what the target eventually returns is returned unchanged by the adapter.
1305      * <p>
1306      * In the final case, it is exactly as if the target method handle were
1307      * temporarily adapted with a {@linkplain #asCollector fixed arity collector}
1308      * to the arity required by the caller type.
1309      * (As with {@code asCollector}, if the array length is zero,
1310      * a shared constant may be used instead of a new array.
1311      * If the implied call to {@code asCollector} would throw
1312      * an {@code IllegalArgumentException} or {@code WrongMethodTypeException},
1313      * the call to the variable arity adapter must throw
1314      * {@code WrongMethodTypeException}.)
1315      * <p>
1316      * The behavior of {@link #asType asType} is also specialized for
1317      * variable arity adapters, to maintain the invariant that
1318      * plain, inexact {@code invoke} is always equivalent to an {@code asType}
1319      * call to adjust the target type, followed by {@code invokeExact}.
1320      * Therefore, a variable arity adapter responds
1321      * to an {@code asType} request by building a fixed arity collector,
1322      * if and only if the adapter and requested type differ either
1323      * in arity or trailing argument type.
1324      * The resulting fixed arity collector has its type further adjusted
1325      * (if necessary) to the requested type by pairwise conversion,
1326      * as if by another application of {@code asType}.
1327      * <p>
1328      * When a method handle is obtained by executing an {@code ldc} instruction
1329      * of a {@code CONSTANT_MethodHandle} constant, and the target method is marked
1330      * as a variable arity method (with the modifier bit {@code 0x0080}),
1331      * the method handle will accept multiple arities, as if the method handle
1332      * constant were created by means of a call to {@code asVarargsCollector}.
1333      * <p>
1334      * In order to create a collecting adapter which collects a predetermined
1335      * number of arguments, and whose type reflects this predetermined number,
1336      * use {@link #asCollector asCollector} instead.
1337      * <p>
1338      * No method handle transformations produce new method handles with
1339      * variable arity, unless they are documented as doing so.
1340      * Therefore, besides {@code asVarargsCollector} and {@code withVarargs},
1341      * all methods in {@code MethodHandle} and {@code MethodHandles}
1342      * will return a method handle with fixed arity,
1343      * except in the cases where they are specified to return their original
1344      * operand (e.g., {@code asType} of the method handle's own type).
1345      * <p>
1346      * Calling {@code asVarargsCollector} on a method handle which is already
1347      * of variable arity will produce a method handle with the same type and behavior.
1348      * It may (or may not) return the original variable arity method handle.
1349      * <p>
1350      * Here is an example, of a list-making variable arity method handle:
1351      * <blockquote><pre>{@code
1352 MethodHandle deepToString = publicLookup()
1353   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
1354 MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
1355 assertEquals("[won]",   (String) ts1.invokeExact(    new Object[]{"won"}));
1356 assertEquals("[won]",   (String) ts1.invoke(         new Object[]{"won"}));
1357 assertEquals("[won]",   (String) ts1.invoke(                      "won" ));
1358 assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"}));
1359 // findStatic of Arrays.asList(...) produces a variable arity method handle:
1360 MethodHandle asList = publicLookup()
1361   .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
1362 assertEquals(methodType(List.class, Object[].class), asList.type());
1363 assert(asList.isVarargsCollector());
1364 assertEquals("[]", asList.invoke().toString());
1365 assertEquals("[1]", asList.invoke(1).toString());
1366 assertEquals("[two, too]", asList.invoke("two", "too").toString());
1367 String[] argv = { "three", "thee", "tee" };
1368 assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
1369 assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString());
1370 List ls = (List) asList.invoke((Object)argv);
1371 assertEquals(1, ls.size());
1372 assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
1373      * }</pre></blockquote>
1374      * <p style="font-size:smaller;">
1375      * <em>Discussion:</em>
1376      * These rules are designed as a dynamically-typed variation
1377      * of the Java rules for variable arity methods.
1378      * In both cases, callers to a variable arity method or method handle
1379      * can either pass zero or more positional arguments, or else pass
1380      * pre-collected arrays of any length.  Users should be aware of the
1381      * special role of the final argument, and of the effect of a
1382      * type match on that final argument, which determines whether
1383      * or not a single trailing argument is interpreted as a whole
1384      * array or a single element of an array to be collected.
1385      * Note that the dynamic type of the trailing argument has no
1386      * effect on this decision, only a comparison between the symbolic
1387      * type descriptor of the call site and the type descriptor of the method handle.)
1388      *
1389      * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
1390      * @return a new method handle which can collect any number of trailing arguments
1391      *         into an array, before calling the original method handle
1392      * @throws NullPointerException if {@code arrayType} is a null reference
1393      * @throws IllegalArgumentException if {@code arrayType} is not an array type
1394      *         or {@code arrayType} is not assignable to this method handle's trailing parameter type
1395      * @see #asCollector
1396      * @see #isVarargsCollector
1397      * @see #withVarargs
1398      * @see #asFixedArity
1399      */
1400     public MethodHandle asVarargsCollector(Class<?> arrayType) {
1401         Objects.requireNonNull(arrayType);
1402         boolean lastMatch = asCollectorChecks(arrayType, type().parameterCount() - 1, 0);
1403         if (isVarargsCollector() && lastMatch)
1404             return this;
1405         return MethodHandleImpl.makeVarargsCollector(this, arrayType);
1406     }
1407 
1408     /**
1409      * Determines if this method handle
1410      * supports {@linkplain #asVarargsCollector variable arity} calls.
1411      * Such method handles arise from the following sources:
1412      * <ul>
1413      * <li>a call to {@linkplain #asVarargsCollector asVarargsCollector}
1414      * <li>a call to a {@linkplain java.lang.invoke.MethodHandles.Lookup lookup method}
1415      *     which resolves to a variable arity Java method or constructor
1416      * <li>an {@code ldc} instruction of a {@code CONSTANT_MethodHandle}
1417      *     which resolves to a variable arity Java method or constructor
1418      * </ul>
1419      * @return true if this method handle accepts more than one arity of plain, inexact {@code invoke} calls
1420      * @see #asVarargsCollector
1421      * @see #asFixedArity
1422      */
1423     public boolean isVarargsCollector() {
1424         return false;
1425     }
1426 
1427     /**
1428      * Makes a <em>fixed arity</em> method handle which is otherwise
1429      * equivalent to the current method handle.
1430      * <p>
1431      * If the current method handle is not of
1432      * {@linkplain #asVarargsCollector variable arity},
1433      * the current method handle is returned.
1434      * This is true even if the current method handle
1435      * could not be a valid input to {@code asVarargsCollector}.
1436      * <p>
1437      * Otherwise, the resulting fixed-arity method handle has the same
1438      * type and behavior of the current method handle,
1439      * except that {@link #isVarargsCollector isVarargsCollector}
1440      * will be false.
1441      * The fixed-arity method handle may (or may not) be the
1442      * a previous argument to {@code asVarargsCollector}.
1443      * <p>
1444      * Here is an example, of a list-making variable arity method handle:
1445      * <blockquote><pre>{@code
1446 MethodHandle asListVar = publicLookup()
1447   .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
1448   .asVarargsCollector(Object[].class);
1449 MethodHandle asListFix = asListVar.asFixedArity();
1450 assertEquals("[1]", asListVar.invoke(1).toString());
1451 Exception caught = null;
1452 try { asListFix.invoke((Object)1); }
1453 catch (Exception ex) { caught = ex; }
1454 assert(caught instanceof ClassCastException);
1455 assertEquals("[two, too]", asListVar.invoke("two", "too").toString());
1456 try { asListFix.invoke("two", "too"); }
1457 catch (Exception ex) { caught = ex; }
1458 assert(caught instanceof WrongMethodTypeException);
1459 Object[] argv = { "three", "thee", "tee" };
1460 assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString());
1461 assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
1462 assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
1463 assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
1464      * }</pre></blockquote>
1465      *
1466      * @return a new method handle which accepts only a fixed number of arguments
1467      * @see #asVarargsCollector
1468      * @see #isVarargsCollector
1469      * @see #withVarargs
1470      */
1471     public MethodHandle asFixedArity() {
1472         assert(!isVarargsCollector());
1473         return this;
1474     }
1475 
1476     /**
1477      * Binds a value {@code x} to the first argument of a method handle, without invoking it.
1478      * The new method handle adapts, as its <i>target</i>,
1479      * the current method handle by binding it to the given argument.
1480      * The type of the bound handle will be
1481      * the same as the type of the target, except that a single leading
1482      * reference parameter will be omitted.
1483      * <p>
1484      * When called, the bound handle inserts the given value {@code x}
1485      * as a new leading argument to the target.  The other arguments are
1486      * also passed unchanged.
1487      * What the target eventually returns is returned unchanged by the bound handle.
1488      * <p>
1489      * The reference {@code x} must be convertible to the first parameter
1490      * type of the target.
1491      * <p>
1492      * <em>Note:</em>  Because method handles are immutable, the target method handle
1493      * retains its original type and behavior.
1494      * <p>
1495      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
1496      * variable-arity method handle}, even if the original target method handle was.
1497      * @param x  the value to bind to the first argument of the target
1498      * @return a new method handle which prepends the given value to the incoming
1499      *         argument list, before calling the original method handle
1500      * @throws IllegalArgumentException if the target does not have a
1501      *         leading parameter type that is a reference type
1502      * @throws ClassCastException if {@code x} cannot be converted
1503      *         to the leading parameter type of the target
1504      * @see MethodHandles#insertArguments
1505      */
1506     public MethodHandle bindTo(Object x) {
1507         x = type.leadingReferenceParameter().cast(x);  // throw CCE if needed
1508         return bindArgumentL(0, x);
1509     }
1510 
1511     /**
1512      * Returns a string representation of the method handle,
1513      * starting with the string {@code "MethodHandle"} and
1514      * ending with the string representation of the method handle's type.
1515      * In other words, this method returns a string equal to the value of:
1516      * <blockquote><pre>{@code
1517      * "MethodHandle" + type().toString()
1518      * }</pre></blockquote>
1519      * <p>
1520      * (<em>Note:</em>  Future releases of this API may add further information
1521      * to the string representation.
1522      * Therefore, the present syntax should not be parsed by applications.)
1523      *
1524      * @return a string representation of the method handle
1525      */
1526     @Override
1527     public String toString() {
1528         if (DEBUG_METHOD_HANDLE_NAMES)  return "MethodHandle"+debugString();
1529         return standardString();
1530     }
1531     String standardString() {
1532         return "MethodHandle"+type;
1533     }
1534     /** Return a string with a several lines describing the method handle structure.
1535      *  This string would be suitable for display in an IDE debugger.
1536      */
1537     String debugString() {
1538         return type+" : "+internalForm()+internalProperties();
1539     }
1540 
1541     //// Implementation methods.
1542     //// Sub-classes can override these default implementations.
1543     //// All these methods assume arguments are already validated.
1544 
1545     // Other transforms to do:  convert, explicitCast, permute, drop, filter, fold, GWT, catch
1546 
1547     BoundMethodHandle bindArgumentL(int pos, Object value) {
1548         return rebind().bindArgumentL(pos, value);
1549     }
1550 
1551     /*non-public*/
1552     MethodHandle setVarargs(MemberName member) throws IllegalAccessException {
1553         if (!member.isVarargs())  return this;
1554         try {
1555             return this.withVarargs(true);
1556         } catch (IllegalArgumentException ex) {
1557             throw member.makeAccessException("cannot make variable arity", null);
1558         }
1559     }
1560 
1561     /*non-public*/
1562     MethodHandle viewAsType(MethodType newType, boolean strict) {
1563         // No actual conversions, just a new view of the same method.
1564         // Note that this operation must not produce a DirectMethodHandle,
1565         // because retyped DMHs, like any transformed MHs,
1566         // cannot be cracked into MethodHandleInfo.
1567         assert viewAsTypeChecks(newType, strict);
1568         BoundMethodHandle mh = rebind();
1569         return mh.copyWith(newType, mh.form);
1570     }
1571 
1572     /*non-public*/
1573     boolean viewAsTypeChecks(MethodType newType, boolean strict) {
1574         if (strict) {
1575             assert(type().isViewableAs(newType, true))
1576                 : Arrays.asList(this, newType);
1577         } else {
1578             assert(type().basicType().isViewableAs(newType.basicType(), true))
1579                 : Arrays.asList(this, newType);
1580         }
1581         return true;
1582     }
1583 
1584     // Decoding
1585 
1586     /*non-public*/
1587     LambdaForm internalForm() {
1588         return form;
1589     }
1590 
1591     /*non-public*/
1592     MemberName internalMemberName() {
1593         return null;  // DMH returns DMH.member
1594     }
1595 
1596     /*non-public*/
1597     Class<?> internalCallerClass() {
1598         return null;  // caller-bound MH for @CallerSensitive method returns caller
1599     }
1600 
1601     /*non-public*/
1602     MethodHandleImpl.Intrinsic intrinsicName() {
1603         // no special intrinsic meaning to most MHs
1604         return MethodHandleImpl.Intrinsic.NONE;
1605     }
1606 
1607     /*non-public*/
1608     MethodHandle withInternalMemberName(MemberName member, boolean isInvokeSpecial) {
1609         if (member != null) {
1610             return MethodHandleImpl.makeWrappedMember(this, member, isInvokeSpecial);
1611         } else if (internalMemberName() == null) {
1612             // The required internaMemberName is null, and this MH (like most) doesn't have one.
1613             return this;
1614         } else {
1615             // The following case is rare. Mask the internalMemberName by wrapping the MH in a BMH.
1616             MethodHandle result = rebind();
1617             assert (result.internalMemberName() == null);
1618             return result;
1619         }
1620     }
1621 
1622     /*non-public*/
1623     boolean isInvokeSpecial() {
1624         return false;  // DMH.Special returns true
1625     }
1626 
1627     /*non-public*/
1628     Object internalValues() {
1629         return null;
1630     }
1631 
1632     /*non-public*/
1633     Object internalProperties() {
1634         // Override to something to follow this.form, like "\n& FOO=bar"
1635         return "";
1636     }
1637 
1638     //// Method handle implementation methods.
1639     //// Sub-classes can override these default implementations.
1640     //// All these methods assume arguments are already validated.
1641 
1642     /*non-public*/
1643     abstract MethodHandle copyWith(MethodType mt, LambdaForm lf);
1644 
1645     /** Require this method handle to be a BMH, or else replace it with a "wrapper" BMH.
1646      *  Many transforms are implemented only for BMHs.
1647      *  @return a behaviorally equivalent BMH
1648      */
1649     abstract BoundMethodHandle rebind();
1650 
1651     /**
1652      * Replace the old lambda form of this method handle with a new one.
1653      * The new one must be functionally equivalent to the old one.
1654      * Threads may continue running the old form indefinitely,
1655      * but it is likely that the new one will be preferred for new executions.
1656      * Use with discretion.
1657      */
1658     /*non-public*/
1659     void updateForm(LambdaForm newForm) {
1660         assert(newForm.customized == null || newForm.customized == this);
1661         if (form == newForm)  return;
1662         newForm.prepare();  // as in MethodHandle.<init>
1663         UNSAFE.putObject(this, FORM_OFFSET, newForm);
1664         UNSAFE.fullFence();
1665     }
1666 
1667     /** Craft a LambdaForm customized for this particular MethodHandle */
1668     /*non-public*/
1669     void customize() {
1670         final LambdaForm form = this.form;
1671         if (form.customized == null) {
1672             LambdaForm newForm = form.customize(this);
1673             updateForm(newForm);
1674         } else {
1675             assert(form.customized == this);
1676         }
1677     }
1678 
1679     private static final long FORM_OFFSET
1680             = UNSAFE.objectFieldOffset(MethodHandle.class, "form");
1681 }