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