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