MethodHandle.java 56.3 KB
Newer Older
1
/*
2
 * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * 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 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
24 25
 */

26
package java.lang.invoke;
27 28


29
import java.util.ArrayList;
30
import sun.invoke.util.ValueConversions;
31
import static java.lang.invoke.MethodHandleStatics.*;
32

33
/**
34
 * A method handle is a typed, directly executable reference to an underlying method,
35
 * constructor, field, or similar low-level operation, with optional
36
 * transformations of arguments or return values.
37 38 39
 * These transformations are quite general, and include such patterns as
 * {@linkplain #asType conversion},
 * {@linkplain #bindTo insertion},
40 41
 * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion},
 * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}.
42 43 44 45 46 47
 *
 * <h3>Method handle contents</h3>
 * Method handles are dynamically and strongly typed according to type descriptor.
 * They are not distinguished by the name or defining class of their underlying methods.
 * A method handle must be invoked using type descriptor which matches
 * the method handle's own {@linkplain #type method type}.
48
 * <p>
49
 * Every method handle reports its type via the {@link #type type} accessor.
50
 * This type descriptor is a {@link java.lang.invoke.MethodType MethodType} object,
51
 * whose structure is a series of classes, one of which is
52
 * the return type of the method (or {@code void.class} if none).
53
 * <p>
54 55 56 57
 * A method handle's type controls the types of invocations it accepts,
 * and the kinds of transformations that apply to it.
 * <p>
 * A method handle contains a pair of special invoker methods
58
 * called {@link #invokeExact invokeExact} and {@link #invoke invoke}.
59 60 61 62
 * Both invoker methods provide direct access to the method handle's
 * underlying method, constructor, field, or other operation,
 * as modified by transformations of arguments and return values.
 * Both invokers accept calls which exactly match the method handle's own type.
63
 * The plain, inexact invoker also accepts a range of other call types.
64
 * <p>
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
 * Method handles are immutable and have no visible state.
 * Of course, they can be bound to underlying methods or data which exhibit state.
 * With respect to the Java Memory Model, any method handle will behave
 * as if all of its (internal) fields are final variables.  This means that any method
 * handle made visible to the application will always be fully formed.
 * This is true even if the method handle is published through a shared
 * variable in a data race.
 * <p>
 * Method handles cannot be subclassed by the user.
 * Implementations may (or may not) create internal subclasses of {@code MethodHandle}
 * which may be visible via the {@link java.lang.Object#getClass Object.getClass}
 * operation.  The programmer should not draw conclusions about a method handle
 * from its specific class, as the method handle class hierarchy (if any)
 * may change from time to time or across implementations from different vendors.
 *
 * <h3>Method handle compilation</h3>
81
 * A Java method call expression naming {@code invokeExact} or {@code invoke}
82 83 84 85 86
 * can invoke a method handle from Java source code.
 * From the viewpoint of source code, these methods can take any arguments
 * and their result can be cast to any return type.
 * Formally this is accomplished by giving the invoker methods
 * {@code Object} return types and variable-arity {@code Object} arguments,
87
 * but they have an additional quality called <em>signature polymorphism</em>
88 89 90
 * which connects this freedom of invocation directly to the JVM execution stack.
 * <p>
 * As is usual with virtual methods, source-level calls to {@code invokeExact}
91
 * and {@code invoke} compile to an {@code invokevirtual} instruction.
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
 * More unusually, the compiler must record the actual argument types,
 * and may not perform method invocation conversions on the arguments.
 * Instead, it must push them on the stack according to their own unconverted types.
 * The method handle object itself is pushed on the stack before the arguments.
 * The compiler then calls the method handle with a type descriptor which
 * describes the argument and return types.
 * <p>
 * To issue a complete type descriptor, the compiler must also determine
 * the return type.  This is based on a cast on the method invocation expression,
 * if there is one, or else {@code Object} if the invocation is an expression
 * or else {@code void} if the invocation is a statement.
 * The cast may be to a primitive type (but not {@code void}).
 * <p>
 * As a corner case, an uncasted {@code null} argument is given
 * a type descriptor of {@code java.lang.Void}.
 * The ambiguity with the type {@code Void} is harmless, since there are no references of type
 * {@code Void} except the null reference.
 *
 * <h3>Method handle invocation</h3>
 * The first time a {@code invokevirtual} instruction is executed
 * it is linked, by symbolically resolving the names in the instruction
 * and verifying that the method call is statically legal.
114
 * This is true of calls to {@code invokeExact} and {@code invoke}.
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
 * In this case, the type descriptor emitted by the compiler is checked for
 * correct syntax and names it contains are resolved.
 * Thus, an {@code invokevirtual} instruction which invokes
 * a method handle will always link, as long
 * as the type descriptor is syntactically well-formed
 * and the types exist.
 * <p>
 * When the {@code invokevirtual} is executed after linking,
 * the receiving method handle's type is first checked by the JVM
 * to ensure that it matches the descriptor.
 * If the type match fails, it means that the method which the
 * caller is invoking is not present on the individual
 * method handle being invoked.
 * <p>
 * In the case of {@code invokeExact}, the type descriptor of the invocation
 * (after resolving symbolic type names) must exactly match the method type
 * of the receiving method handle.
132
 * In the case of plain, inexact {@code invoke}, the resolved type descriptor
133
 * must be a valid argument to the receiver's {@link #asType asType} method.
134
 * Thus, plain {@code invoke} is more permissive than {@code invokeExact}.
135 136 137 138
 * <p>
 * After type matching, a call to {@code invokeExact} directly
 * and immediately invoke the method handle's underlying method
 * (or other behavior, as the case may be).
139
 * <p>
140
 * A call to plain {@code invoke} works the same as a call to
141
 * {@code invokeExact}, if the type descriptor specified by the caller
142
 * exactly matches the method handle's own type.
143
 * If there is a type mismatch, {@code invoke} attempts
144 145 146
 * to adjust the type of the receiving method handle,
 * as if by a call to {@link #asType asType},
 * to obtain an exactly invokable method handle {@code M2}.
147 148 149
 * This allows a more powerful negotiation of method type
 * between caller and callee.
 * <p>
150
 * (<em>Note:</em> The adjusted method handle {@code M2} is not directly observable,
151 152 153 154 155 156
 * and implementations are therefore not required to materialize it.)
 *
 * <h3>Invocation checking</h3>
 * In typical programs, method handle type matching will usually succeed.
 * But if a match fails, the JVM will throw a {@link WrongMethodTypeException},
 * either directly (in the case of {@code invokeExact}) or indirectly as if
157
 * by a failed call to {@code asType} (in the case of {@code invoke}).
158
 * <p>
159 160 161 162
 * Thus, a method type mismatch which might show up as a linkage error
 * in a statically typed program can show up as
 * a dynamic {@code WrongMethodTypeException}
 * in a program which uses method handles.
163
 * <p>
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
 * Because method types contain "live" {@code Class} objects,
 * method type matching takes into account both types names and class loaders.
 * Thus, even if a method handle {@code M} is created in one
 * class loader {@code L1} and used in another {@code L2},
 * method handle calls are type-safe, because the caller's type
 * descriptor, as resolved in {@code L2},
 * is matched against the original callee method's type descriptor,
 * as resolved in {@code L1}.
 * The resolution in {@code L1} happens when {@code M} is created
 * and its type is assigned, while the resolution in {@code L2} happens
 * when the {@code invokevirtual} instruction is linked.
 * <p>
 * Apart from the checking of type descriptors,
 * a method handle's capability to call its underlying method is unrestricted.
 * If a method handle is formed on a non-public method by a class
 * that has access to that method, the resulting handle can be used
 * in any place by any caller who receives a reference to it.
181
 * <p>
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
 * Unlike with the Core Reflection API, where access is checked every time
 * a reflective method is invoked,
 * method handle access checking is performed
 * <a href="MethodHandles.Lookup.html#access">when the method handle is created</a>.
 * In the case of {@code ldc} (see below), access checking is performed as part of linking
 * the constant pool entry underlying the constant method handle.
 * <p>
 * Thus, handles to non-public methods, or to methods in non-public classes,
 * should generally be kept secret.
 * They should not be passed to untrusted code unless their use from
 * the untrusted code would be harmless.
 *
 * <h3>Method handle creation</h3>
 * Java code can create a method handle that directly accesses
 * any method, constructor, or field that is accessible to that code.
 * This is done via a reflective, capability-based API called
198
 * {@link java.lang.invoke.MethodHandles.Lookup MethodHandles.Lookup}
199
 * For example, a static method handle can be obtained
200
 * from {@link java.lang.invoke.MethodHandles.Lookup#findStatic Lookup.findStatic}.
201
 * There are also conversion methods from Core Reflection API objects,
202
 * such as {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
203 204 205 206 207 208
 * <p>
 * Like classes and strings, method handles that correspond to accessible
 * fields, methods, and constructors can also be represented directly
 * in a class file's constant pool as constants to be loaded by {@code ldc} bytecodes.
 * A new type of constant pool entry, {@code CONSTANT_MethodHandle},
 * refers directly to an associated {@code CONSTANT_Methodref},
209 210
 * {@code CONSTANT_InterfaceMethodref}, or {@code CONSTANT_Fieldref}
 * constant pool entry.
211 212
 * (For more details on method handle constants,
 * see the <a href="package-summary.html#mhcon">package summary</a>.)
213
 * <p>
214 215 216 217 218
 * Method handles produced by lookups or constant loads from methods or
 * constructors with the variable arity modifier bit ({@code 0x0080})
 * have a corresponding variable arity, as if they were defined with
 * the help of {@link #asVarargsCollector asVarargsCollector}.
 * <p>
219 220 221 222 223
 * A method reference may refer either to a static or non-static method.
 * In the non-static case, the method handle type includes an explicit
 * receiver argument, prepended before any other arguments.
 * In the method handle's type, the initial receiver argument is typed
 * according to the class under which the method was initially requested.
224
 * (E.g., if a non-static method handle is obtained via {@code ldc},
225 226 227 228 229
 * the type of the receiver is the class named in the constant pool entry.)
 * <p>
 * When a method handle to a virtual method is invoked, the method is
 * always looked up in the receiver (that is, the first argument).
 * <p>
230
 * A non-virtual method handle to a specific virtual method implementation
231 232
 * can also be created.  These do not perform virtual lookup based on
 * receiver type.  Such a method handle simulates the effect of
233
 * an {@code invokespecial} instruction to the same method.
234 235
 *
 * <h3>Usage examples</h3>
236 237
 * Here are some examples of usage:
 * <p><blockquote><pre>
238 239 240
Object x, y; String s; int i;
MethodType mt; MethodHandle mh;
MethodHandles.Lookup lookup = MethodHandles.lookup();
241
// mt is (char,char)String
242 243
mt = MethodType.methodType(String.class, char.class, char.class);
mh = lookup.findVirtual(String.class, "replace", mt);
244
s = (String) mh.invokeExact("daddy",'d','n');
245
// invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
246 247
assert(s.equals("nanny"));
// weakly typed invocation (using MHs.invoke)
248
s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
249
assert(s.equals("savvy"));
250
// mt is (Object[])List
251 252
mt = MethodType.methodType(java.util.List.class, Object[].class);
mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
253
assert(mh.isVarargsCollector());
254 255
x = mh.invoke("one", "two");
// invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
256
assert(x.equals(java.util.Arrays.asList("one","two")));
257
// mt is (Object,Object,Object)Object
258
mt = MethodType.genericMethodType(3);
259
mh = mh.asType(mt);
260
x = mh.invokeExact((Object)1, (Object)2, (Object)3);
261
// invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
262
assert(x.equals(java.util.Arrays.asList(1,2,3)));
263
// mt is int()
264 265
mt = MethodType.methodType(int.class);
mh = lookup.findVirtual(java.util.List.class, "size", mt);
266
i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
267
// invokeExact(Ljava/util/List;)I
268
assert(i == 3);
269 270 271
mt = MethodType.methodType(void.class, String.class);
mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
mh.invokeExact(System.out, "Hello, world.");
272
// invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
273
 * </pre></blockquote>
274
 * Each of the above calls to {@code invokeExact} or plain {@code invoke}
275 276 277 278
 * generates a single invokevirtual instruction with
 * the type descriptor indicated in the following comment.
 *
 * <h3>Exceptions</h3>
279
 * The methods {@code invokeExact} and {@code invoke} are declared
280 281 282 283 284 285 286 287 288 289 290
 * to throw {@link java.lang.Throwable Throwable},
 * which is to say that there is no static restriction on what a method handle
 * can throw.  Since the JVM does not distinguish between checked
 * and unchecked exceptions (other than by their class, of course),
 * there is no particular effect on bytecode shape from ascribing
 * checked exceptions to method handle invocations.  But in Java source
 * code, methods which perform method handle calls must either explicitly
 * throw {@code java.lang.Throwable Throwable}, or else must catch all
 * throwables locally, rethrowing only those which are legal in the context,
 * and wrapping ones which are illegal.
 *
291
 * <h3><a name="sigpoly"></a>Signature polymorphism</h3>
292
 * The unusual compilation and linkage behavior of
293
 * {@code invokeExact} and plain {@code invoke}
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
 * is referenced by the term <em>signature polymorphism</em>.
 * A signature polymorphic method is one which can operate with
 * any of a wide range of call signatures and return types.
 * In order to make this work, both the Java compiler and the JVM must
 * give special treatment to signature polymorphic methods.
 * <p>
 * In source code, a call to a signature polymorphic method will
 * compile, regardless of the requested type descriptor.
 * As usual, the Java compiler emits an {@code invokevirtual}
 * instruction with the given type descriptor against the named method.
 * The unusual part is that the type descriptor is derived from
 * the actual argument and return types, not from the method declaration.
 * <p>
 * When the JVM processes bytecode containing signature polymorphic calls,
 * it will successfully link any such call, regardless of its type descriptor.
 * (In order to retain type safety, the JVM will guard such calls with suitable
 * dynamic type checks, as described elsewhere.)
 * <p>
 * Bytecode generators, including the compiler back end, are required to emit
 * untransformed type descriptors for these methods.
 * Tools which determine symbolic linkage are required to accept such
 * untransformed descriptors, without reporting linkage errors.
316 317 318
 * <p>
 * For the sake of tools (but not as a programming API), the signature polymorphic
 * methods are marked with a private yet standard annotation,
319
 * {@code @java.lang.invoke.MethodHandle.PolymorphicSignature}.
320 321 322 323 324 325
 * The annotation's retention is {@code RUNTIME}, so that all tools can see it.
 *
 * <h3>Formal rules for processing signature polymorphic methods</h3>
 * <p>
 * The following methods (and no others) are signature polymorphic:
 * <ul>
326
 * <li>{@link java.lang.invoke.MethodHandle#invokeExact   MethodHandle.invokeExact}
327
 * <li>{@link java.lang.invoke.MethodHandle#invoke        MethodHandle.invoke}
328 329 330 331 332 333 334
 * </ul>
 * <p>
 * A signature polymorphic method will be declared with the following properties:
 * <ul>
 * <li>It must be native.
 * <li>It must take a single varargs parameter of the form {@code Object...}.
 * <li>It must produce a return value of type {@code Object}.
335
 * <li>It must be contained within the {@code java.lang.invoke} package.
336 337 338 339 340 341 342 343 344 345 346 347
 * </ul>
 * Because of these requirements, a signature polymorphic method is able to accept
 * any number and type of actual arguments, and can, with a cast, produce a value of any type.
 * However, the JVM will treat these declaration features as a documentation convention,
 * rather than a description of the actual structure of the methods as executed.
 * <p>
 * When a call to a signature polymorphic method is compiled, the associated linkage information for
 * its arguments is not array of {@code Object} (as for other similar varargs methods)
 * but rather the erasure of the static types of all the arguments.
 * <p>
 * In an argument position of a method invocation on a signature polymorphic method,
 * a null literal has type {@code java.lang.Void}, unless cast to a reference type.
348
 * (<em>Note:</em> This typing rule allows the null type to have its own encoding in linkage information
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
 * distinct from other types.
 * <p>
 * The linkage information for the return type is derived from a context-dependent target typing convention.
 * The return type for a signature polymorphic method invocation is determined as follows:
 * <ul>
 * <li>If the method invocation expression is an expression statement, the method is {@code void}.
 * <li>Otherwise, if the method invocation expression is the immediate operand of a cast,
 * the return type is the erasure of the cast type.
 * <li>Otherwise, the return type is the method's nominal return type, {@code Object}.
 * </ul>
 * (Programmers are encouraged to use explicit casts unless it is clear that a signature polymorphic
 * call will be used as a plain {@code Object} expression.)
 * <p>
 * The linkage information for argument and return types is stored in the descriptor for the
 * compiled (bytecode) call site. As for any invocation instruction, the arguments and return value
 * will be passed directly on the JVM stack, in accordance with the descriptor,
 * and without implicit boxing or unboxing.
366 367
 *
 * <h3>Interoperation between method handles and the Core Reflection API</h3>
368
 * Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup Lookup} API,
369 370 371 372
 * any class member represented by a Core Reflection API object
 * can be converted to a behaviorally equivalent method handle.
 * For example, a reflective {@link java.lang.reflect.Method Method} can
 * be converted to a method handle using
373
 * {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
374 375 376 377 378
 * The resulting method handles generally provide more direct and efficient
 * access to the underlying class members.
 * <p>
 * As a special case,
 * when the Core Reflection API is used to view the signature polymorphic
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
 * methods {@code invokeExact} or plain {@code invoke} in this class,
 * they appear as ordinary non-polymorphic methods.
 * Their reflective appearance, as viewed by
 * {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod},
 * is unaffected by their special status in this API.
 * For example, {@link java.lang.reflect.Method#getModifiers Method.getModifiers}
 * will report exactly those modifier bits required for any similarly
 * declared method, including in this case {@code native} and {@code varargs} bits.
 * <p>
 * As with any reflected method, these methods (when reflected) may be
 * invoked via {@link java.lang.reflect.Method#invoke Method.invoke}.
 * However, such reflective calls do not result in method handle invocations.
 * Such a call, if passed the required argument
 * (a single one, of type {@code Object[]}), will ignore the argument and
 * will throw an {@code UnsupportedOperationException}.
 * <p>
395 396
 * Since {@code invokevirtual} instructions can natively
 * invoke method handles under any type descriptor, this reflective view conflicts
397 398 399
 * with the normal presentation of these methods via bytecodes.
 * Thus, these two native methods, when reflectively viewed by
 * {@code Class.getDeclaredMethod}, may be regarded as placeholders only.
400 401
 * <p>
 * In order to obtain an invoker method for a particular type descriptor,
402
 * use {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker},
403
 * or {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}.
404
 * The {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual}
405
 * API is also able to return a method handle
406
 * to call {@code invokeExact} or plain {@code invoke},
407 408 409 410 411 412 413 414 415 416 417 418
 * for any specified type descriptor .
 *
 * <h3>Interoperation between method handles and Java generics</h3>
 * A method handle can be obtained on a method, constructor, or field
 * which is declared with Java generic types.
 * As with the Core Reflection API, the type of the method handle
 * will constructed from the erasure of the source-level type.
 * When a method handle is invoked, the types of its arguments
 * or the return value cast type may be generic types or type instances.
 * If this occurs, the compiler will replace those
 * types by their erasures when when it constructs the type descriptor
 * for the {@code invokevirtual} instruction.
419
 * <p>
420 421 422
 * Method handles do not represent
 * their function-like types in terms of Java parameterized (generic) types,
 * because there are three mismatches between function-like types and parameterized
423
 * Java types.
424
 * <ul>
425
 * <li>Method types range over all possible arities,
426
 * from no arguments to up to 255 of arguments (a limit imposed by the JVM).
427 428 429 430 431 432 433
 * Generics are not variadic, and so cannot represent this.</li>
 * <li>Method types can specify arguments of primitive types,
 * which Java generic types cannot range over.</li>
 * <li>Higher order functions over method handles (combinators) are
 * often generic across a wide range of function types, including
 * those of multiple arities.  It is impossible to represent such
 * genericity with a Java type parameter.</li>
434
 * </ul>
435 436 437 438 439
 *
 * @see MethodType
 * @see MethodHandles
 * @author John Rose, JSR 292 EG
 */
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
public abstract class MethodHandle {
    // { JVM internals:

    private byte       vmentry;    // adapter stub or method entry point
    //private int      vmslots;    // optionally, hoist type.form.vmslots
    /*non-public*/ Object vmtarget;   // VM-specific, class-specific target value

    // TO DO:  vmtarget should be invisible to Java, since the JVM puts internal
    // managed pointers into it.  Making it visible exposes it to debuggers,
    // which can cause errors when they treat the pointer as an Object.

    // These two dummy fields are present to force 'I' and 'J' signatures
    // into this class's constant pool, so they can be transferred
    // to vmentry when this class is loaded.
    static final int  INT_FIELD = 0;
    static final long LONG_FIELD = 0;

    // vmentry (a void* field) is used *only* by the JVM.
    // The JVM adjusts its type to int or long depending on system wordsize.
    // Since it is statically typed as neither int nor long, it is impossible
    // to use this field from Java bytecode.  (Please don't try to, either.)

    // The vmentry is an assembly-language stub which is jumped to
    // immediately after the method type is verified.
    // For a direct MH, this stub loads the vmtarget's entry point
    // and jumps to it.

    // } End of JVM internals.

469
    static { MethodHandleImpl.initStatics(); }
470

471
    // interface MethodHandle<R throws X extends Exception,A...>
472 473 474 475
    // { MethodType<R throws X,A...> type(); public R invokeExact(A...) throws X; }

    /**
     * Internal marker interface which distinguishes (to the Java compiler)
476
     * those methods which are <a href="MethodHandle.html#sigpoly">signature polymorphic</a>.
477
     */
478
    @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
479
    @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
480
    @interface PolymorphicSignature { }
481 482

    private MethodType type;
483 484

    /**
485
     * Reports the type of this method handle.
486
     * Every invocation of this method handle via {@code invokeExact} must exactly match this type.
487 488
     * @return the method handle type
     */
489
    public MethodType type() {
490 491 492 493
        return type;
    }

    /**
494 495
     * Package-private constructor for the method handle implementation hierarchy.
     * Method handle inheritance will be contained completely within
496
     * the {@code java.lang.invoke} package.
497
     */
498
    // @param type type (permanently assigned) of the new method handle
499
    /*non-public*/ MethodHandle(MethodType type) {
500
        type.getClass();  // elicit NPE
501 502
        this.type = type;
    }
503 504

    /**
505
     * Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match.
506
     * The type descriptor at the call site of {@code invokeExact} must
507
     * exactly match this method handle's {@link #type type}.
508
     * No conversions are allowed on arguments or return values.
509 510 511 512 513
     * <p>
     * When this method is observed via the Core Reflection API,
     * it will appear as a single native method, taking an object array and returning an object.
     * If this native method is invoked directly via
     * {@link java.lang.reflect.Method#invoke Method.invoke}, via JNI,
514
     * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
515 516
     * it will throw an {@code UnsupportedOperationException}.
     * @throws WrongMethodTypeException if the target's type is not identical with the caller's type descriptor
517
     * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
518
     */
519
    public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable;
520

521
    /**
522
     * Invokes the method handle, allowing any caller type descriptor,
523
     * and optionally performing conversions on arguments and return values.
524
     * <p>
525
     * If the call site type descriptor exactly matches this method handle's {@link #type type},
526
     * the call proceeds as if by {@link #invokeExact invokeExact}.
527 528
     * <p>
     * Otherwise, the call proceeds as if this method handle were first
529
     * adjusted by calling {@link #asType asType} to adjust this method handle
530
     * to the required type, and then the call proceeds as if by
531 532 533 534 535 536 537
     * {@link #invokeExact invokeExact} on the adjusted method handle.
     * <p>
     * There is no guarantee that the {@code asType} call is actually made.
     * If the JVM can predict the results of making the call, it may perform
     * adaptations directly on the caller's arguments,
     * and call the target method handle according to its own exact type.
     * <p>
538
     * The type descriptor at the call site of {@code invoke} must
539
     * be a valid argument to the receivers {@code asType} method.
540
     * In particular, the caller must specify the same argument arity
541 542
     * as the callee's type,
     * if the callee is not a {@linkplain #asVarargsCollector variable arity collector}.
543 544 545 546 547
     * <p>
     * When this method is observed via the Core Reflection API,
     * it will appear as a single native method, taking an object array and returning an object.
     * If this native method is invoked directly via
     * {@link java.lang.reflect.Method#invoke Method.invoke}, via JNI,
548
     * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
549 550
     * it will throw an {@code UnsupportedOperationException}.
     * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's type descriptor
551
     * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails
552
     * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
553
     */
554 555 556 557 558 559 560
    public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable;

    /**
     * <em>Temporary alias</em> for {@link #invoke}, for backward compatibility with some versions of JSR 292.
     * On some JVMs, support can be excluded by the flags {@code -XX:+UnlockExperimentalVMOptions -XX:-AllowInvokeGeneric}.
     * @deprecated Will be removed for JSR 292 Proposed Final Draft.
     */
561
    public final native @PolymorphicSignature Object invokeGeneric(Object... args) throws Throwable;
562

563
    /**
564
     * Performs a varargs invocation, passing the arguments in the given array
565
     * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
566 567 568
     * which mentions only the type {@code Object}, and whose arity is the length
     * of the argument array.
     * <p>
569 570 571 572 573 574
     * Specifically, execution proceeds as if by the following steps,
     * although the methods are not guaranteed to be called if the JVM
     * can predict their effects.
     * <ul>
     * <li>Determine the length of the argument array as {@code N}.
     *     For a null reference, {@code N=0}. </li>
575
     * <li>Determine the general type {@code TN} of {@code N} arguments as
576 577 578 579 580 581 582 583
     *     as {@code TN=MethodType.genericMethodType(N)}.</li>
     * <li>Force the original target method handle {@code MH0} to the
     *     required type, as {@code MH1 = MH0.asType(TN)}. </li>
     * <li>Spread the array into {@code N} separate arguments {@code A0, ...}. </li>
     * <li>Invoke the type-adjusted method handle on the unpacked arguments:
     *     MH1.invokeExact(A0, ...). </li>
     * <li>Take the return value as an {@code Object} reference. </li>
     * </ul>
584
     * <p>
585
     * Because of the action of the {@code asType} step, the following argument
586 587 588 589
     * conversions are applied as necessary:
     * <ul>
     * <li>reference casting
     * <li>unboxing
590
     * <li>widening primitive conversions
591
     * </ul>
592
     * <p>
593 594 595 596 597
     * The result returned by the call is boxed if it is a primitive,
     * or forced to null if the return type is void.
     * <p>
     * This call is equivalent to the following code:
     * <p><blockquote><pre>
598
     * MethodHandle invoker = MethodHandles.spreadInvoker(this.type(), 0);
599
     * Object result = invoker.invokeExact(this, arguments);
600
     * </pre></blockquote>
601
     * <p>
602
     * Unlike the signature polymorphic methods {@code invokeExact} and {@code invoke},
603 604 605
     * {@code invokeWithArguments} can be accessed normally via the Core Reflection API and JNI.
     * It can therefore be used as a bridge between native or reflective code and method handles.
     *
606 607
     * @param arguments the arguments to pass to the target
     * @return the result returned by the target
608 609
     * @throws ClassCastException if an argument cannot be converted by reference casting
     * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
610
     * @throws Throwable anything thrown by the target method invocation
611
     * @see MethodHandles#spreadInvoker
612
     */
613
    public Object invokeWithArguments(Object... arguments) throws Throwable {
614 615
        int argc = arguments == null ? 0 : arguments.length;
        MethodType type = type();
616
        if (type.parameterCount() != argc) {
617
            // simulate invoke
618 619
            return asType(MethodType.genericMethodType(argc)).invokeWithArguments(arguments);
        }
620
        if (argc <= 10) {
621
            MethodHandle invoker = type.invokers().generalInvoker();
622
            switch (argc) {
623 624
                case 0:  return invoker.invokeExact(this);
                case 1:  return invoker.invokeExact(this,
625
                                    arguments[0]);
626
                case 2:  return invoker.invokeExact(this,
627
                                    arguments[0], arguments[1]);
628
                case 3:  return invoker.invokeExact(this,
629
                                    arguments[0], arguments[1], arguments[2]);
630
                case 4:  return invoker.invokeExact(this,
631 632
                                    arguments[0], arguments[1], arguments[2],
                                    arguments[3]);
633
                case 5:  return invoker.invokeExact(this,
634 635
                                    arguments[0], arguments[1], arguments[2],
                                    arguments[3], arguments[4]);
636
                case 6:  return invoker.invokeExact(this,
637 638
                                    arguments[0], arguments[1], arguments[2],
                                    arguments[3], arguments[4], arguments[5]);
639
                case 7:  return invoker.invokeExact(this,
640 641 642
                                    arguments[0], arguments[1], arguments[2],
                                    arguments[3], arguments[4], arguments[5],
                                    arguments[6]);
643
                case 8:  return invoker.invokeExact(this,
644 645 646
                                    arguments[0], arguments[1], arguments[2],
                                    arguments[3], arguments[4], arguments[5],
                                    arguments[6], arguments[7]);
647
                case 9:  return invoker.invokeExact(this,
648 649 650
                                    arguments[0], arguments[1], arguments[2],
                                    arguments[3], arguments[4], arguments[5],
                                    arguments[6], arguments[7], arguments[8]);
651
                case 10:  return invoker.invokeExact(this,
652 653 654 655 656 657 658 659
                                    arguments[0], arguments[1], arguments[2],
                                    arguments[3], arguments[4], arguments[5],
                                    arguments[6], arguments[7], arguments[8],
                                    arguments[9]);
            }
        }

        // more than ten arguments get boxed in a varargs list:
660
        MethodHandle invoker = type.invokers().spreadInvoker(0);
661
        return invoker.invokeExact(this, arguments);
662
    }
663 664 665

    /**
     * Performs a varargs invocation, passing the arguments in the given array
666
     * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
667 668 669 670 671 672 673 674 675 676 677 678 679 680
     * which mentions only the type {@code Object}, and whose arity is the length
     * of the argument array.
     * <p>
     * This method is also equivalent to the following code:
     * <p><blockquote><pre>
     * {@link #invokeWithArguments(Object...) invokeWithArguments}(arguments.toArray())
     * </pre></blockquote>
     *
     * @param arguments the arguments to pass to the target
     * @return the result returned by the target
     * @throws ClassCastException if an argument cannot be converted by reference casting
     * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
     * @throws Throwable anything thrown by the target method invocation
     */
681
    public Object invokeWithArguments(java.util.List<?> arguments) throws Throwable {
682
        return invokeWithArguments(arguments.toArray());
683 684
    }

685
    /**
686 687
     * Produces an adapter method handle which adapts the type of the
     * current method handle to a new type.
688
     * The resulting method handle is guaranteed to report a type
689 690 691 692
     * which is equal to the desired new type.
     * <p>
     * If the original type and new type are equal, returns {@code this}.
     * <p>
693
     * This method provides the crucial behavioral difference between
694
     * {@link #invokeExact invokeExact} and plain, inexact {@link #invoke invoke}.  The two methods
695
     * perform the same steps when the caller's type descriptor is identical
696
     * with the callee's, but when the types differ, plain {@link #invoke invoke}
697 698
     * also calls {@code asType} (or some internal equivalent) in order
     * to match up the caller's and callee's types.
699
     * <p>
700
     * This method is equivalent to {@link MethodHandles#convertArguments convertArguments},
701
     * except for variable arity method handles produced by {@link #asVarargsCollector asVarargsCollector}.
702
     *
703 704 705 706
     * @param newType the expected type of the new method handle
     * @return a method handle which delegates to {@code this} after performing
     *           any necessary argument conversions, and arranges for any
     *           necessary return value conversions
707
     * @throws WrongMethodTypeException if the conversion cannot be made
708 709
     * @see MethodHandles#convertArguments
     */
710
    public MethodHandle asType(MethodType newType) {
711
        if (!type.isConvertibleTo(newType)) {
712
            throw new WrongMethodTypeException("cannot convert "+this+" to "+newType);
713
        }
714
        return MethodHandleImpl.convertArguments(this, newType, 1);
715 716 717
    }

    /**
718
     * Makes an adapter which accepts a trailing array argument
719 720
     * and spreads its elements as positional arguments.
     * The new method handle adapts, as its <i>target</i>,
721
     * the current method handle.  The type of the adapter will be
722 723 724 725 726
     * the same as the type of the target, except that the final
     * {@code arrayLength} parameters of the target's type are replaced
     * by a single array parameter of type {@code arrayType}.
     * <p>
     * If the array element type differs from any of the corresponding
727
     * argument types on the original target,
728 729
     * the original target is adapted to take the array elements directly,
     * as if by a call to {@link #asType asType}.
730 731 732 733 734 735 736 737 738 739 740 741 742
     * <p>
     * When called, the adapter replaces a trailing array argument
     * by the array's elements, each as its own argument to the target.
     * (The order of the arguments is preserved.)
     * They are converted pairwise by casting and/or unboxing
     * to the types of the trailing parameters of the target.
     * Finally the target is called.
     * What the target eventually returns is returned unchanged by the adapter.
     * <p>
     * Before calling the target, the adapter verifies that the array
     * contains exactly enough elements to provide a correct argument count
     * to the target method handle.
     * (The array may also be null when zero elements are required.)
743 744 745
     * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments
     * @param arrayLength the number of arguments to spread from an incoming array argument
     * @return a new method handle which spreads its final array argument,
746
     *         before calling the original method handle
747
     * @throws IllegalArgumentException if {@code arrayType} is not an array type
748
     * @throws IllegalArgumentException if target does not have at least
749 750
     *         {@code arrayLength} parameter types
     * @throws WrongMethodTypeException if the implied {@code asType} call fails
751
     * @see #asCollector
752
     */
753
    public MethodHandle asSpreader(Class<?> arrayType, int arrayLength) {
754 755 756 757 758 759
        asSpreaderChecks(arrayType, arrayLength);
        return MethodHandleImpl.spreadArguments(this, arrayType, arrayLength);
    }

    private void asSpreaderChecks(Class<?> arrayType, int arrayLength) {
        spreadArrayChecks(arrayType, arrayLength);
760
        int nargs = type().parameterCount();
761
        if (nargs < arrayLength)  throw newIllegalArgumentException("bad spread array length");
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
        if (arrayType != Object[].class && arrayLength != 0) {
            boolean sawProblem = false;
            Class<?> arrayElement = arrayType.getComponentType();
            for (int i = nargs - arrayLength; i < nargs; i++) {
                if (!MethodType.canConvert(arrayElement, type().parameterType(i))) {
                    sawProblem = true;
                    break;
                }
            }
            if (sawProblem) {
                ArrayList<Class<?>> ptypes = new ArrayList<Class<?>>(type().parameterList());
                for (int i = nargs - arrayLength; i < nargs; i++) {
                    ptypes.set(i, arrayElement);
                }
                // elicit an error:
                this.asType(MethodType.methodType(type().returnType(), ptypes));
            }
        }
    }

    private void spreadArrayChecks(Class<?> arrayType, int arrayLength) {
        Class<?> arrayElement = arrayType.getComponentType();
        if (arrayElement == null)
            throw newIllegalArgumentException("not an array type", arrayType);
        if ((arrayLength & 0x7F) != arrayLength) {
            if ((arrayLength & 0xFF) != arrayLength)
                throw newIllegalArgumentException("array length is not legal", arrayLength);
            assert(arrayLength >= 128);
            if (arrayElement == long.class ||
                arrayElement == double.class)
                throw newIllegalArgumentException("array length is not legal for long[] or double[]", arrayLength);
        }
794 795 796
    }

    /**
797
     * Makes an adapter which accepts a given number of trailing
798 799
     * positional arguments and collects them into an array argument.
     * The new method handle adapts, as its <i>target</i>,
800 801
     * the current method handle.  The type of the adapter will be
     * the same as the type of the target, except that a single trailing
802 803 804
     * parameter (usually of type {@code arrayType}) is replaced by
     * {@code arrayLength} parameters whose type is element type of {@code arrayType}.
     * <p>
805
     * If the array type differs from the final argument type on the original target,
806 807
     * the original target is adapted to take the array type directly,
     * as if by a call to {@link #asType asType}.
808
     * <p>
809 810
     * When called, the adapter replaces its trailing {@code arrayLength}
     * arguments by a single new array of type {@code arrayType}, whose elements
811 812 813 814
     * comprise (in order) the replaced arguments.
     * Finally the target is called.
     * What the target eventually returns is returned unchanged by the adapter.
     * <p>
815
     * (The array may also be a shared constant when {@code arrayLength} is zero.)
816 817 818 819 820 821 822 823 824
     * <p>
     * (<em>Note:</em> The {@code arrayType} is often identical to the last
     * parameter type of the original target.
     * It is an explicit argument for symmetry with {@code asSpreader}, and also
     * to allow the target to use a simple {@code Object} as its last parameter type.)
     * <p>
     * In order to create a collecting adapter which is not restricted to a particular
     * number of collected arguments, use {@link #asVarargsCollector asVarargsCollector} instead.
     * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
825
     * @param arrayLength the number of arguments to collect into a new array argument
826 827
     * @return a new method handle which collects some trailing argument
     *         into an array, before calling the original method handle
828
     * @throws IllegalArgumentException if {@code arrayType} is not an array type
829 830
     *         or {@code arrayType} is not assignable to this method handle's trailing parameter type,
     *         or {@code arrayLength} is not a legal array size
831
     * @throws WrongMethodTypeException if the implied {@code asType} call fails
832 833
     * @see #asSpreader
     * @see #asVarargsCollector
834
     */
835
    public MethodHandle asCollector(Class<?> arrayType, int arrayLength) {
836 837 838 839 840
        asCollectorChecks(arrayType, arrayLength);
        MethodHandle collector = ValueConversions.varargsArray(arrayType, arrayLength);
        return MethodHandleImpl.collectArguments(this, type.parameterCount()-1, collector);
    }

841 842
    private void asCollectorChecks(Class<?> arrayType, int arrayLength) {
        spreadArrayChecks(arrayType, arrayLength);
843 844 845
        int nargs = type().parameterCount();
        if (nargs == 0 || !type().parameterType(nargs-1).isAssignableFrom(arrayType))
            throw newIllegalArgumentException("array type not assignable to trailing argument", this, arrayType);
846 847 848
    }

    /**
849
     * Makes a <em>variable arity</em> adapter which is able to accept
850 851 852 853 854
     * any number of trailing positional arguments and collect them
     * into an array argument.
     * <p>
     * The type and behavior of the adapter will be the same as
     * the type and behavior of the target, except that certain
855
     * {@code invoke} and {@code asType} requests can lead to
856 857 858 859 860 861 862 863 864 865 866 867 868
     * trailing positional arguments being collected into target's
     * trailing parameter.
     * Also, the last parameter type of the adapter will be
     * {@code arrayType}, even if the target has a different
     * last parameter type.
     * <p>
     * When called with {@link #invokeExact invokeExact}, the adapter invokes
     * the target with no argument changes.
     * (<em>Note:</em> This behavior is different from a
     * {@linkplain #asCollector fixed arity collector},
     * since it accepts a whole array of indeterminate length,
     * rather than a fixed number of arguments.)
     * <p>
869
     * When called with plain, inexact {@link #invoke invoke}, if the caller
870 871
     * type is the same as the adapter, the adapter invokes the target as with
     * {@code invokeExact}.
872
     * (This is the normal behavior for {@code invoke} when types match.)
873 874 875 876 877 878
     * <p>
     * Otherwise, if the caller and adapter arity are the same, and the
     * trailing parameter type of the caller is a reference type identical to
     * or assignable to the trailing parameter type of the adapter,
     * the arguments and return values are converted pairwise,
     * as if by {@link MethodHandles#convertArguments convertArguments}.
879
     * (This is also normal behavior for {@code invoke} in such a case.)
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
     * <p>
     * Otherwise, the arities differ, or the adapter's trailing parameter
     * type is not assignable from the corresponding caller type.
     * In this case, the adapter replaces all trailing arguments from
     * the original trailing argument position onward, by
     * a new array of type {@code arrayType}, whose elements
     * comprise (in order) the replaced arguments.
     * <p>
     * The caller type must provides as least enough arguments,
     * and of the correct type, to satisfy the target's requirement for
     * positional arguments before the trailing array argument.
     * Thus, the caller must supply, at a minimum, {@code N-1} arguments,
     * where {@code N} is the arity of the target.
     * Also, there must exist conversions from the incoming arguments
     * to the target's arguments.
895
     * As with other uses of plain {@code invoke}, if these basic
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
     * requirements are not fulfilled, a {@code WrongMethodTypeException}
     * may be thrown.
     * <p>
     * In all cases, what the target eventually returns is returned unchanged by the adapter.
     * <p>
     * In the final case, it is exactly as if the target method handle were
     * temporarily adapted with a {@linkplain #asCollector fixed arity collector}
     * to the arity required by the caller type.
     * (As with {@code asCollector}, if the array length is zero,
     * a shared constant may be used instead of a new array.
     * If the implied call to {@code asCollector} would throw
     * an {@code IllegalArgumentException} or {@code WrongMethodTypeException},
     * the call to the variable arity adapter must throw
     * {@code WrongMethodTypeException}.)
     * <p>
     * The behavior of {@link #asType asType} is also specialized for
     * variable arity adapters, to maintain the invariant that
913
     * plain, inexact {@code invoke} is always equivalent to an {@code asType}
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
     * call to adjust the target type, followed by {@code invokeExact}.
     * Therefore, a variable arity adapter responds
     * to an {@code asType} request by building a fixed arity collector,
     * if and only if the adapter and requested type differ either
     * in arity or trailing argument type.
     * The resulting fixed arity collector has its type further adjusted
     * (if necessary) to the requested type by pairwise conversion,
     * as if by another application of {@code asType}.
     * <p>
     * When a method handle is obtained by executing an {@code ldc} instruction
     * of a {@code CONSTANT_MethodHandle} constant, and the target method is marked
     * as a variable arity method (with the modifier bit {@code 0x0080}),
     * the method handle will accept multiple arities, as if the method handle
     * constant were created by means of a call to {@code asVarargsCollector}.
     * <p>
     * In order to create a collecting adapter which collects a predetermined
     * number of arguments, and whose type reflects this predetermined number,
     * use {@link #asCollector asCollector} instead.
     * <p>
     * No method handle transformations produce new method handles with
     * variable arity, unless they are documented as doing so.
     * Therefore, besides {@code asVarargsCollector},
     * all methods in {@code MethodHandle} and {@code MethodHandles}
     * will return a method handle with fixed arity,
     * except in the cases where they are specified to return their original
     * operand (e.g., {@code asType} of the method handle's own type).
     * <p>
     * Calling {@code asVarargsCollector} on a method handle which is already
     * of variable arity will produce a method handle with the same type and behavior.
     * It may (or may not) return the original variable arity method handle.
     * <p>
     * Here is an example, of a list-making variable arity method handle:
     * <blockquote><pre>
MethodHandle asList = publicLookup()
  .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
  .asVarargsCollector(Object[].class);
950 951 952
assertEquals("[]", asList.invoke().toString());
assertEquals("[1]", asList.invoke(1).toString());
assertEquals("[two, too]", asList.invoke("two", "too").toString());
953
Object[] argv = { "three", "thee", "tee" };
954 955
assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
List ls = (List) asList.invoke((Object)argv);
956 957 958 959
assertEquals(1, ls.size());
assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
     * </pre></blockquote>
     * <p style="font-size:smaller;">
960
     * <em>Discussion:</em>
961 962 963 964 965 966 967 968 969 970 971
     * These rules are designed as a dynamically-typed variation
     * of the Java rules for variable arity methods.
     * In both cases, callers to a variable arity method or method handle
     * can either pass zero or more positional arguments, or else pass
     * pre-collected arrays of any length.  Users should be aware of the
     * special role of the final argument, and of the effect of a
     * type match on that final argument, which determines whether
     * or not a single trailing argument is interpreted as a whole
     * array or a single element of an array to be collected.
     * Note that the dynamic type of the trailing argument has no
     * effect on this decision, only a comparison between the static
972
     * type descriptor of the call site and the type of the method handle.)
973 974 975 976 977 978 979 980
     * <p style="font-size:smaller;">
     * As a result of the previously stated rules, the variable arity behavior
     * of a method handle may be suppressed, by binding it to the exact invoker
     * of its own type, as follows:
     * <blockquote><pre>
MethodHandle vamh = publicLookup()
  .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
  .asVarargsCollector(Object[].class);
981
MethodHandle mh = MethodHandles.exactInvoker(vamh.type()).bindTo(vamh);
982
assert(vamh.type().equals(mh.type()));
983
assertEquals("[1, 2, 3]", vamh.invoke(1,2,3).toString());
984
boolean failed = false;
985
try { mh.invoke(1,2,3); }
986 987 988 989 990
catch (WrongMethodTypeException ex) { failed = true; }
assert(failed);
     * </pre></blockquote>
     * This transformation has no behavioral effect if the method handle is
     * not of variable arity.
991
     *
992 993 994 995 996 997
     * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
     * @return a new method handle which can collect any number of trailing arguments
     *         into an array, before calling the original method handle
     * @throws IllegalArgumentException if {@code arrayType} is not an array type
     *         or {@code arrayType} is not assignable to this method handle's trailing parameter type
     * @see #asCollector
998
     * @see #isVarargsCollector
999 1000 1001
     */
    public MethodHandle asVarargsCollector(Class<?> arrayType) {
        Class<?> arrayElement = arrayType.getComponentType();
1002 1003
        asCollectorChecks(arrayType, 0);
        return AdapterMethodHandle.makeVarargsCollector(this, arrayType);
1004 1005 1006
    }

    /**
1007
     * Determines if this method handle
1008 1009 1010 1011
     * supports {@linkplain #asVarargsCollector variable arity} calls.
     * Such method handles arise from the following sources:
     * <ul>
     * <li>a call to {@linkplain #asVarargsCollector asVarargsCollector}
1012
     * <li>a call to a {@linkplain java.lang.invoke.MethodHandles.Lookup lookup method}
1013 1014 1015 1016
     *     which resolves to a variable arity Java method or constructor
     * <li>an {@code ldc} instruction of a {@code CONSTANT_MethodHandle}
     *     which resolves to a variable arity Java method or constructor
     * </ul>
1017
     * @return true if this method handle accepts more than one arity of plain, inexact {@code invoke} calls
1018
     * @see #asVarargsCollector
1019 1020 1021 1022 1023 1024
     */
    public boolean isVarargsCollector() {
        return false;
    }

    /**
1025
     * Binds a value {@code x} to the first argument of a method handle, without invoking it.
1026
     * The new method handle adapts, as its <i>target</i>,
1027
     * the current method handle by binding it to the given argument.
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
     * The type of the bound handle will be
     * the same as the type of the target, except that a single leading
     * reference parameter will be omitted.
     * <p>
     * When called, the bound handle inserts the given value {@code x}
     * as a new leading argument to the target.  The other arguments are
     * also passed unchanged.
     * What the target eventually returns is returned unchanged by the bound handle.
     * <p>
     * The reference {@code x} must be convertible to the first parameter
     * type of the target.
1039 1040 1041
     * <p>
     * (<em>Note:</em>  Because method handles are immutable, the target method handle
     * retains its original type and behavior.)
1042
     * @param x  the value to bind to the first argument of the target
1043 1044
     * @return a new method handle which prepends the given value to the incoming
     *         argument list, before calling the original method handle
1045 1046 1047 1048
     * @throws IllegalArgumentException if the target does not have a
     *         leading parameter type that is a reference type
     * @throws ClassCastException if {@code x} cannot be converted
     *         to the leading parameter type of the target
1049
     * @see MethodHandles#insertArguments
1050
     */
1051
    public MethodHandle bindTo(Object x) {
1052 1053 1054 1055 1056 1057 1058 1059 1060
        Class<?> ptype;
        if (type().parameterCount() == 0 ||
            (ptype = type().parameterType(0)).isPrimitive())
            throw newIllegalArgumentException("no leading reference parameter", x);
        x = MethodHandles.checkValue(ptype, x);
        // Cf. MethodHandles.insertArguments for the following logic:
        MethodHandle bmh = MethodHandleImpl.bindReceiver(this, x);
        if (bmh != null)  return bmh;
        return MethodHandleImpl.bindArgument(this, 0, x);
1061
    }
1062

1063
    /**
1064 1065 1066 1067
     * Returns a string representation of the method handle,
     * starting with the string {@code "MethodHandle"} and
     * ending with the string representation of the method handle's type.
     * In other words, this method returns a string equal to the value of:
1068
     * <blockquote><pre>
1069
     * "MethodHandle" + type().toString()
1070 1071
     * </pre></blockquote>
     * <p>
1072
     * (<em>Note:</em>  Future releases of this API may add further information
1073
     * to the string representation.
1074
     * Therefore, the present syntax should not be parsed by applications.)
1075 1076
     *
     * @return a string representation of the method handle
1077
     */
1078 1079
    @Override
    public String toString() {
1080 1081 1082 1083 1084 1085
        if (DEBUG_METHOD_HANDLE_NAMES)  return debugString();
        return "MethodHandle"+type;
    }

    /*non-public*/
    String debugString() {
1086
        return getNameString(this);
1087
    }
1088
}