rt/emul/compact/src/main/java/java/lang/invoke/MethodHandle.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 14 Sep 2014 19:27:44 +0200
changeset 1692 2f800fdc371e
permissions -rw-r--r--
Adding necessary fake classes to allow Javac to compile lamda expressions against our emulation library.
jaroslav@1692
     1
/*
jaroslav@1692
     2
 * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
jaroslav@1692
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1692
     4
 *
jaroslav@1692
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1692
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1692
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1692
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1692
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1692
    10
 *
jaroslav@1692
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1692
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1692
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1692
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1692
    15
 * accompanied this code).
jaroslav@1692
    16
 *
jaroslav@1692
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@1692
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1692
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1692
    20
 *
jaroslav@1692
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1692
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1692
    23
 * questions.
jaroslav@1692
    24
 */
jaroslav@1692
    25
jaroslav@1692
    26
package java.lang.invoke;
jaroslav@1692
    27
jaroslav@1692
    28
jaroslav@1692
    29
import java.util.*;
jaroslav@1692
    30
jaroslav@1692
    31
/**
jaroslav@1692
    32
 * A method handle is a typed, directly executable reference to an underlying method,
jaroslav@1692
    33
 * constructor, field, or similar low-level operation, with optional
jaroslav@1692
    34
 * transformations of arguments or return values.
jaroslav@1692
    35
 * These transformations are quite general, and include such patterns as
jaroslav@1692
    36
 * {@linkplain #asType conversion},
jaroslav@1692
    37
 * {@linkplain #bindTo insertion},
jaroslav@1692
    38
 * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion},
jaroslav@1692
    39
 * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}.
jaroslav@1692
    40
 *
jaroslav@1692
    41
 * <h1>Method handle contents</h1>
jaroslav@1692
    42
 * Method handles are dynamically and strongly typed according to their parameter and return types.
jaroslav@1692
    43
 * They are not distinguished by the name or the defining class of their underlying methods.
jaroslav@1692
    44
 * A method handle must be invoked using a symbolic type descriptor which matches
jaroslav@1692
    45
 * the method handle's own {@linkplain #type type descriptor}.
jaroslav@1692
    46
 * <p>
jaroslav@1692
    47
 * Every method handle reports its type descriptor via the {@link #type type} accessor.
jaroslav@1692
    48
 * This type descriptor is a {@link java.lang.invoke.MethodType MethodType} object,
jaroslav@1692
    49
 * whose structure is a series of classes, one of which is
jaroslav@1692
    50
 * the return type of the method (or {@code void.class} if none).
jaroslav@1692
    51
 * <p>
jaroslav@1692
    52
 * A method handle's type controls the types of invocations it accepts,
jaroslav@1692
    53
 * and the kinds of transformations that apply to it.
jaroslav@1692
    54
 * <p>
jaroslav@1692
    55
 * A method handle contains a pair of special invoker methods
jaroslav@1692
    56
 * called {@link #invokeExact invokeExact} and {@link #invoke invoke}.
jaroslav@1692
    57
 * Both invoker methods provide direct access to the method handle's
jaroslav@1692
    58
 * underlying method, constructor, field, or other operation,
jaroslav@1692
    59
 * as modified by transformations of arguments and return values.
jaroslav@1692
    60
 * Both invokers accept calls which exactly match the method handle's own type.
jaroslav@1692
    61
 * The plain, inexact invoker also accepts a range of other call types.
jaroslav@1692
    62
 * <p>
jaroslav@1692
    63
 * Method handles are immutable and have no visible state.
jaroslav@1692
    64
 * Of course, they can be bound to underlying methods or data which exhibit state.
jaroslav@1692
    65
 * With respect to the Java Memory Model, any method handle will behave
jaroslav@1692
    66
 * as if all of its (internal) fields are final variables.  This means that any method
jaroslav@1692
    67
 * handle made visible to the application will always be fully formed.
jaroslav@1692
    68
 * This is true even if the method handle is published through a shared
jaroslav@1692
    69
 * variable in a data race.
jaroslav@1692
    70
 * <p>
jaroslav@1692
    71
 * Method handles cannot be subclassed by the user.
jaroslav@1692
    72
 * Implementations may (or may not) create internal subclasses of {@code MethodHandle}
jaroslav@1692
    73
 * which may be visible via the {@link java.lang.Object#getClass Object.getClass}
jaroslav@1692
    74
 * operation.  The programmer should not draw conclusions about a method handle
jaroslav@1692
    75
 * from its specific class, as the method handle class hierarchy (if any)
jaroslav@1692
    76
 * may change from time to time or across implementations from different vendors.
jaroslav@1692
    77
 *
jaroslav@1692
    78
 * <h1>Method handle compilation</h1>
jaroslav@1692
    79
 * A Java method call expression naming {@code invokeExact} or {@code invoke}
jaroslav@1692
    80
 * can invoke a method handle from Java source code.
jaroslav@1692
    81
 * From the viewpoint of source code, these methods can take any arguments
jaroslav@1692
    82
 * and their result can be cast to any return type.
jaroslav@1692
    83
 * Formally this is accomplished by giving the invoker methods
jaroslav@1692
    84
 * {@code Object} return types and variable arity {@code Object} arguments,
jaroslav@1692
    85
 * but they have an additional quality called <em>signature polymorphism</em>
jaroslav@1692
    86
 * which connects this freedom of invocation directly to the JVM execution stack.
jaroslav@1692
    87
 * <p>
jaroslav@1692
    88
 * As is usual with virtual methods, source-level calls to {@code invokeExact}
jaroslav@1692
    89
 * and {@code invoke} compile to an {@code invokevirtual} instruction.
jaroslav@1692
    90
 * More unusually, the compiler must record the actual argument types,
jaroslav@1692
    91
 * and may not perform method invocation conversions on the arguments.
jaroslav@1692
    92
 * Instead, it must push them on the stack according to their own unconverted types.
jaroslav@1692
    93
 * The method handle object itself is pushed on the stack before the arguments.
jaroslav@1692
    94
 * The compiler then calls the method handle with a symbolic type descriptor which
jaroslav@1692
    95
 * describes the argument and return types.
jaroslav@1692
    96
 * <p>
jaroslav@1692
    97
 * To issue a complete symbolic type descriptor, the compiler must also determine
jaroslav@1692
    98
 * the return type.  This is based on a cast on the method invocation expression,
jaroslav@1692
    99
 * if there is one, or else {@code Object} if the invocation is an expression
jaroslav@1692
   100
 * or else {@code void} if the invocation is a statement.
jaroslav@1692
   101
 * The cast may be to a primitive type (but not {@code void}).
jaroslav@1692
   102
 * <p>
jaroslav@1692
   103
 * As a corner case, an uncasted {@code null} argument is given
jaroslav@1692
   104
 * a symbolic type descriptor of {@code java.lang.Void}.
jaroslav@1692
   105
 * The ambiguity with the type {@code Void} is harmless, since there are no references of type
jaroslav@1692
   106
 * {@code Void} except the null reference.
jaroslav@1692
   107
 *
jaroslav@1692
   108
 * <h1>Method handle invocation</h1>
jaroslav@1692
   109
 * The first time a {@code invokevirtual} instruction is executed
jaroslav@1692
   110
 * it is linked, by symbolically resolving the names in the instruction
jaroslav@1692
   111
 * and verifying that the method call is statically legal.
jaroslav@1692
   112
 * This is true of calls to {@code invokeExact} and {@code invoke}.
jaroslav@1692
   113
 * In this case, the symbolic type descriptor emitted by the compiler is checked for
jaroslav@1692
   114
 * correct syntax and names it contains are resolved.
jaroslav@1692
   115
 * Thus, an {@code invokevirtual} instruction which invokes
jaroslav@1692
   116
 * a method handle will always link, as long
jaroslav@1692
   117
 * as the symbolic type descriptor is syntactically well-formed
jaroslav@1692
   118
 * and the types exist.
jaroslav@1692
   119
 * <p>
jaroslav@1692
   120
 * When the {@code invokevirtual} is executed after linking,
jaroslav@1692
   121
 * the receiving method handle's type is first checked by the JVM
jaroslav@1692
   122
 * to ensure that it matches the symbolic type descriptor.
jaroslav@1692
   123
 * If the type match fails, it means that the method which the
jaroslav@1692
   124
 * caller is invoking is not present on the individual
jaroslav@1692
   125
 * method handle being invoked.
jaroslav@1692
   126
 * <p>
jaroslav@1692
   127
 * In the case of {@code invokeExact}, the type descriptor of the invocation
jaroslav@1692
   128
 * (after resolving symbolic type names) must exactly match the method type
jaroslav@1692
   129
 * of the receiving method handle.
jaroslav@1692
   130
 * In the case of plain, inexact {@code invoke}, the resolved type descriptor
jaroslav@1692
   131
 * must be a valid argument to the receiver's {@link #asType asType} method.
jaroslav@1692
   132
 * Thus, plain {@code invoke} is more permissive than {@code invokeExact}.
jaroslav@1692
   133
 * <p>
jaroslav@1692
   134
 * After type matching, a call to {@code invokeExact} directly
jaroslav@1692
   135
 * and immediately invoke the method handle's underlying method
jaroslav@1692
   136
 * (or other behavior, as the case may be).
jaroslav@1692
   137
 * <p>
jaroslav@1692
   138
 * A call to plain {@code invoke} works the same as a call to
jaroslav@1692
   139
 * {@code invokeExact}, if the symbolic type descriptor specified by the caller
jaroslav@1692
   140
 * exactly matches the method handle's own type.
jaroslav@1692
   141
 * If there is a type mismatch, {@code invoke} attempts
jaroslav@1692
   142
 * to adjust the type of the receiving method handle,
jaroslav@1692
   143
 * as if by a call to {@link #asType asType},
jaroslav@1692
   144
 * to obtain an exactly invokable method handle {@code M2}.
jaroslav@1692
   145
 * This allows a more powerful negotiation of method type
jaroslav@1692
   146
 * between caller and callee.
jaroslav@1692
   147
 * <p>
jaroslav@1692
   148
 * (<em>Note:</em> The adjusted method handle {@code M2} is not directly observable,
jaroslav@1692
   149
 * and implementations are therefore not required to materialize it.)
jaroslav@1692
   150
 *
jaroslav@1692
   151
 * <h1>Invocation checking</h1>
jaroslav@1692
   152
 * In typical programs, method handle type matching will usually succeed.
jaroslav@1692
   153
 * But if a match fails, the JVM will throw a {@link WrongMethodTypeException},
jaroslav@1692
   154
 * either directly (in the case of {@code invokeExact}) or indirectly as if
jaroslav@1692
   155
 * by a failed call to {@code asType} (in the case of {@code invoke}).
jaroslav@1692
   156
 * <p>
jaroslav@1692
   157
 * Thus, a method type mismatch which might show up as a linkage error
jaroslav@1692
   158
 * in a statically typed program can show up as
jaroslav@1692
   159
 * a dynamic {@code WrongMethodTypeException}
jaroslav@1692
   160
 * in a program which uses method handles.
jaroslav@1692
   161
 * <p>
jaroslav@1692
   162
 * Because method types contain "live" {@code Class} objects,
jaroslav@1692
   163
 * method type matching takes into account both types names and class loaders.
jaroslav@1692
   164
 * Thus, even if a method handle {@code M} is created in one
jaroslav@1692
   165
 * class loader {@code L1} and used in another {@code L2},
jaroslav@1692
   166
 * method handle calls are type-safe, because the caller's symbolic type
jaroslav@1692
   167
 * descriptor, as resolved in {@code L2},
jaroslav@1692
   168
 * is matched against the original callee method's symbolic type descriptor,
jaroslav@1692
   169
 * as resolved in {@code L1}.
jaroslav@1692
   170
 * The resolution in {@code L1} happens when {@code M} is created
jaroslav@1692
   171
 * and its type is assigned, while the resolution in {@code L2} happens
jaroslav@1692
   172
 * when the {@code invokevirtual} instruction is linked.
jaroslav@1692
   173
 * <p>
jaroslav@1692
   174
 * Apart from the checking of type descriptors,
jaroslav@1692
   175
 * a method handle's capability to call its underlying method is unrestricted.
jaroslav@1692
   176
 * If a method handle is formed on a non-public method by a class
jaroslav@1692
   177
 * that has access to that method, the resulting handle can be used
jaroslav@1692
   178
 * in any place by any caller who receives a reference to it.
jaroslav@1692
   179
 * <p>
jaroslav@1692
   180
 * Unlike with the Core Reflection API, where access is checked every time
jaroslav@1692
   181
 * a reflective method is invoked,
jaroslav@1692
   182
 * method handle access checking is performed
jaroslav@1692
   183
 * <a href="MethodHandles.Lookup.html#access">when the method handle is created</a>.
jaroslav@1692
   184
 * In the case of {@code ldc} (see below), access checking is performed as part of linking
jaroslav@1692
   185
 * the constant pool entry underlying the constant method handle.
jaroslav@1692
   186
 * <p>
jaroslav@1692
   187
 * Thus, handles to non-public methods, or to methods in non-public classes,
jaroslav@1692
   188
 * should generally be kept secret.
jaroslav@1692
   189
 * They should not be passed to untrusted code unless their use from
jaroslav@1692
   190
 * the untrusted code would be harmless.
jaroslav@1692
   191
 *
jaroslav@1692
   192
 * <h1>Method handle creation</h1>
jaroslav@1692
   193
 * Java code can create a method handle that directly accesses
jaroslav@1692
   194
 * any method, constructor, or field that is accessible to that code.
jaroslav@1692
   195
 * This is done via a reflective, capability-based API called
jaroslav@1692
   196
 * {@link java.lang.invoke.MethodHandles.Lookup MethodHandles.Lookup}
jaroslav@1692
   197
 * For example, a static method handle can be obtained
jaroslav@1692
   198
 * from {@link java.lang.invoke.MethodHandles.Lookup#findStatic Lookup.findStatic}.
jaroslav@1692
   199
 * There are also conversion methods from Core Reflection API objects,
jaroslav@1692
   200
 * such as {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
jaroslav@1692
   201
 * <p>
jaroslav@1692
   202
 * Like classes and strings, method handles that correspond to accessible
jaroslav@1692
   203
 * fields, methods, and constructors can also be represented directly
jaroslav@1692
   204
 * in a class file's constant pool as constants to be loaded by {@code ldc} bytecodes.
jaroslav@1692
   205
 * A new type of constant pool entry, {@code CONSTANT_MethodHandle},
jaroslav@1692
   206
 * refers directly to an associated {@code CONSTANT_Methodref},
jaroslav@1692
   207
 * {@code CONSTANT_InterfaceMethodref}, or {@code CONSTANT_Fieldref}
jaroslav@1692
   208
 * constant pool entry.
jaroslav@1692
   209
 * (For full details on method handle constants,
jaroslav@1692
   210
 * see sections 4.4.8 and 5.4.3.5 of the Java Virtual Machine Specification.)
jaroslav@1692
   211
 * <p>
jaroslav@1692
   212
 * Method handles produced by lookups or constant loads from methods or
jaroslav@1692
   213
 * constructors with the variable arity modifier bit ({@code 0x0080})
jaroslav@1692
   214
 * have a corresponding variable arity, as if they were defined with
jaroslav@1692
   215
 * the help of {@link #asVarargsCollector asVarargsCollector}.
jaroslav@1692
   216
 * <p>
jaroslav@1692
   217
 * A method reference may refer either to a static or non-static method.
jaroslav@1692
   218
 * In the non-static case, the method handle type includes an explicit
jaroslav@1692
   219
 * receiver argument, prepended before any other arguments.
jaroslav@1692
   220
 * In the method handle's type, the initial receiver argument is typed
jaroslav@1692
   221
 * according to the class under which the method was initially requested.
jaroslav@1692
   222
 * (E.g., if a non-static method handle is obtained via {@code ldc},
jaroslav@1692
   223
 * the type of the receiver is the class named in the constant pool entry.)
jaroslav@1692
   224
 * <p>
jaroslav@1692
   225
 * Method handle constants are subject to the same link-time access checks
jaroslav@1692
   226
 * their corresponding bytecode instructions, and the {@code ldc} instruction
jaroslav@1692
   227
 * will throw corresponding linkage errors if the bytecode behaviors would
jaroslav@1692
   228
 * throw such errors.
jaroslav@1692
   229
 * <p>
jaroslav@1692
   230
 * As a corollary of this, access to protected members is restricted
jaroslav@1692
   231
 * to receivers only of the accessing class, or one of its subclasses,
jaroslav@1692
   232
 * and the accessing class must in turn be a subclass (or package sibling)
jaroslav@1692
   233
 * of the protected member's defining class.
jaroslav@1692
   234
 * If a method reference refers to a protected non-static method or field
jaroslav@1692
   235
 * of a class outside the current package, the receiver argument will
jaroslav@1692
   236
 * be narrowed to the type of the accessing class.
jaroslav@1692
   237
 * <p>
jaroslav@1692
   238
 * When a method handle to a virtual method is invoked, the method is
jaroslav@1692
   239
 * always looked up in the receiver (that is, the first argument).
jaroslav@1692
   240
 * <p>
jaroslav@1692
   241
 * A non-virtual method handle to a specific virtual method implementation
jaroslav@1692
   242
 * can also be created.  These do not perform virtual lookup based on
jaroslav@1692
   243
 * receiver type.  Such a method handle simulates the effect of
jaroslav@1692
   244
 * an {@code invokespecial} instruction to the same method.
jaroslav@1692
   245
 *
jaroslav@1692
   246
 * <h1>Usage examples</h1>
jaroslav@1692
   247
 * Here are some examples of usage:
jaroslav@1692
   248
 * <blockquote><pre>{@code
jaroslav@1692
   249
Object x, y; String s; int i;
jaroslav@1692
   250
MethodType mt; MethodHandle mh;
jaroslav@1692
   251
MethodHandles.Lookup lookup = MethodHandles.lookup();
jaroslav@1692
   252
// mt is (char,char)String
jaroslav@1692
   253
mt = MethodType.methodType(String.class, char.class, char.class);
jaroslav@1692
   254
mh = lookup.findVirtual(String.class, "replace", mt);
jaroslav@1692
   255
s = (String) mh.invokeExact("daddy",'d','n');
jaroslav@1692
   256
// invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
jaroslav@1692
   257
assertEquals(s, "nanny");
jaroslav@1692
   258
// weakly typed invocation (using MHs.invoke)
jaroslav@1692
   259
s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
jaroslav@1692
   260
assertEquals(s, "savvy");
jaroslav@1692
   261
// mt is (Object[])List
jaroslav@1692
   262
mt = MethodType.methodType(java.util.List.class, Object[].class);
jaroslav@1692
   263
mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
jaroslav@1692
   264
assert(mh.isVarargsCollector());
jaroslav@1692
   265
x = mh.invoke("one", "two");
jaroslav@1692
   266
// invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
jaroslav@1692
   267
assertEquals(x, java.util.Arrays.asList("one","two"));
jaroslav@1692
   268
// mt is (Object,Object,Object)Object
jaroslav@1692
   269
mt = MethodType.genericMethodType(3);
jaroslav@1692
   270
mh = mh.asType(mt);
jaroslav@1692
   271
x = mh.invokeExact((Object)1, (Object)2, (Object)3);
jaroslav@1692
   272
// invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
jaroslav@1692
   273
assertEquals(x, java.util.Arrays.asList(1,2,3));
jaroslav@1692
   274
// mt is ()int
jaroslav@1692
   275
mt = MethodType.methodType(int.class);
jaroslav@1692
   276
mh = lookup.findVirtual(java.util.List.class, "size", mt);
jaroslav@1692
   277
i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
jaroslav@1692
   278
// invokeExact(Ljava/util/List;)I
jaroslav@1692
   279
assert(i == 3);
jaroslav@1692
   280
mt = MethodType.methodType(void.class, String.class);
jaroslav@1692
   281
mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
jaroslav@1692
   282
mh.invokeExact(System.out, "Hello, world.");
jaroslav@1692
   283
// invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
jaroslav@1692
   284
 * }</pre></blockquote>
jaroslav@1692
   285
 * Each of the above calls to {@code invokeExact} or plain {@code invoke}
jaroslav@1692
   286
 * generates a single invokevirtual instruction with
jaroslav@1692
   287
 * the symbolic type descriptor indicated in the following comment.
jaroslav@1692
   288
 * In these examples, the helper method {@code assertEquals} is assumed to
jaroslav@1692
   289
 * be a method which calls {@link java.util.Objects#equals(Object,Object) Objects.equals}
jaroslav@1692
   290
 * on its arguments, and asserts that the result is true.
jaroslav@1692
   291
 *
jaroslav@1692
   292
 * <h1>Exceptions</h1>
jaroslav@1692
   293
 * The methods {@code invokeExact} and {@code invoke} are declared
jaroslav@1692
   294
 * to throw {@link java.lang.Throwable Throwable},
jaroslav@1692
   295
 * which is to say that there is no static restriction on what a method handle
jaroslav@1692
   296
 * can throw.  Since the JVM does not distinguish between checked
jaroslav@1692
   297
 * and unchecked exceptions (other than by their class, of course),
jaroslav@1692
   298
 * there is no particular effect on bytecode shape from ascribing
jaroslav@1692
   299
 * checked exceptions to method handle invocations.  But in Java source
jaroslav@1692
   300
 * code, methods which perform method handle calls must either explicitly
jaroslav@1692
   301
 * throw {@code Throwable}, or else must catch all
jaroslav@1692
   302
 * throwables locally, rethrowing only those which are legal in the context,
jaroslav@1692
   303
 * and wrapping ones which are illegal.
jaroslav@1692
   304
 *
jaroslav@1692
   305
 * <h1><a name="sigpoly"></a>Signature polymorphism</h1>
jaroslav@1692
   306
 * The unusual compilation and linkage behavior of
jaroslav@1692
   307
 * {@code invokeExact} and plain {@code invoke}
jaroslav@1692
   308
 * is referenced by the term <em>signature polymorphism</em>.
jaroslav@1692
   309
 * As defined in the Java Language Specification,
jaroslav@1692
   310
 * a signature polymorphic method is one which can operate with
jaroslav@1692
   311
 * any of a wide range of call signatures and return types.
jaroslav@1692
   312
 * <p>
jaroslav@1692
   313
 * In source code, a call to a signature polymorphic method will
jaroslav@1692
   314
 * compile, regardless of the requested symbolic type descriptor.
jaroslav@1692
   315
 * As usual, the Java compiler emits an {@code invokevirtual}
jaroslav@1692
   316
 * instruction with the given symbolic type descriptor against the named method.
jaroslav@1692
   317
 * The unusual part is that the symbolic type descriptor is derived from
jaroslav@1692
   318
 * the actual argument and return types, not from the method declaration.
jaroslav@1692
   319
 * <p>
jaroslav@1692
   320
 * When the JVM processes bytecode containing signature polymorphic calls,
jaroslav@1692
   321
 * it will successfully link any such call, regardless of its symbolic type descriptor.
jaroslav@1692
   322
 * (In order to retain type safety, the JVM will guard such calls with suitable
jaroslav@1692
   323
 * dynamic type checks, as described elsewhere.)
jaroslav@1692
   324
 * <p>
jaroslav@1692
   325
 * Bytecode generators, including the compiler back end, are required to emit
jaroslav@1692
   326
 * untransformed symbolic type descriptors for these methods.
jaroslav@1692
   327
 * Tools which determine symbolic linkage are required to accept such
jaroslav@1692
   328
 * untransformed descriptors, without reporting linkage errors.
jaroslav@1692
   329
 *
jaroslav@1692
   330
 * <h1>Interoperation between method handles and the Core Reflection API</h1>
jaroslav@1692
   331
 * Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup Lookup} API,
jaroslav@1692
   332
 * any class member represented by a Core Reflection API object
jaroslav@1692
   333
 * can be converted to a behaviorally equivalent method handle.
jaroslav@1692
   334
 * For example, a reflective {@link java.lang.reflect.Method Method} can
jaroslav@1692
   335
 * be converted to a method handle using
jaroslav@1692
   336
 * {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
jaroslav@1692
   337
 * The resulting method handles generally provide more direct and efficient
jaroslav@1692
   338
 * access to the underlying class members.
jaroslav@1692
   339
 * <p>
jaroslav@1692
   340
 * As a special case,
jaroslav@1692
   341
 * when the Core Reflection API is used to view the signature polymorphic
jaroslav@1692
   342
 * methods {@code invokeExact} or plain {@code invoke} in this class,
jaroslav@1692
   343
 * they appear as ordinary non-polymorphic methods.
jaroslav@1692
   344
 * Their reflective appearance, as viewed by
jaroslav@1692
   345
 * {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod},
jaroslav@1692
   346
 * is unaffected by their special status in this API.
jaroslav@1692
   347
 * For example, {@link java.lang.reflect.Method#getModifiers Method.getModifiers}
jaroslav@1692
   348
 * will report exactly those modifier bits required for any similarly
jaroslav@1692
   349
 * declared method, including in this case {@code native} and {@code varargs} bits.
jaroslav@1692
   350
 * <p>
jaroslav@1692
   351
 * As with any reflected method, these methods (when reflected) may be
jaroslav@1692
   352
 * invoked via {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.
jaroslav@1692
   353
 * However, such reflective calls do not result in method handle invocations.
jaroslav@1692
   354
 * Such a call, if passed the required argument
jaroslav@1692
   355
 * (a single one, of type {@code Object[]}), will ignore the argument and
jaroslav@1692
   356
 * will throw an {@code UnsupportedOperationException}.
jaroslav@1692
   357
 * <p>
jaroslav@1692
   358
 * Since {@code invokevirtual} instructions can natively
jaroslav@1692
   359
 * invoke method handles under any symbolic type descriptor, this reflective view conflicts
jaroslav@1692
   360
 * with the normal presentation of these methods via bytecodes.
jaroslav@1692
   361
 * Thus, these two native methods, when reflectively viewed by
jaroslav@1692
   362
 * {@code Class.getDeclaredMethod}, may be regarded as placeholders only.
jaroslav@1692
   363
 * <p>
jaroslav@1692
   364
 * In order to obtain an invoker method for a particular type descriptor,
jaroslav@1692
   365
 * use {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker},
jaroslav@1692
   366
 * or {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}.
jaroslav@1692
   367
 * The {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual}
jaroslav@1692
   368
 * API is also able to return a method handle
jaroslav@1692
   369
 * to call {@code invokeExact} or plain {@code invoke},
jaroslav@1692
   370
 * for any specified type descriptor .
jaroslav@1692
   371
 *
jaroslav@1692
   372
 * <h1>Interoperation between method handles and Java generics</h1>
jaroslav@1692
   373
 * A method handle can be obtained on a method, constructor, or field
jaroslav@1692
   374
 * which is declared with Java generic types.
jaroslav@1692
   375
 * As with the Core Reflection API, the type of the method handle
jaroslav@1692
   376
 * will constructed from the erasure of the source-level type.
jaroslav@1692
   377
 * When a method handle is invoked, the types of its arguments
jaroslav@1692
   378
 * or the return value cast type may be generic types or type instances.
jaroslav@1692
   379
 * If this occurs, the compiler will replace those
jaroslav@1692
   380
 * types by their erasures when it constructs the symbolic type descriptor
jaroslav@1692
   381
 * for the {@code invokevirtual} instruction.
jaroslav@1692
   382
 * <p>
jaroslav@1692
   383
 * Method handles do not represent
jaroslav@1692
   384
 * their function-like types in terms of Java parameterized (generic) types,
jaroslav@1692
   385
 * because there are three mismatches between function-like types and parameterized
jaroslav@1692
   386
 * Java types.
jaroslav@1692
   387
 * <ul>
jaroslav@1692
   388
 * <li>Method types range over all possible arities,
jaroslav@1692
   389
 * from no arguments to up to the  <a href="MethodHandle.html#maxarity">maximum number</a> of allowed arguments.
jaroslav@1692
   390
 * Generics are not variadic, and so cannot represent this.</li>
jaroslav@1692
   391
 * <li>Method types can specify arguments of primitive types,
jaroslav@1692
   392
 * which Java generic types cannot range over.</li>
jaroslav@1692
   393
 * <li>Higher order functions over method handles (combinators) are
jaroslav@1692
   394
 * often generic across a wide range of function types, including
jaroslav@1692
   395
 * those of multiple arities.  It is impossible to represent such
jaroslav@1692
   396
 * genericity with a Java type parameter.</li>
jaroslav@1692
   397
 * </ul>
jaroslav@1692
   398
 *
jaroslav@1692
   399
 * <h1><a name="maxarity"></a>Arity limits</h1>
jaroslav@1692
   400
 * The JVM imposes on all methods and constructors of any kind an absolute
jaroslav@1692
   401
 * limit of 255 stacked arguments.  This limit can appear more restrictive
jaroslav@1692
   402
 * in certain cases:
jaroslav@1692
   403
 * <ul>
jaroslav@1692
   404
 * <li>A {@code long} or {@code double} argument counts (for purposes of arity limits) as two argument slots.
jaroslav@1692
   405
 * <li>A non-static method consumes an extra argument for the object on which the method is called.
jaroslav@1692
   406
 * <li>A constructor consumes an extra argument for the object which is being constructed.
jaroslav@1692
   407
 * <li>Since a method handle&rsquo;s {@code invoke} method (or other signature-polymorphic method) is non-virtual,
jaroslav@1692
   408
 *     it consumes an extra argument for the method handle itself, in addition to any non-virtual receiver object.
jaroslav@1692
   409
 * </ul>
jaroslav@1692
   410
 * These limits imply that certain method handles cannot be created, solely because of the JVM limit on stacked arguments.
jaroslav@1692
   411
 * For example, if a static JVM method accepts exactly 255 arguments, a method handle cannot be created for it.
jaroslav@1692
   412
 * Attempts to create method handles with impossible method types lead to an {@link IllegalArgumentException}.
jaroslav@1692
   413
 * In particular, a method handle&rsquo;s type must not have an arity of the exact maximum 255.
jaroslav@1692
   414
 *
jaroslav@1692
   415
 * @see MethodType
jaroslav@1692
   416
 * @see MethodHandles
jaroslav@1692
   417
 * @author John Rose, JSR 292 EG
jaroslav@1692
   418
 */
jaroslav@1692
   419
public abstract class MethodHandle {
jaroslav@1692
   420
    /**
jaroslav@1692
   421
     * Internal marker interface which distinguishes (to the Java compiler)
jaroslav@1692
   422
     * those methods which are <a href="MethodHandle.html#sigpoly">signature polymorphic</a>.
jaroslav@1692
   423
     */
jaroslav@1692
   424
    @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
jaroslav@1692
   425
    @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
jaroslav@1692
   426
    @interface PolymorphicSignature { }
jaroslav@1692
   427
jaroslav@1692
   428
    /**
jaroslav@1692
   429
     * Reports the type of this method handle.
jaroslav@1692
   430
     * Every invocation of this method handle via {@code invokeExact} must exactly match this type.
jaroslav@1692
   431
     * @return the method handle type
jaroslav@1692
   432
     */
jaroslav@1692
   433
    public MethodType type() {
jaroslav@1692
   434
        throw new IllegalStateException();
jaroslav@1692
   435
    }
jaroslav@1692
   436
jaroslav@1692
   437
    /**
jaroslav@1692
   438
     * Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match.
jaroslav@1692
   439
     * The symbolic type descriptor at the call site of {@code invokeExact} must
jaroslav@1692
   440
     * exactly match this method handle's {@link #type type}.
jaroslav@1692
   441
     * No conversions are allowed on arguments or return values.
jaroslav@1692
   442
     * <p>
jaroslav@1692
   443
     * When this method is observed via the Core Reflection API,
jaroslav@1692
   444
     * it will appear as a single native method, taking an object array and returning an object.
jaroslav@1692
   445
     * If this native method is invoked directly via
jaroslav@1692
   446
     * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
jaroslav@1692
   447
     * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
jaroslav@1692
   448
     * it will throw an {@code UnsupportedOperationException}.
jaroslav@1692
   449
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1692
   450
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1692
   451
     * @throws WrongMethodTypeException if the target's type is not identical with the caller's symbolic type descriptor
jaroslav@1692
   452
     * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
jaroslav@1692
   453
     */
jaroslav@1692
   454
    public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable;
jaroslav@1692
   455
jaroslav@1692
   456
    /**
jaroslav@1692
   457
     * Invokes the method handle, allowing any caller type descriptor,
jaroslav@1692
   458
     * and optionally performing conversions on arguments and return values.
jaroslav@1692
   459
     * <p>
jaroslav@1692
   460
     * If the call site's symbolic type descriptor exactly matches this method handle's {@link #type type},
jaroslav@1692
   461
     * the call proceeds as if by {@link #invokeExact invokeExact}.
jaroslav@1692
   462
     * <p>
jaroslav@1692
   463
     * Otherwise, the call proceeds as if this method handle were first
jaroslav@1692
   464
     * adjusted by calling {@link #asType asType} to adjust this method handle
jaroslav@1692
   465
     * to the required type, and then the call proceeds as if by
jaroslav@1692
   466
     * {@link #invokeExact invokeExact} on the adjusted method handle.
jaroslav@1692
   467
     * <p>
jaroslav@1692
   468
     * There is no guarantee that the {@code asType} call is actually made.
jaroslav@1692
   469
     * If the JVM can predict the results of making the call, it may perform
jaroslav@1692
   470
     * adaptations directly on the caller's arguments,
jaroslav@1692
   471
     * and call the target method handle according to its own exact type.
jaroslav@1692
   472
     * <p>
jaroslav@1692
   473
     * The resolved type descriptor at the call site of {@code invoke} must
jaroslav@1692
   474
     * be a valid argument to the receivers {@code asType} method.
jaroslav@1692
   475
     * In particular, the caller must specify the same argument arity
jaroslav@1692
   476
     * as the callee's type,
jaroslav@1692
   477
     * if the callee is not a {@linkplain #asVarargsCollector variable arity collector}.
jaroslav@1692
   478
     * <p>
jaroslav@1692
   479
     * When this method is observed via the Core Reflection API,
jaroslav@1692
   480
     * it will appear as a single native method, taking an object array and returning an object.
jaroslav@1692
   481
     * If this native method is invoked directly via
jaroslav@1692
   482
     * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
jaroslav@1692
   483
     * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
jaroslav@1692
   484
     * it will throw an {@code UnsupportedOperationException}.
jaroslav@1692
   485
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1692
   486
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1692
   487
     * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's symbolic type descriptor
jaroslav@1692
   488
     * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails
jaroslav@1692
   489
     * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
jaroslav@1692
   490
     */
jaroslav@1692
   491
    public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable;
jaroslav@1692
   492
jaroslav@1692
   493
    /**
jaroslav@1692
   494
     * Private method for trusted invocation of a method handle respecting simplified signatures.
jaroslav@1692
   495
     * Type mismatches will not throw {@code WrongMethodTypeException}, but could crash the JVM.
jaroslav@1692
   496
     * <p>
jaroslav@1692
   497
     * The caller signature is restricted to the following basic types:
jaroslav@1692
   498
     * Object, int, long, float, double, and void return.
jaroslav@1692
   499
     * <p>
jaroslav@1692
   500
     * The caller is responsible for maintaining type correctness by ensuring
jaroslav@1692
   501
     * that the each outgoing argument value is a member of the range of the corresponding
jaroslav@1692
   502
     * callee argument type.
jaroslav@1692
   503
     * (The caller should therefore issue appropriate casts and integer narrowing
jaroslav@1692
   504
     * operations on outgoing argument values.)
jaroslav@1692
   505
     * The caller can assume that the incoming result value is part of the range
jaroslav@1692
   506
     * of the callee's return type.
jaroslav@1692
   507
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1692
   508
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1692
   509
     */
jaroslav@1692
   510
    /*non-public*/ final native @PolymorphicSignature Object invokeBasic(Object... args) throws Throwable;
jaroslav@1692
   511
jaroslav@1692
   512
    /**
jaroslav@1692
   513
     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeVirtual}.
jaroslav@1692
   514
     * The caller signature is restricted to basic types as with {@code invokeBasic}.
jaroslav@1692
   515
     * The trailing (not leading) argument must be a MemberName.
jaroslav@1692
   516
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1692
   517
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1692
   518
     */
jaroslav@1692
   519
    /*non-public*/ static native @PolymorphicSignature Object linkToVirtual(Object... args) throws Throwable;
jaroslav@1692
   520
jaroslav@1692
   521
    /**
jaroslav@1692
   522
     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeStatic}.
jaroslav@1692
   523
     * The caller signature is restricted to basic types as with {@code invokeBasic}.
jaroslav@1692
   524
     * The trailing (not leading) argument must be a MemberName.
jaroslav@1692
   525
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1692
   526
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1692
   527
     */
jaroslav@1692
   528
    /*non-public*/ static native @PolymorphicSignature Object linkToStatic(Object... args) throws Throwable;
jaroslav@1692
   529
jaroslav@1692
   530
    /**
jaroslav@1692
   531
     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeSpecial}.
jaroslav@1692
   532
     * The caller signature is restricted to basic types as with {@code invokeBasic}.
jaroslav@1692
   533
     * The trailing (not leading) argument must be a MemberName.
jaroslav@1692
   534
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1692
   535
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1692
   536
     */
jaroslav@1692
   537
    /*non-public*/ static native @PolymorphicSignature Object linkToSpecial(Object... args) throws Throwable;
jaroslav@1692
   538
jaroslav@1692
   539
    /**
jaroslav@1692
   540
     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeInterface}.
jaroslav@1692
   541
     * The caller signature is restricted to basic types as with {@code invokeBasic}.
jaroslav@1692
   542
     * The trailing (not leading) argument must be a MemberName.
jaroslav@1692
   543
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1692
   544
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1692
   545
     */
jaroslav@1692
   546
    /*non-public*/ static native @PolymorphicSignature Object linkToInterface(Object... args) throws Throwable;
jaroslav@1692
   547
jaroslav@1692
   548
    /**
jaroslav@1692
   549
     * Performs a variable arity invocation, passing the arguments in the given list
jaroslav@1692
   550
     * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
jaroslav@1692
   551
     * which mentions only the type {@code Object}, and whose arity is the length
jaroslav@1692
   552
     * of the argument list.
jaroslav@1692
   553
     * <p>
jaroslav@1692
   554
     * Specifically, execution proceeds as if by the following steps,
jaroslav@1692
   555
     * although the methods are not guaranteed to be called if the JVM
jaroslav@1692
   556
     * can predict their effects.
jaroslav@1692
   557
     * <ul>
jaroslav@1692
   558
     * <li>Determine the length of the argument array as {@code N}.
jaroslav@1692
   559
     *     For a null reference, {@code N=0}. </li>
jaroslav@1692
   560
     * <li>Determine the general type {@code TN} of {@code N} arguments as
jaroslav@1692
   561
     *     as {@code TN=MethodType.genericMethodType(N)}.</li>
jaroslav@1692
   562
     * <li>Force the original target method handle {@code MH0} to the
jaroslav@1692
   563
     *     required type, as {@code MH1 = MH0.asType(TN)}. </li>
jaroslav@1692
   564
     * <li>Spread the array into {@code N} separate arguments {@code A0, ...}. </li>
jaroslav@1692
   565
     * <li>Invoke the type-adjusted method handle on the unpacked arguments:
jaroslav@1692
   566
     *     MH1.invokeExact(A0, ...). </li>
jaroslav@1692
   567
     * <li>Take the return value as an {@code Object} reference. </li>
jaroslav@1692
   568
     * </ul>
jaroslav@1692
   569
     * <p>
jaroslav@1692
   570
     * Because of the action of the {@code asType} step, the following argument
jaroslav@1692
   571
     * conversions are applied as necessary:
jaroslav@1692
   572
     * <ul>
jaroslav@1692
   573
     * <li>reference casting
jaroslav@1692
   574
     * <li>unboxing
jaroslav@1692
   575
     * <li>widening primitive conversions
jaroslav@1692
   576
     * </ul>
jaroslav@1692
   577
     * <p>
jaroslav@1692
   578
     * The result returned by the call is boxed if it is a primitive,
jaroslav@1692
   579
     * or forced to null if the return type is void.
jaroslav@1692
   580
     * <p>
jaroslav@1692
   581
     * This call is equivalent to the following code:
jaroslav@1692
   582
     * <blockquote><pre>{@code
jaroslav@1692
   583
     * MethodHandle invoker = MethodHandles.spreadInvoker(this.type(), 0);
jaroslav@1692
   584
     * Object result = invoker.invokeExact(this, arguments);
jaroslav@1692
   585
     * }</pre></blockquote>
jaroslav@1692
   586
     * <p>
jaroslav@1692
   587
     * Unlike the signature polymorphic methods {@code invokeExact} and {@code invoke},
jaroslav@1692
   588
     * {@code invokeWithArguments} can be accessed normally via the Core Reflection API and JNI.
jaroslav@1692
   589
     * It can therefore be used as a bridge between native or reflective code and method handles.
jaroslav@1692
   590
     *
jaroslav@1692
   591
     * @param arguments the arguments to pass to the target
jaroslav@1692
   592
     * @return the result returned by the target
jaroslav@1692
   593
     * @throws ClassCastException if an argument cannot be converted by reference casting
jaroslav@1692
   594
     * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
jaroslav@1692
   595
     * @throws Throwable anything thrown by the target method invocation
jaroslav@1692
   596
     * @see MethodHandles#spreadInvoker
jaroslav@1692
   597
     */
jaroslav@1692
   598
    public Object invokeWithArguments(Object... arguments) throws Throwable {
jaroslav@1692
   599
        throw new IllegalStateException();
jaroslav@1692
   600
    }
jaroslav@1692
   601
jaroslav@1692
   602
    /**
jaroslav@1692
   603
     * Performs a variable arity invocation, passing the arguments in the given array
jaroslav@1692
   604
     * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
jaroslav@1692
   605
     * which mentions only the type {@code Object}, and whose arity is the length
jaroslav@1692
   606
     * of the argument array.
jaroslav@1692
   607
     * <p>
jaroslav@1692
   608
     * This method is also equivalent to the following code:
jaroslav@1692
   609
     * <blockquote><pre>{@code
jaroslav@1692
   610
     *   invokeWithArguments(arguments.toArray()
jaroslav@1692
   611
     * }</pre></blockquote>
jaroslav@1692
   612
     *
jaroslav@1692
   613
     * @param arguments the arguments to pass to the target
jaroslav@1692
   614
     * @return the result returned by the target
jaroslav@1692
   615
     * @throws NullPointerException if {@code arguments} is a null reference
jaroslav@1692
   616
     * @throws ClassCastException if an argument cannot be converted by reference casting
jaroslav@1692
   617
     * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
jaroslav@1692
   618
     * @throws Throwable anything thrown by the target method invocation
jaroslav@1692
   619
     */
jaroslav@1692
   620
    public Object invokeWithArguments(java.util.List<?> arguments) throws Throwable {
jaroslav@1692
   621
        return invokeWithArguments(arguments.toArray());
jaroslav@1692
   622
    }
jaroslav@1692
   623
jaroslav@1692
   624
    /**
jaroslav@1692
   625
     * Produces an adapter method handle which adapts the type of the
jaroslav@1692
   626
     * current method handle to a new type.
jaroslav@1692
   627
     * The resulting method handle is guaranteed to report a type
jaroslav@1692
   628
     * which is equal to the desired new type.
jaroslav@1692
   629
     * <p>
jaroslav@1692
   630
     * If the original type and new type are equal, returns {@code this}.
jaroslav@1692
   631
     * <p>
jaroslav@1692
   632
     * The new method handle, when invoked, will perform the following
jaroslav@1692
   633
     * steps:
jaroslav@1692
   634
     * <ul>
jaroslav@1692
   635
     * <li>Convert the incoming argument list to match the original
jaroslav@1692
   636
     *     method handle's argument list.
jaroslav@1692
   637
     * <li>Invoke the original method handle on the converted argument list.
jaroslav@1692
   638
     * <li>Convert any result returned by the original method handle
jaroslav@1692
   639
     *     to the return type of new method handle.
jaroslav@1692
   640
     * </ul>
jaroslav@1692
   641
     * <p>
jaroslav@1692
   642
     * This method provides the crucial behavioral difference between
jaroslav@1692
   643
     * {@link #invokeExact invokeExact} and plain, inexact {@link #invoke invoke}.
jaroslav@1692
   644
     * The two methods
jaroslav@1692
   645
     * perform the same steps when the caller's type descriptor exactly m atches
jaroslav@1692
   646
     * the callee's, but when the types differ, plain {@link #invoke invoke}
jaroslav@1692
   647
     * also calls {@code asType} (or some internal equivalent) in order
jaroslav@1692
   648
     * to match up the caller's and callee's types.
jaroslav@1692
   649
     * <p>
jaroslav@1692
   650
     * If the current method is a variable arity method handle
jaroslav@1692
   651
     * argument list conversion may involve the conversion and collection
jaroslav@1692
   652
     * of several arguments into an array, as
jaroslav@1692
   653
     * {@linkplain #asVarargsCollector described elsewhere}.
jaroslav@1692
   654
     * In every other case, all conversions are applied <em>pairwise</em>,
jaroslav@1692
   655
     * which means that each argument or return value is converted to
jaroslav@1692
   656
     * exactly one argument or return value (or no return value).
jaroslav@1692
   657
     * The applied conversions are defined by consulting the
jaroslav@1692
   658
     * the corresponding component types of the old and new
jaroslav@1692
   659
     * method handle types.
jaroslav@1692
   660
     * <p>
jaroslav@1692
   661
     * Let <em>T0</em> and <em>T1</em> be corresponding new and old parameter types,
jaroslav@1692
   662
     * or old and new return types.  Specifically, for some valid index {@code i}, let
jaroslav@1692
   663
     * <em>T0</em>{@code =newType.parameterType(i)} and <em>T1</em>{@code =this.type().parameterType(i)}.
jaroslav@1692
   664
     * Or else, going the other way for return values, let
jaroslav@1692
   665
     * <em>T0</em>{@code =this.type().returnType()} and <em>T1</em>{@code =newType.returnType()}.
jaroslav@1692
   666
     * If the types are the same, the new method handle makes no change
jaroslav@1692
   667
     * to the corresponding argument or return value (if any).
jaroslav@1692
   668
     * Otherwise, one of the following conversions is applied
jaroslav@1692
   669
     * if possible:
jaroslav@1692
   670
     * <ul>
jaroslav@1692
   671
     * <li>If <em>T0</em> and <em>T1</em> are references, then a cast to <em>T1</em> is applied.
jaroslav@1692
   672
     *     (The types do not need to be related in any particular way.
jaroslav@1692
   673
     *     This is because a dynamic value of null can convert to any reference type.)
jaroslav@1692
   674
     * <li>If <em>T0</em> and <em>T1</em> are primitives, then a Java method invocation
jaroslav@1692
   675
     *     conversion (JLS 5.3) is applied, if one exists.
jaroslav@1692
   676
     *     (Specifically, <em>T0</em> must convert to <em>T1</em> by a widening primitive conversion.)
jaroslav@1692
   677
     * <li>If <em>T0</em> is a primitive and <em>T1</em> a reference,
jaroslav@1692
   678
     *     a Java casting conversion (JLS 5.5) is applied if one exists.
jaroslav@1692
   679
     *     (Specifically, the value is boxed from <em>T0</em> to its wrapper class,
jaroslav@1692
   680
     *     which is then widened as needed to <em>T1</em>.)
jaroslav@1692
   681
     * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
jaroslav@1692
   682
     *     conversion will be applied at runtime, possibly followed
jaroslav@1692
   683
     *     by a Java method invocation conversion (JLS 5.3)
jaroslav@1692
   684
     *     on the primitive value.  (These are the primitive widening conversions.)
jaroslav@1692
   685
     *     <em>T0</em> must be a wrapper class or a supertype of one.
jaroslav@1692
   686
     *     (In the case where <em>T0</em> is Object, these are the conversions
jaroslav@1692
   687
     *     allowed by {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.)
jaroslav@1692
   688
     *     The unboxing conversion must have a possibility of success, which means that
jaroslav@1692
   689
     *     if <em>T0</em> is not itself a wrapper class, there must exist at least one
jaroslav@1692
   690
     *     wrapper class <em>TW</em> which is a subtype of <em>T0</em> and whose unboxed
jaroslav@1692
   691
     *     primitive value can be widened to <em>T1</em>.
jaroslav@1692
   692
     * <li>If the return type <em>T1</em> is marked as void, any returned value is discarded
jaroslav@1692
   693
     * <li>If the return type <em>T0</em> is void and <em>T1</em> a reference, a null value is introduced.
jaroslav@1692
   694
     * <li>If the return type <em>T0</em> is void and <em>T1</em> a primitive,
jaroslav@1692
   695
     *     a zero value is introduced.
jaroslav@1692
   696
     * </ul>
jaroslav@1692
   697
    * (<em>Note:</em> Both <em>T0</em> and <em>T1</em> may be regarded as static types,
jaroslav@1692
   698
     * because neither corresponds specifically to the <em>dynamic type</em> of any
jaroslav@1692
   699
     * actual argument or return value.)
jaroslav@1692
   700
     * <p>
jaroslav@1692
   701
     * The method handle conversion cannot be made if any one of the required
jaroslav@1692
   702
     * pairwise conversions cannot be made.
jaroslav@1692
   703
     * <p>
jaroslav@1692
   704
     * At runtime, the conversions applied to reference arguments
jaroslav@1692
   705
     * or return values may require additional runtime checks which can fail.
jaroslav@1692
   706
     * An unboxing operation may fail because the original reference is null,
jaroslav@1692
   707
     * causing a {@link java.lang.NullPointerException NullPointerException}.
jaroslav@1692
   708
     * An unboxing operation or a reference cast may also fail on a reference
jaroslav@1692
   709
     * to an object of the wrong type,
jaroslav@1692
   710
     * causing a {@link java.lang.ClassCastException ClassCastException}.
jaroslav@1692
   711
     * Although an unboxing operation may accept several kinds of wrappers,
jaroslav@1692
   712
     * if none are available, a {@code ClassCastException} will be thrown.
jaroslav@1692
   713
     *
jaroslav@1692
   714
     * @param newType the expected type of the new method handle
jaroslav@1692
   715
     * @return a method handle which delegates to {@code this} after performing
jaroslav@1692
   716
     *           any necessary argument conversions, and arranges for any
jaroslav@1692
   717
     *           necessary return value conversions
jaroslav@1692
   718
     * @throws NullPointerException if {@code newType} is a null reference
jaroslav@1692
   719
     * @throws WrongMethodTypeException if the conversion cannot be made
jaroslav@1692
   720
     * @see MethodHandles#explicitCastArguments
jaroslav@1692
   721
     */
jaroslav@1692
   722
    public MethodHandle asType(MethodType newType) {
jaroslav@1692
   723
        throw new IllegalStateException();
jaroslav@1692
   724
    }
jaroslav@1692
   725
jaroslav@1692
   726
    /**
jaroslav@1692
   727
     * Makes an <em>array-spreading</em> method handle, which accepts a trailing array argument
jaroslav@1692
   728
     * and spreads its elements as positional arguments.
jaroslav@1692
   729
     * The new method handle adapts, as its <i>target</i>,
jaroslav@1692
   730
     * the current method handle.  The type of the adapter will be
jaroslav@1692
   731
     * the same as the type of the target, except that the final
jaroslav@1692
   732
     * {@code arrayLength} parameters of the target's type are replaced
jaroslav@1692
   733
     * by a single array parameter of type {@code arrayType}.
jaroslav@1692
   734
     * <p>
jaroslav@1692
   735
     * If the array element type differs from any of the corresponding
jaroslav@1692
   736
     * argument types on the original target,
jaroslav@1692
   737
     * the original target is adapted to take the array elements directly,
jaroslav@1692
   738
     * as if by a call to {@link #asType asType}.
jaroslav@1692
   739
     * <p>
jaroslav@1692
   740
     * When called, the adapter replaces a trailing array argument
jaroslav@1692
   741
     * by the array's elements, each as its own argument to the target.
jaroslav@1692
   742
     * (The order of the arguments is preserved.)
jaroslav@1692
   743
     * They are converted pairwise by casting and/or unboxing
jaroslav@1692
   744
     * to the types of the trailing parameters of the target.
jaroslav@1692
   745
     * Finally the target is called.
jaroslav@1692
   746
     * What the target eventually returns is returned unchanged by the adapter.
jaroslav@1692
   747
     * <p>
jaroslav@1692
   748
     * Before calling the target, the adapter verifies that the array
jaroslav@1692
   749
     * contains exactly enough elements to provide a correct argument count
jaroslav@1692
   750
     * to the target method handle.
jaroslav@1692
   751
     * (The array may also be null when zero elements are required.)
jaroslav@1692
   752
     * <p>
jaroslav@1692
   753
     * If, when the adapter is called, the supplied array argument does
jaroslav@1692
   754
     * not have the correct number of elements, the adapter will throw
jaroslav@1692
   755
     * an {@link IllegalArgumentException} instead of invoking the target.
jaroslav@1692
   756
     * <p>
jaroslav@1692
   757
     * Here are some simple examples of array-spreading method handles:
jaroslav@1692
   758
     * <blockquote><pre>{@code
jaroslav@1692
   759
MethodHandle equals = publicLookup()
jaroslav@1692
   760
  .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
jaroslav@1692
   761
assert( (boolean) equals.invokeExact("me", (Object)"me"));
jaroslav@1692
   762
assert(!(boolean) equals.invokeExact("me", (Object)"thee"));
jaroslav@1692
   763
// spread both arguments from a 2-array:
jaroslav@1692
   764
MethodHandle eq2 = equals.asSpreader(Object[].class, 2);
jaroslav@1692
   765
assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" }));
jaroslav@1692
   766
assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
jaroslav@1692
   767
// try to spread from anything but a 2-array:
jaroslav@1692
   768
for (int n = 0; n <= 10; n++) {
jaroslav@1692
   769
  Object[] badArityArgs = (n == 2 ? null : new Object[n]);
jaroslav@1692
   770
  try { assert((boolean) eq2.invokeExact(badArityArgs) && false); }
jaroslav@1692
   771
  catch (IllegalArgumentException ex) { } // OK
jaroslav@1692
   772
}
jaroslav@1692
   773
// spread both arguments from a String array:
jaroslav@1692
   774
MethodHandle eq2s = equals.asSpreader(String[].class, 2);
jaroslav@1692
   775
assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" }));
jaroslav@1692
   776
assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" }));
jaroslav@1692
   777
// spread second arguments from a 1-array:
jaroslav@1692
   778
MethodHandle eq1 = equals.asSpreader(Object[].class, 1);
jaroslav@1692
   779
assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" }));
jaroslav@1692
   780
assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" }));
jaroslav@1692
   781
// spread no arguments from a 0-array or null:
jaroslav@1692
   782
MethodHandle eq0 = equals.asSpreader(Object[].class, 0);
jaroslav@1692
   783
assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0]));
jaroslav@1692
   784
assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null));
jaroslav@1692
   785
// asSpreader and asCollector are approximate inverses:
jaroslav@1692
   786
for (int n = 0; n <= 2; n++) {
jaroslav@1692
   787
    for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) {
jaroslav@1692
   788
        MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n);
jaroslav@1692
   789
        assert( (boolean) equals2.invokeWithArguments("me", "me"));
jaroslav@1692
   790
        assert(!(boolean) equals2.invokeWithArguments("me", "thee"));
jaroslav@1692
   791
    }
jaroslav@1692
   792
}
jaroslav@1692
   793
MethodHandle caToString = publicLookup()
jaroslav@1692
   794
  .findStatic(Arrays.class, "toString", methodType(String.class, char[].class));
jaroslav@1692
   795
assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray()));
jaroslav@1692
   796
MethodHandle caString3 = caToString.asCollector(char[].class, 3);
jaroslav@1692
   797
assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
jaroslav@1692
   798
MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
jaroslav@1692
   799
assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
jaroslav@1692
   800
     * }</pre></blockquote>
jaroslav@1692
   801
     * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments
jaroslav@1692
   802
     * @param arrayLength the number of arguments to spread from an incoming array argument
jaroslav@1692
   803
     * @return a new method handle which spreads its final array argument,
jaroslav@1692
   804
     *         before calling the original method handle
jaroslav@1692
   805
     * @throws NullPointerException if {@code arrayType} is a null reference
jaroslav@1692
   806
     * @throws IllegalArgumentException if {@code arrayType} is not an array type,
jaroslav@1692
   807
     *         or if target does not have at least
jaroslav@1692
   808
     *         {@code arrayLength} parameter types,
jaroslav@1692
   809
     *         or if {@code arrayLength} is negative,
jaroslav@1692
   810
     *         or if the resulting method handle's type would have
jaroslav@1692
   811
     *         <a href="MethodHandle.html#maxarity">too many parameters</a>
jaroslav@1692
   812
     * @throws WrongMethodTypeException if the implied {@code asType} call fails
jaroslav@1692
   813
     * @see #asCollector
jaroslav@1692
   814
     */
jaroslav@1692
   815
    public MethodHandle asSpreader(Class<?> arrayType, int arrayLength) {
jaroslav@1692
   816
        throw new IllegalStateException();
jaroslav@1692
   817
    }
jaroslav@1692
   818
jaroslav@1692
   819
    /**
jaroslav@1692
   820
     * Makes an <em>array-collecting</em> method handle, which accepts a given number of trailing
jaroslav@1692
   821
     * positional arguments and collects them into an array argument.
jaroslav@1692
   822
     * The new method handle adapts, as its <i>target</i>,
jaroslav@1692
   823
     * the current method handle.  The type of the adapter will be
jaroslav@1692
   824
     * the same as the type of the target, except that a single trailing
jaroslav@1692
   825
     * parameter (usually of type {@code arrayType}) is replaced by
jaroslav@1692
   826
     * {@code arrayLength} parameters whose type is element type of {@code arrayType}.
jaroslav@1692
   827
     * <p>
jaroslav@1692
   828
     * If the array type differs from the final argument type on the original target,
jaroslav@1692
   829
     * the original target is adapted to take the array type directly,
jaroslav@1692
   830
     * as if by a call to {@link #asType asType}.
jaroslav@1692
   831
     * <p>
jaroslav@1692
   832
     * When called, the adapter replaces its trailing {@code arrayLength}
jaroslav@1692
   833
     * arguments by a single new array of type {@code arrayType}, whose elements
jaroslav@1692
   834
     * comprise (in order) the replaced arguments.
jaroslav@1692
   835
     * Finally the target is called.
jaroslav@1692
   836
     * What the target eventually returns is returned unchanged by the adapter.
jaroslav@1692
   837
     * <p>
jaroslav@1692
   838
     * (The array may also be a shared constant when {@code arrayLength} is zero.)
jaroslav@1692
   839
     * <p>
jaroslav@1692
   840
     * (<em>Note:</em> The {@code arrayType} is often identical to the last
jaroslav@1692
   841
     * parameter type of the original target.
jaroslav@1692
   842
     * It is an explicit argument for symmetry with {@code asSpreader}, and also
jaroslav@1692
   843
     * to allow the target to use a simple {@code Object} as its last parameter type.)
jaroslav@1692
   844
     * <p>
jaroslav@1692
   845
     * In order to create a collecting adapter which is not restricted to a particular
jaroslav@1692
   846
     * number of collected arguments, use {@link #asVarargsCollector asVarargsCollector} instead.
jaroslav@1692
   847
     * <p>
jaroslav@1692
   848
     * Here are some examples of array-collecting method handles:
jaroslav@1692
   849
     * <blockquote><pre>{@code
jaroslav@1692
   850
MethodHandle deepToString = publicLookup()
jaroslav@1692
   851
  .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
jaroslav@1692
   852
assertEquals("[won]",   (String) deepToString.invokeExact(new Object[]{"won"}));
jaroslav@1692
   853
MethodHandle ts1 = deepToString.asCollector(Object[].class, 1);
jaroslav@1692
   854
assertEquals(methodType(String.class, Object.class), ts1.type());
jaroslav@1692
   855
//assertEquals("[won]", (String) ts1.invokeExact(         new Object[]{"won"})); //FAIL
jaroslav@1692
   856
assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"}));
jaroslav@1692
   857
// arrayType can be a subtype of Object[]
jaroslav@1692
   858
MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
jaroslav@1692
   859
assertEquals(methodType(String.class, String.class, String.class), ts2.type());
jaroslav@1692
   860
assertEquals("[two, too]", (String) ts2.invokeExact("two", "too"));
jaroslav@1692
   861
MethodHandle ts0 = deepToString.asCollector(Object[].class, 0);
jaroslav@1692
   862
assertEquals("[]", (String) ts0.invokeExact());
jaroslav@1692
   863
// collectors can be nested, Lisp-style
jaroslav@1692
   864
MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2);
jaroslav@1692
   865
assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D")));
jaroslav@1692
   866
// arrayType can be any primitive array type
jaroslav@1692
   867
MethodHandle bytesToString = publicLookup()
jaroslav@1692
   868
  .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class))
jaroslav@1692
   869
  .asCollector(byte[].class, 3);
jaroslav@1692
   870
assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3));
jaroslav@1692
   871
MethodHandle longsToString = publicLookup()
jaroslav@1692
   872
  .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
jaroslav@1692
   873
  .asCollector(long[].class, 1);
jaroslav@1692
   874
assertEquals("[123]", (String) longsToString.invokeExact((long)123));
jaroslav@1692
   875
     * }</pre></blockquote>
jaroslav@1692
   876
     * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
jaroslav@1692
   877
     * @param arrayLength the number of arguments to collect into a new array argument
jaroslav@1692
   878
     * @return a new method handle which collects some trailing argument
jaroslav@1692
   879
     *         into an array, before calling the original method handle
jaroslav@1692
   880
     * @throws NullPointerException if {@code arrayType} is a null reference
jaroslav@1692
   881
     * @throws IllegalArgumentException if {@code arrayType} is not an array type
jaroslav@1692
   882
     *         or {@code arrayType} is not assignable to this method handle's trailing parameter type,
jaroslav@1692
   883
     *         or {@code arrayLength} is not a legal array size,
jaroslav@1692
   884
     *         or the resulting method handle's type would have
jaroslav@1692
   885
     *         <a href="MethodHandle.html#maxarity">too many parameters</a>
jaroslav@1692
   886
     * @throws WrongMethodTypeException if the implied {@code asType} call fails
jaroslav@1692
   887
     * @see #asSpreader
jaroslav@1692
   888
     * @see #asVarargsCollector
jaroslav@1692
   889
     */
jaroslav@1692
   890
    public MethodHandle asCollector(Class<?> arrayType, int arrayLength) {
jaroslav@1692
   891
        throw new IllegalStateException();
jaroslav@1692
   892
    }
jaroslav@1692
   893
jaroslav@1692
   894
    /**
jaroslav@1692
   895
     * Makes a <em>variable arity</em> adapter which is able to accept
jaroslav@1692
   896
     * any number of trailing positional arguments and collect them
jaroslav@1692
   897
     * into an array argument.
jaroslav@1692
   898
     * <p>
jaroslav@1692
   899
     * The type and behavior of the adapter will be the same as
jaroslav@1692
   900
     * the type and behavior of the target, except that certain
jaroslav@1692
   901
     * {@code invoke} and {@code asType} requests can lead to
jaroslav@1692
   902
     * trailing positional arguments being collected into target's
jaroslav@1692
   903
     * trailing parameter.
jaroslav@1692
   904
     * Also, the last parameter type of the adapter will be
jaroslav@1692
   905
     * {@code arrayType}, even if the target has a different
jaroslav@1692
   906
     * last parameter type.
jaroslav@1692
   907
     * <p>
jaroslav@1692
   908
     * This transformation may return {@code this} if the method handle is
jaroslav@1692
   909
     * already of variable arity and its trailing parameter type
jaroslav@1692
   910
     * is identical to {@code arrayType}.
jaroslav@1692
   911
     * <p>
jaroslav@1692
   912
     * When called with {@link #invokeExact invokeExact}, the adapter invokes
jaroslav@1692
   913
     * the target with no argument changes.
jaroslav@1692
   914
     * (<em>Note:</em> This behavior is different from a
jaroslav@1692
   915
     * {@linkplain #asCollector fixed arity collector},
jaroslav@1692
   916
     * since it accepts a whole array of indeterminate length,
jaroslav@1692
   917
     * rather than a fixed number of arguments.)
jaroslav@1692
   918
     * <p>
jaroslav@1692
   919
     * When called with plain, inexact {@link #invoke invoke}, if the caller
jaroslav@1692
   920
     * type is the same as the adapter, the adapter invokes the target as with
jaroslav@1692
   921
     * {@code invokeExact}.
jaroslav@1692
   922
     * (This is the normal behavior for {@code invoke} when types match.)
jaroslav@1692
   923
     * <p>
jaroslav@1692
   924
     * Otherwise, if the caller and adapter arity are the same, and the
jaroslav@1692
   925
     * trailing parameter type of the caller is a reference type identical to
jaroslav@1692
   926
     * or assignable to the trailing parameter type of the adapter,
jaroslav@1692
   927
     * the arguments and return values are converted pairwise,
jaroslav@1692
   928
     * as if by {@link #asType asType} on a fixed arity
jaroslav@1692
   929
     * method handle.
jaroslav@1692
   930
     * <p>
jaroslav@1692
   931
     * Otherwise, the arities differ, or the adapter's trailing parameter
jaroslav@1692
   932
     * type is not assignable from the corresponding caller type.
jaroslav@1692
   933
     * In this case, the adapter replaces all trailing arguments from
jaroslav@1692
   934
     * the original trailing argument position onward, by
jaroslav@1692
   935
     * a new array of type {@code arrayType}, whose elements
jaroslav@1692
   936
     * comprise (in order) the replaced arguments.
jaroslav@1692
   937
     * <p>
jaroslav@1692
   938
     * The caller type must provides as least enough arguments,
jaroslav@1692
   939
     * and of the correct type, to satisfy the target's requirement for
jaroslav@1692
   940
     * positional arguments before the trailing array argument.
jaroslav@1692
   941
     * Thus, the caller must supply, at a minimum, {@code N-1} arguments,
jaroslav@1692
   942
     * where {@code N} is the arity of the target.
jaroslav@1692
   943
     * Also, there must exist conversions from the incoming arguments
jaroslav@1692
   944
     * to the target's arguments.
jaroslav@1692
   945
     * As with other uses of plain {@code invoke}, if these basic
jaroslav@1692
   946
     * requirements are not fulfilled, a {@code WrongMethodTypeException}
jaroslav@1692
   947
     * may be thrown.
jaroslav@1692
   948
     * <p>
jaroslav@1692
   949
     * In all cases, what the target eventually returns is returned unchanged by the adapter.
jaroslav@1692
   950
     * <p>
jaroslav@1692
   951
     * In the final case, it is exactly as if the target method handle were
jaroslav@1692
   952
     * temporarily adapted with a {@linkplain #asCollector fixed arity collector}
jaroslav@1692
   953
     * to the arity required by the caller type.
jaroslav@1692
   954
     * (As with {@code asCollector}, if the array length is zero,
jaroslav@1692
   955
     * a shared constant may be used instead of a new array.
jaroslav@1692
   956
     * If the implied call to {@code asCollector} would throw
jaroslav@1692
   957
     * an {@code IllegalArgumentException} or {@code WrongMethodTypeException},
jaroslav@1692
   958
     * the call to the variable arity adapter must throw
jaroslav@1692
   959
     * {@code WrongMethodTypeException}.)
jaroslav@1692
   960
     * <p>
jaroslav@1692
   961
     * The behavior of {@link #asType asType} is also specialized for
jaroslav@1692
   962
     * variable arity adapters, to maintain the invariant that
jaroslav@1692
   963
     * plain, inexact {@code invoke} is always equivalent to an {@code asType}
jaroslav@1692
   964
     * call to adjust the target type, followed by {@code invokeExact}.
jaroslav@1692
   965
     * Therefore, a variable arity adapter responds
jaroslav@1692
   966
     * to an {@code asType} request by building a fixed arity collector,
jaroslav@1692
   967
     * if and only if the adapter and requested type differ either
jaroslav@1692
   968
     * in arity or trailing argument type.
jaroslav@1692
   969
     * The resulting fixed arity collector has its type further adjusted
jaroslav@1692
   970
     * (if necessary) to the requested type by pairwise conversion,
jaroslav@1692
   971
     * as if by another application of {@code asType}.
jaroslav@1692
   972
     * <p>
jaroslav@1692
   973
     * When a method handle is obtained by executing an {@code ldc} instruction
jaroslav@1692
   974
     * of a {@code CONSTANT_MethodHandle} constant, and the target method is marked
jaroslav@1692
   975
     * as a variable arity method (with the modifier bit {@code 0x0080}),
jaroslav@1692
   976
     * the method handle will accept multiple arities, as if the method handle
jaroslav@1692
   977
     * constant were created by means of a call to {@code asVarargsCollector}.
jaroslav@1692
   978
     * <p>
jaroslav@1692
   979
     * In order to create a collecting adapter which collects a predetermined
jaroslav@1692
   980
     * number of arguments, and whose type reflects this predetermined number,
jaroslav@1692
   981
     * use {@link #asCollector asCollector} instead.
jaroslav@1692
   982
     * <p>
jaroslav@1692
   983
     * No method handle transformations produce new method handles with
jaroslav@1692
   984
     * variable arity, unless they are documented as doing so.
jaroslav@1692
   985
     * Therefore, besides {@code asVarargsCollector},
jaroslav@1692
   986
     * all methods in {@code MethodHandle} and {@code MethodHandles}
jaroslav@1692
   987
     * will return a method handle with fixed arity,
jaroslav@1692
   988
     * except in the cases where they are specified to return their original
jaroslav@1692
   989
     * operand (e.g., {@code asType} of the method handle's own type).
jaroslav@1692
   990
     * <p>
jaroslav@1692
   991
     * Calling {@code asVarargsCollector} on a method handle which is already
jaroslav@1692
   992
     * of variable arity will produce a method handle with the same type and behavior.
jaroslav@1692
   993
     * It may (or may not) return the original variable arity method handle.
jaroslav@1692
   994
     * <p>
jaroslav@1692
   995
     * Here is an example, of a list-making variable arity method handle:
jaroslav@1692
   996
     * <blockquote><pre>{@code
jaroslav@1692
   997
MethodHandle deepToString = publicLookup()
jaroslav@1692
   998
  .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
jaroslav@1692
   999
MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
jaroslav@1692
  1000
assertEquals("[won]",   (String) ts1.invokeExact(    new Object[]{"won"}));
jaroslav@1692
  1001
assertEquals("[won]",   (String) ts1.invoke(         new Object[]{"won"}));
jaroslav@1692
  1002
assertEquals("[won]",   (String) ts1.invoke(                      "won" ));
jaroslav@1692
  1003
assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"}));
jaroslav@1692
  1004
// findStatic of Arrays.asList(...) produces a variable arity method handle:
jaroslav@1692
  1005
MethodHandle asList = publicLookup()
jaroslav@1692
  1006
  .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
jaroslav@1692
  1007
assertEquals(methodType(List.class, Object[].class), asList.type());
jaroslav@1692
  1008
assert(asList.isVarargsCollector());
jaroslav@1692
  1009
assertEquals("[]", asList.invoke().toString());
jaroslav@1692
  1010
assertEquals("[1]", asList.invoke(1).toString());
jaroslav@1692
  1011
assertEquals("[two, too]", asList.invoke("two", "too").toString());
jaroslav@1692
  1012
String[] argv = { "three", "thee", "tee" };
jaroslav@1692
  1013
assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
jaroslav@1692
  1014
assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString());
jaroslav@1692
  1015
List ls = (List) asList.invoke((Object)argv);
jaroslav@1692
  1016
assertEquals(1, ls.size());
jaroslav@1692
  1017
assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
jaroslav@1692
  1018
     * }</pre></blockquote>
jaroslav@1692
  1019
     * <p style="font-size:smaller;">
jaroslav@1692
  1020
     * <em>Discussion:</em>
jaroslav@1692
  1021
     * These rules are designed as a dynamically-typed variation
jaroslav@1692
  1022
     * of the Java rules for variable arity methods.
jaroslav@1692
  1023
     * In both cases, callers to a variable arity method or method handle
jaroslav@1692
  1024
     * can either pass zero or more positional arguments, or else pass
jaroslav@1692
  1025
     * pre-collected arrays of any length.  Users should be aware of the
jaroslav@1692
  1026
     * special role of the final argument, and of the effect of a
jaroslav@1692
  1027
     * type match on that final argument, which determines whether
jaroslav@1692
  1028
     * or not a single trailing argument is interpreted as a whole
jaroslav@1692
  1029
     * array or a single element of an array to be collected.
jaroslav@1692
  1030
     * Note that the dynamic type of the trailing argument has no
jaroslav@1692
  1031
     * effect on this decision, only a comparison between the symbolic
jaroslav@1692
  1032
     * type descriptor of the call site and the type descriptor of the method handle.)
jaroslav@1692
  1033
     *
jaroslav@1692
  1034
     * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
jaroslav@1692
  1035
     * @return a new method handle which can collect any number of trailing arguments
jaroslav@1692
  1036
     *         into an array, before calling the original method handle
jaroslav@1692
  1037
     * @throws NullPointerException if {@code arrayType} is a null reference
jaroslav@1692
  1038
     * @throws IllegalArgumentException if {@code arrayType} is not an array type
jaroslav@1692
  1039
     *         or {@code arrayType} is not assignable to this method handle's trailing parameter type
jaroslav@1692
  1040
     * @see #asCollector
jaroslav@1692
  1041
     * @see #isVarargsCollector
jaroslav@1692
  1042
     * @see #asFixedArity
jaroslav@1692
  1043
     */
jaroslav@1692
  1044
    public MethodHandle asVarargsCollector(Class<?> arrayType) {
jaroslav@1692
  1045
        throw new IllegalStateException();
jaroslav@1692
  1046
    }
jaroslav@1692
  1047
jaroslav@1692
  1048
    /**
jaroslav@1692
  1049
     * Determines if this method handle
jaroslav@1692
  1050
     * supports {@linkplain #asVarargsCollector variable arity} calls.
jaroslav@1692
  1051
     * Such method handles arise from the following sources:
jaroslav@1692
  1052
     * <ul>
jaroslav@1692
  1053
     * <li>a call to {@linkplain #asVarargsCollector asVarargsCollector}
jaroslav@1692
  1054
     * <li>a call to a {@linkplain java.lang.invoke.MethodHandles.Lookup lookup method}
jaroslav@1692
  1055
     *     which resolves to a variable arity Java method or constructor
jaroslav@1692
  1056
     * <li>an {@code ldc} instruction of a {@code CONSTANT_MethodHandle}
jaroslav@1692
  1057
     *     which resolves to a variable arity Java method or constructor
jaroslav@1692
  1058
     * </ul>
jaroslav@1692
  1059
     * @return true if this method handle accepts more than one arity of plain, inexact {@code invoke} calls
jaroslav@1692
  1060
     * @see #asVarargsCollector
jaroslav@1692
  1061
     * @see #asFixedArity
jaroslav@1692
  1062
     */
jaroslav@1692
  1063
    public boolean isVarargsCollector() {
jaroslav@1692
  1064
        return false;
jaroslav@1692
  1065
    }
jaroslav@1692
  1066
jaroslav@1692
  1067
    /**
jaroslav@1692
  1068
     * Makes a <em>fixed arity</em> method handle which is otherwise
jaroslav@1692
  1069
     * equivalent to the current method handle.
jaroslav@1692
  1070
     * <p>
jaroslav@1692
  1071
     * If the current method handle is not of
jaroslav@1692
  1072
     * {@linkplain #asVarargsCollector variable arity},
jaroslav@1692
  1073
     * the current method handle is returned.
jaroslav@1692
  1074
     * This is true even if the current method handle
jaroslav@1692
  1075
     * could not be a valid input to {@code asVarargsCollector}.
jaroslav@1692
  1076
     * <p>
jaroslav@1692
  1077
     * Otherwise, the resulting fixed-arity method handle has the same
jaroslav@1692
  1078
     * type and behavior of the current method handle,
jaroslav@1692
  1079
     * except that {@link #isVarargsCollector isVarargsCollector}
jaroslav@1692
  1080
     * will be false.
jaroslav@1692
  1081
     * The fixed-arity method handle may (or may not) be the
jaroslav@1692
  1082
     * a previous argument to {@code asVarargsCollector}.
jaroslav@1692
  1083
     * <p>
jaroslav@1692
  1084
     * Here is an example, of a list-making variable arity method handle:
jaroslav@1692
  1085
     * <blockquote><pre>{@code
jaroslav@1692
  1086
MethodHandle asListVar = publicLookup()
jaroslav@1692
  1087
  .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
jaroslav@1692
  1088
  .asVarargsCollector(Object[].class);
jaroslav@1692
  1089
MethodHandle asListFix = asListVar.asFixedArity();
jaroslav@1692
  1090
assertEquals("[1]", asListVar.invoke(1).toString());
jaroslav@1692
  1091
Exception caught = null;
jaroslav@1692
  1092
try { asListFix.invoke((Object)1); }
jaroslav@1692
  1093
catch (Exception ex) { caught = ex; }
jaroslav@1692
  1094
assert(caught instanceof ClassCastException);
jaroslav@1692
  1095
assertEquals("[two, too]", asListVar.invoke("two", "too").toString());
jaroslav@1692
  1096
try { asListFix.invoke("two", "too"); }
jaroslav@1692
  1097
catch (Exception ex) { caught = ex; }
jaroslav@1692
  1098
assert(caught instanceof WrongMethodTypeException);
jaroslav@1692
  1099
Object[] argv = { "three", "thee", "tee" };
jaroslav@1692
  1100
assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString());
jaroslav@1692
  1101
assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
jaroslav@1692
  1102
assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
jaroslav@1692
  1103
assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
jaroslav@1692
  1104
     * }</pre></blockquote>
jaroslav@1692
  1105
     *
jaroslav@1692
  1106
     * @return a new method handle which accepts only a fixed number of arguments
jaroslav@1692
  1107
     * @see #asVarargsCollector
jaroslav@1692
  1108
     * @see #isVarargsCollector
jaroslav@1692
  1109
     */
jaroslav@1692
  1110
    public MethodHandle asFixedArity() {
jaroslav@1692
  1111
        assert(!isVarargsCollector());
jaroslav@1692
  1112
        return this;
jaroslav@1692
  1113
    }
jaroslav@1692
  1114
jaroslav@1692
  1115
    /**
jaroslav@1692
  1116
     * Binds a value {@code x} to the first argument of a method handle, without invoking it.
jaroslav@1692
  1117
     * The new method handle adapts, as its <i>target</i>,
jaroslav@1692
  1118
     * the current method handle by binding it to the given argument.
jaroslav@1692
  1119
     * The type of the bound handle will be
jaroslav@1692
  1120
     * the same as the type of the target, except that a single leading
jaroslav@1692
  1121
     * reference parameter will be omitted.
jaroslav@1692
  1122
     * <p>
jaroslav@1692
  1123
     * When called, the bound handle inserts the given value {@code x}
jaroslav@1692
  1124
     * as a new leading argument to the target.  The other arguments are
jaroslav@1692
  1125
     * also passed unchanged.
jaroslav@1692
  1126
     * What the target eventually returns is returned unchanged by the bound handle.
jaroslav@1692
  1127
     * <p>
jaroslav@1692
  1128
     * The reference {@code x} must be convertible to the first parameter
jaroslav@1692
  1129
     * type of the target.
jaroslav@1692
  1130
     * <p>
jaroslav@1692
  1131
     * (<em>Note:</em>  Because method handles are immutable, the target method handle
jaroslav@1692
  1132
     * retains its original type and behavior.)
jaroslav@1692
  1133
     * @param x  the value to bind to the first argument of the target
jaroslav@1692
  1134
     * @return a new method handle which prepends the given value to the incoming
jaroslav@1692
  1135
     *         argument list, before calling the original method handle
jaroslav@1692
  1136
     * @throws IllegalArgumentException if the target does not have a
jaroslav@1692
  1137
     *         leading parameter type that is a reference type
jaroslav@1692
  1138
     * @throws ClassCastException if {@code x} cannot be converted
jaroslav@1692
  1139
     *         to the leading parameter type of the target
jaroslav@1692
  1140
     * @see MethodHandles#insertArguments
jaroslav@1692
  1141
     */
jaroslav@1692
  1142
    public MethodHandle bindTo(Object x) {
jaroslav@1692
  1143
        throw new IllegalStateException();
jaroslav@1692
  1144
    }
jaroslav@1692
  1145
jaroslav@1692
  1146
    /**
jaroslav@1692
  1147
     * Returns a string representation of the method handle,
jaroslav@1692
  1148
     * starting with the string {@code "MethodHandle"} and
jaroslav@1692
  1149
     * ending with the string representation of the method handle's type.
jaroslav@1692
  1150
     * In other words, this method returns a string equal to the value of:
jaroslav@1692
  1151
     * <blockquote><pre>{@code
jaroslav@1692
  1152
     * "MethodHandle" + type().toString()
jaroslav@1692
  1153
     * }</pre></blockquote>
jaroslav@1692
  1154
     * <p>
jaroslav@1692
  1155
     * (<em>Note:</em>  Future releases of this API may add further information
jaroslav@1692
  1156
     * to the string representation.
jaroslav@1692
  1157
     * Therefore, the present syntax should not be parsed by applications.)
jaroslav@1692
  1158
     *
jaroslav@1692
  1159
     * @return a string representation of the method handle
jaroslav@1692
  1160
     */
jaroslav@1692
  1161
    @Override
jaroslav@1692
  1162
    public String toString() {
jaroslav@1692
  1163
        return standardString();
jaroslav@1692
  1164
    }
jaroslav@1692
  1165
    String standardString() {
jaroslav@1692
  1166
        throw new IllegalStateException();
jaroslav@1692
  1167
    }
jaroslav@1692
  1168
}