27
28
29 import java.util.*;
30 import sun.invoke.util.*;
31 import sun.misc.Unsafe;
32
33 import static java.lang.invoke.MethodHandleStatics.*;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
36
37 /**
38 * A method handle is a typed, directly executable reference to an underlying method,
39 * constructor, field, or similar low-level operation, with optional
40 * transformations of arguments or return values.
41 * These transformations are quite general, and include such patterns as
42 * {@linkplain #asType conversion},
43 * {@linkplain #bindTo insertion},
44 * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion},
45 * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}.
46 *
47 * <h3>Method handle contents</h3>
48 * Method handles are dynamically and strongly typed according to their parameter and return types.
49 * They are not distinguished by the name or the defining class of their underlying methods.
50 * A method handle must be invoked using a symbolic type descriptor which matches
51 * the method handle's own {@linkplain #type type descriptor}.
52 * <p>
53 * Every method handle reports its type descriptor via the {@link #type type} accessor.
54 * This type descriptor is a {@link java.lang.invoke.MethodType MethodType} object,
55 * whose structure is a series of classes, one of which is
56 * the return type of the method (or {@code void.class} if none).
57 * <p>
58 * A method handle's type controls the types of invocations it accepts,
59 * and the kinds of transformations that apply to it.
60 * <p>
61 * A method handle contains a pair of special invoker methods
62 * called {@link #invokeExact invokeExact} and {@link #invoke invoke}.
63 * Both invoker methods provide direct access to the method handle's
64 * underlying method, constructor, field, or other operation,
65 * as modified by transformations of arguments and return values.
66 * Both invokers accept calls which exactly match the method handle's own type.
67 * The plain, inexact invoker also accepts a range of other call types.
68 * <p>
69 * Method handles are immutable and have no visible state.
70 * Of course, they can be bound to underlying methods or data which exhibit state.
71 * With respect to the Java Memory Model, any method handle will behave
72 * as if all of its (internal) fields are final variables. This means that any method
73 * handle made visible to the application will always be fully formed.
74 * This is true even if the method handle is published through a shared
75 * variable in a data race.
76 * <p>
77 * Method handles cannot be subclassed by the user.
78 * Implementations may (or may not) create internal subclasses of {@code MethodHandle}
79 * which may be visible via the {@link java.lang.Object#getClass Object.getClass}
80 * operation. The programmer should not draw conclusions about a method handle
81 * from its specific class, as the method handle class hierarchy (if any)
82 * may change from time to time or across implementations from different vendors.
83 *
84 * <h3>Method handle compilation</h3>
85 * A Java method call expression naming {@code invokeExact} or {@code invoke}
86 * can invoke a method handle from Java source code.
87 * From the viewpoint of source code, these methods can take any arguments
88 * and their result can be cast to any return type.
89 * Formally this is accomplished by giving the invoker methods
90 * {@code Object} return types and variable arity {@code Object} arguments,
91 * but they have an additional quality called <em>signature polymorphism</em>
92 * which connects this freedom of invocation directly to the JVM execution stack.
93 * <p>
94 * As is usual with virtual methods, source-level calls to {@code invokeExact}
95 * and {@code invoke} compile to an {@code invokevirtual} instruction.
96 * More unusually, the compiler must record the actual argument types,
97 * and may not perform method invocation conversions on the arguments.
98 * Instead, it must push them on the stack according to their own unconverted types.
99 * The method handle object itself is pushed on the stack before the arguments.
100 * The compiler then calls the method handle with a symbolic type descriptor which
101 * describes the argument and return types.
102 * <p>
103 * To issue a complete symbolic type descriptor, the compiler must also determine
104 * the return type. This is based on a cast on the method invocation expression,
105 * if there is one, or else {@code Object} if the invocation is an expression
106 * or else {@code void} if the invocation is a statement.
107 * The cast may be to a primitive type (but not {@code void}).
108 * <p>
109 * As a corner case, an uncasted {@code null} argument is given
110 * a symbolic type descriptor of {@code java.lang.Void}.
111 * The ambiguity with the type {@code Void} is harmless, since there are no references of type
112 * {@code Void} except the null reference.
113 *
114 * <h3>Method handle invocation</h3>
115 * The first time a {@code invokevirtual} instruction is executed
116 * it is linked, by symbolically resolving the names in the instruction
117 * and verifying that the method call is statically legal.
118 * This is true of calls to {@code invokeExact} and {@code invoke}.
119 * In this case, the symbolic type descriptor emitted by the compiler is checked for
120 * correct syntax and names it contains are resolved.
121 * Thus, an {@code invokevirtual} instruction which invokes
122 * a method handle will always link, as long
123 * as the symbolic type descriptor is syntactically well-formed
124 * and the types exist.
125 * <p>
126 * When the {@code invokevirtual} is executed after linking,
127 * the receiving method handle's type is first checked by the JVM
128 * to ensure that it matches the symbolic type descriptor.
129 * If the type match fails, it means that the method which the
130 * caller is invoking is not present on the individual
131 * method handle being invoked.
132 * <p>
133 * In the case of {@code invokeExact}, the type descriptor of the invocation
134 * (after resolving symbolic type names) must exactly match the method type
137 * must be a valid argument to the receiver's {@link #asType asType} method.
138 * Thus, plain {@code invoke} is more permissive than {@code invokeExact}.
139 * <p>
140 * After type matching, a call to {@code invokeExact} directly
141 * and immediately invoke the method handle's underlying method
142 * (or other behavior, as the case may be).
143 * <p>
144 * A call to plain {@code invoke} works the same as a call to
145 * {@code invokeExact}, if the symbolic type descriptor specified by the caller
146 * exactly matches the method handle's own type.
147 * If there is a type mismatch, {@code invoke} attempts
148 * to adjust the type of the receiving method handle,
149 * as if by a call to {@link #asType asType},
150 * to obtain an exactly invokable method handle {@code M2}.
151 * This allows a more powerful negotiation of method type
152 * between caller and callee.
153 * <p>
154 * (<em>Note:</em> The adjusted method handle {@code M2} is not directly observable,
155 * and implementations are therefore not required to materialize it.)
156 *
157 * <h3>Invocation checking</h3>
158 * In typical programs, method handle type matching will usually succeed.
159 * But if a match fails, the JVM will throw a {@link WrongMethodTypeException},
160 * either directly (in the case of {@code invokeExact}) or indirectly as if
161 * by a failed call to {@code asType} (in the case of {@code invoke}).
162 * <p>
163 * Thus, a method type mismatch which might show up as a linkage error
164 * in a statically typed program can show up as
165 * a dynamic {@code WrongMethodTypeException}
166 * in a program which uses method handles.
167 * <p>
168 * Because method types contain "live" {@code Class} objects,
169 * method type matching takes into account both types names and class loaders.
170 * Thus, even if a method handle {@code M} is created in one
171 * class loader {@code L1} and used in another {@code L2},
172 * method handle calls are type-safe, because the caller's symbolic type
173 * descriptor, as resolved in {@code L2},
174 * is matched against the original callee method's symbolic type descriptor,
175 * as resolved in {@code L1}.
176 * The resolution in {@code L1} happens when {@code M} is created
177 * and its type is assigned, while the resolution in {@code L2} happens
178 * when the {@code invokevirtual} instruction is linked.
179 * <p>
180 * Apart from the checking of type descriptors,
181 * a method handle's capability to call its underlying method is unrestricted.
182 * If a method handle is formed on a non-public method by a class
183 * that has access to that method, the resulting handle can be used
184 * in any place by any caller who receives a reference to it.
185 * <p>
186 * Unlike with the Core Reflection API, where access is checked every time
187 * a reflective method is invoked,
188 * method handle access checking is performed
189 * <a href="MethodHandles.Lookup.html#access">when the method handle is created</a>.
190 * In the case of {@code ldc} (see below), access checking is performed as part of linking
191 * the constant pool entry underlying the constant method handle.
192 * <p>
193 * Thus, handles to non-public methods, or to methods in non-public classes,
194 * should generally be kept secret.
195 * They should not be passed to untrusted code unless their use from
196 * the untrusted code would be harmless.
197 *
198 * <h3>Method handle creation</h3>
199 * Java code can create a method handle that directly accesses
200 * any method, constructor, or field that is accessible to that code.
201 * This is done via a reflective, capability-based API called
202 * {@link java.lang.invoke.MethodHandles.Lookup MethodHandles.Lookup}
203 * For example, a static method handle can be obtained
204 * from {@link java.lang.invoke.MethodHandles.Lookup#findStatic Lookup.findStatic}.
205 * There are also conversion methods from Core Reflection API objects,
206 * such as {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
207 * <p>
208 * Like classes and strings, method handles that correspond to accessible
209 * fields, methods, and constructors can also be represented directly
210 * in a class file's constant pool as constants to be loaded by {@code ldc} bytecodes.
211 * A new type of constant pool entry, {@code CONSTANT_MethodHandle},
212 * refers directly to an associated {@code CONSTANT_Methodref},
213 * {@code CONSTANT_InterfaceMethodref}, or {@code CONSTANT_Fieldref}
214 * constant pool entry.
215 * (For full details on method handle constants,
216 * see sections 4.4.8 and 5.4.3.5 of the Java Virtual Machine Specification.)
217 * <p>
218 * Method handles produced by lookups or constant loads from methods or
232 * their corresponding bytecode instructions, and the {@code ldc} instruction
233 * will throw corresponding linkage errors if the bytecode behaviors would
234 * throw such errors.
235 * <p>
236 * As a corollary of this, access to protected members is restricted
237 * to receivers only of the accessing class, or one of its subclasses,
238 * and the accessing class must in turn be a subclass (or package sibling)
239 * of the protected member's defining class.
240 * If a method reference refers to a protected non-static method or field
241 * of a class outside the current package, the receiver argument will
242 * be narrowed to the type of the accessing class.
243 * <p>
244 * When a method handle to a virtual method is invoked, the method is
245 * always looked up in the receiver (that is, the first argument).
246 * <p>
247 * A non-virtual method handle to a specific virtual method implementation
248 * can also be created. These do not perform virtual lookup based on
249 * receiver type. Such a method handle simulates the effect of
250 * an {@code invokespecial} instruction to the same method.
251 *
252 * <h3>Usage examples</h3>
253 * Here are some examples of usage:
254 * <p><blockquote><pre>{@code
255 Object x, y; String s; int i;
256 MethodType mt; MethodHandle mh;
257 MethodHandles.Lookup lookup = MethodHandles.lookup();
258 // mt is (char,char)String
259 mt = MethodType.methodType(String.class, char.class, char.class);
260 mh = lookup.findVirtual(String.class, "replace", mt);
261 s = (String) mh.invokeExact("daddy",'d','n');
262 // invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
263 assertEquals(s, "nanny");
264 // weakly typed invocation (using MHs.invoke)
265 s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
266 assertEquals(s, "savvy");
267 // mt is (Object[])List
268 mt = MethodType.methodType(java.util.List.class, Object[].class);
269 mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
270 assert(mh.isVarargsCollector());
271 x = mh.invoke("one", "two");
272 // invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
278 // invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
279 assertEquals(x, java.util.Arrays.asList(1,2,3));
280 // mt is ()int
281 mt = MethodType.methodType(int.class);
282 mh = lookup.findVirtual(java.util.List.class, "size", mt);
283 i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
284 // invokeExact(Ljava/util/List;)I
285 assert(i == 3);
286 mt = MethodType.methodType(void.class, String.class);
287 mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
288 mh.invokeExact(System.out, "Hello, world.");
289 // invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
290 * }</pre></blockquote>
291 * Each of the above calls to {@code invokeExact} or plain {@code invoke}
292 * generates a single invokevirtual instruction with
293 * the symbolic type descriptor indicated in the following comment.
294 * In these examples, the helper method {@code assertEquals} is assumed to
295 * be a method which calls {@link java.util.Objects#equals(Object,Object) Objects.equals }
296 * on its arguments, and asserts that the result is true.
297 *
298 * <h3>Exceptions</h3>
299 * The methods {@code invokeExact} and {@code invoke} are declared
300 * to throw {@link java.lang.Throwable Throwable},
301 * which is to say that there is no static restriction on what a method handle
302 * can throw. Since the JVM does not distinguish between checked
303 * and unchecked exceptions (other than by their class, of course),
304 * there is no particular effect on bytecode shape from ascribing
305 * checked exceptions to method handle invocations. But in Java source
306 * code, methods which perform method handle calls must either explicitly
307 * throw {@code Throwable}, or else must catch all
308 * throwables locally, rethrowing only those which are legal in the context,
309 * and wrapping ones which are illegal.
310 *
311 * <h3><a name="sigpoly"></a>Signature polymorphism</h3>
312 * The unusual compilation and linkage behavior of
313 * {@code invokeExact} and plain {@code invoke}
314 * is referenced by the term <em>signature polymorphism</em>.
315 * As defined in the Java Language Specification,
316 * a signature polymorphic method is one which can operate with
317 * any of a wide range of call signatures and return types.
318 * <p>
319 * In source code, a call to a signature polymorphic method will
320 * compile, regardless of the requested symbolic type descriptor.
321 * As usual, the Java compiler emits an {@code invokevirtual}
322 * instruction with the given symbolic type descriptor against the named method.
323 * The unusual part is that the symbolic type descriptor is derived from
324 * the actual argument and return types, not from the method declaration.
325 * <p>
326 * When the JVM processes bytecode containing signature polymorphic calls,
327 * it will successfully link any such call, regardless of its symbolic type descriptor.
328 * (In order to retain type safety, the JVM will guard such calls with suitable
329 * dynamic type checks, as described elsewhere.)
330 * <p>
331 * Bytecode generators, including the compiler back end, are required to emit
332 * untransformed symbolic type descriptors for these methods.
333 * Tools which determine symbolic linkage are required to accept such
334 * untransformed descriptors, without reporting linkage errors.
335 *
336 * <h3>Interoperation between method handles and the Core Reflection API</h3>
337 * Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup Lookup} API,
338 * any class member represented by a Core Reflection API object
339 * can be converted to a behaviorally equivalent method handle.
340 * For example, a reflective {@link java.lang.reflect.Method Method} can
341 * be converted to a method handle using
342 * {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
343 * The resulting method handles generally provide more direct and efficient
344 * access to the underlying class members.
345 * <p>
346 * As a special case,
347 * when the Core Reflection API is used to view the signature polymorphic
348 * methods {@code invokeExact} or plain {@code invoke} in this class,
349 * they appear as ordinary non-polymorphic methods.
350 * Their reflective appearance, as viewed by
351 * {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod},
352 * is unaffected by their special status in this API.
353 * For example, {@link java.lang.reflect.Method#getModifiers Method.getModifiers}
354 * will report exactly those modifier bits required for any similarly
355 * declared method, including in this case {@code native} and {@code varargs} bits.
356 * <p>
358 * invoked via {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.
359 * However, such reflective calls do not result in method handle invocations.
360 * Such a call, if passed the required argument
361 * (a single one, of type {@code Object[]}), will ignore the argument and
362 * will throw an {@code UnsupportedOperationException}.
363 * <p>
364 * Since {@code invokevirtual} instructions can natively
365 * invoke method handles under any symbolic type descriptor, this reflective view conflicts
366 * with the normal presentation of these methods via bytecodes.
367 * Thus, these two native methods, when reflectively viewed by
368 * {@code Class.getDeclaredMethod}, may be regarded as placeholders only.
369 * <p>
370 * In order to obtain an invoker method for a particular type descriptor,
371 * use {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker},
372 * or {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}.
373 * The {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual}
374 * API is also able to return a method handle
375 * to call {@code invokeExact} or plain {@code invoke},
376 * for any specified type descriptor .
377 *
378 * <h3>Interoperation between method handles and Java generics</h3>
379 * A method handle can be obtained on a method, constructor, or field
380 * which is declared with Java generic types.
381 * As with the Core Reflection API, the type of the method handle
382 * will constructed from the erasure of the source-level type.
383 * When a method handle is invoked, the types of its arguments
384 * or the return value cast type may be generic types or type instances.
385 * If this occurs, the compiler will replace those
386 * types by their erasures when it constructs the symbolic type descriptor
387 * for the {@code invokevirtual} instruction.
388 * <p>
389 * Method handles do not represent
390 * their function-like types in terms of Java parameterized (generic) types,
391 * because there are three mismatches between function-like types and parameterized
392 * Java types.
393 * <ul>
394 * <li>Method types range over all possible arities,
395 * from no arguments to up to 255 of arguments (a limit imposed by the JVM).
396 * Generics are not variadic, and so cannot represent this.</li>
397 * <li>Method types can specify arguments of primitive types,
398 * which Java generic types cannot range over.</li>
440 type.getClass(); // explicit NPE
441 form.getClass(); // explicit NPE
442 this.type = type;
443 this.form = form;
444
445 form.prepare(); // TO DO: Try to delay this step until just before invocation.
446 }
447
448 /**
449 * Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match.
450 * The symbolic type descriptor at the call site of {@code invokeExact} must
451 * exactly match this method handle's {@link #type type}.
452 * No conversions are allowed on arguments or return values.
453 * <p>
454 * When this method is observed via the Core Reflection API,
455 * it will appear as a single native method, taking an object array and returning an object.
456 * If this native method is invoked directly via
457 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
458 * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
459 * it will throw an {@code UnsupportedOperationException}.
460 * @throws WrongMethodTypeException if the target's type is not identical with the caller's symbolic type descriptor
461 * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
462 */
463 public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable;
464
465 /**
466 * Invokes the method handle, allowing any caller type descriptor,
467 * and optionally performing conversions on arguments and return values.
468 * <p>
469 * If the call site's symbolic type descriptor exactly matches this method handle's {@link #type type},
470 * the call proceeds as if by {@link #invokeExact invokeExact}.
471 * <p>
472 * Otherwise, the call proceeds as if this method handle were first
473 * adjusted by calling {@link #asType asType} to adjust this method handle
474 * to the required type, and then the call proceeds as if by
475 * {@link #invokeExact invokeExact} on the adjusted method handle.
476 * <p>
477 * There is no guarantee that the {@code asType} call is actually made.
478 * If the JVM can predict the results of making the call, it may perform
479 * adaptations directly on the caller's arguments,
480 * and call the target method handle according to its own exact type.
481 * <p>
482 * The resolved type descriptor at the call site of {@code invoke} must
483 * be a valid argument to the receivers {@code asType} method.
484 * In particular, the caller must specify the same argument arity
485 * as the callee's type,
486 * if the callee is not a {@linkplain #asVarargsCollector variable arity collector}.
487 * <p>
488 * When this method is observed via the Core Reflection API,
489 * it will appear as a single native method, taking an object array and returning an object.
490 * If this native method is invoked directly via
491 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
492 * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
493 * it will throw an {@code UnsupportedOperationException}.
494 * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's symbolic type descriptor
495 * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails
496 * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
497 */
498 public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable;
499
500 /**
501 * Private method for trusted invocation of a method handle respecting simplified signatures.
502 * Type mismatches will not throw {@code WrongMethodTypeException}, but could crash the JVM.
503 * <p>
504 * The caller signature is restricted to the following basic types:
505 * Object, int, long, float, double, and void return.
506 * <p>
507 * The caller is responsible for maintaining type correctness by ensuring
508 * that the each outgoing argument value is a member of the range of the corresponding
509 * callee argument type.
510 * (The caller should therefore issue appropriate casts and integer narrowing
511 * operations on outgoing argument values.)
512 * The caller can assume that the incoming result value is part of the range
513 * of the callee's return type.
514 */
515 /*non-public*/ final native @PolymorphicSignature Object invokeBasic(Object... args) throws Throwable;
516
517 /*non-public*/ static native @PolymorphicSignature Object linkToVirtual(Object... args) throws Throwable;
518
519 /**
520 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeStatic}.
521 * The caller signature is restricted to basic types as with {@code invokeBasic}.
522 * The trailing (not leading) argument must be a MemberName.
523 */
524 /*non-public*/ static native @PolymorphicSignature Object linkToStatic(Object... args) throws Throwable;
525
526 /**
527 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeSpecial}.
528 * The caller signature is restricted to basic types as with {@code invokeBasic}.
529 * The trailing (not leading) argument must be a MemberName.
530 */
531 /*non-public*/ static native @PolymorphicSignature Object linkToSpecial(Object... args) throws Throwable;
532
533 /**
534 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeInterface}.
535 * The caller signature is restricted to basic types as with {@code invokeBasic}.
536 * The trailing (not leading) argument must be a MemberName.
537 */
538 /*non-public*/ static native @PolymorphicSignature Object linkToInterface(Object... args) throws Throwable;
539
540 /**
541 * Performs a variable arity invocation, passing the arguments in the given array
542 * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
543 * which mentions only the type {@code Object}, and whose arity is the length
544 * of the argument array.
545 * <p>
546 * Specifically, execution proceeds as if by the following steps,
547 * although the methods are not guaranteed to be called if the JVM
548 * can predict their effects.
549 * <ul>
550 * <li>Determine the length of the argument array as {@code N}.
551 * For a null reference, {@code N=0}. </li>
552 * <li>Determine the general type {@code TN} of {@code N} arguments as
553 * as {@code TN=MethodType.genericMethodType(N)}.</li>
554 * <li>Force the original target method handle {@code MH0} to the
555 * required type, as {@code MH1 = MH0.asType(TN)}. </li>
556 * <li>Spread the array into {@code N} separate arguments {@code A0, ...}. </li>
|
27
28
29 import java.util.*;
30 import sun.invoke.util.*;
31 import sun.misc.Unsafe;
32
33 import static java.lang.invoke.MethodHandleStatics.*;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
36
37 /**
38 * A method handle is a typed, directly executable reference to an underlying method,
39 * constructor, field, or similar low-level operation, with optional
40 * transformations of arguments or return values.
41 * These transformations are quite general, and include such patterns as
42 * {@linkplain #asType conversion},
43 * {@linkplain #bindTo insertion},
44 * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion},
45 * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}.
46 *
47 * <h1>Method handle contents</h1>
48 * Method handles are dynamically and strongly typed according to their parameter and return types.
49 * They are not distinguished by the name or the defining class of their underlying methods.
50 * A method handle must be invoked using a symbolic type descriptor which matches
51 * the method handle's own {@linkplain #type type descriptor}.
52 * <p>
53 * Every method handle reports its type descriptor via the {@link #type type} accessor.
54 * This type descriptor is a {@link java.lang.invoke.MethodType MethodType} object,
55 * whose structure is a series of classes, one of which is
56 * the return type of the method (or {@code void.class} if none).
57 * <p>
58 * A method handle's type controls the types of invocations it accepts,
59 * and the kinds of transformations that apply to it.
60 * <p>
61 * A method handle contains a pair of special invoker methods
62 * called {@link #invokeExact invokeExact} and {@link #invoke invoke}.
63 * Both invoker methods provide direct access to the method handle's
64 * underlying method, constructor, field, or other operation,
65 * as modified by transformations of arguments and return values.
66 * Both invokers accept calls which exactly match the method handle's own type.
67 * The plain, inexact invoker also accepts a range of other call types.
68 * <p>
69 * Method handles are immutable and have no visible state.
70 * Of course, they can be bound to underlying methods or data which exhibit state.
71 * With respect to the Java Memory Model, any method handle will behave
72 * as if all of its (internal) fields are final variables. This means that any method
73 * handle made visible to the application will always be fully formed.
74 * This is true even if the method handle is published through a shared
75 * variable in a data race.
76 * <p>
77 * Method handles cannot be subclassed by the user.
78 * Implementations may (or may not) create internal subclasses of {@code MethodHandle}
79 * which may be visible via the {@link java.lang.Object#getClass Object.getClass}
80 * operation. The programmer should not draw conclusions about a method handle
81 * from its specific class, as the method handle class hierarchy (if any)
82 * may change from time to time or across implementations from different vendors.
83 *
84 * <h1>Method handle compilation</h1>
85 * A Java method call expression naming {@code invokeExact} or {@code invoke}
86 * can invoke a method handle from Java source code.
87 * From the viewpoint of source code, these methods can take any arguments
88 * and their result can be cast to any return type.
89 * Formally this is accomplished by giving the invoker methods
90 * {@code Object} return types and variable arity {@code Object} arguments,
91 * but they have an additional quality called <em>signature polymorphism</em>
92 * which connects this freedom of invocation directly to the JVM execution stack.
93 * <p>
94 * As is usual with virtual methods, source-level calls to {@code invokeExact}
95 * and {@code invoke} compile to an {@code invokevirtual} instruction.
96 * More unusually, the compiler must record the actual argument types,
97 * and may not perform method invocation conversions on the arguments.
98 * Instead, it must push them on the stack according to their own unconverted types.
99 * The method handle object itself is pushed on the stack before the arguments.
100 * The compiler then calls the method handle with a symbolic type descriptor which
101 * describes the argument and return types.
102 * <p>
103 * To issue a complete symbolic type descriptor, the compiler must also determine
104 * the return type. This is based on a cast on the method invocation expression,
105 * if there is one, or else {@code Object} if the invocation is an expression
106 * or else {@code void} if the invocation is a statement.
107 * The cast may be to a primitive type (but not {@code void}).
108 * <p>
109 * As a corner case, an uncasted {@code null} argument is given
110 * a symbolic type descriptor of {@code java.lang.Void}.
111 * The ambiguity with the type {@code Void} is harmless, since there are no references of type
112 * {@code Void} except the null reference.
113 *
114 * <h1>Method handle invocation</h1>
115 * The first time a {@code invokevirtual} instruction is executed
116 * it is linked, by symbolically resolving the names in the instruction
117 * and verifying that the method call is statically legal.
118 * This is true of calls to {@code invokeExact} and {@code invoke}.
119 * In this case, the symbolic type descriptor emitted by the compiler is checked for
120 * correct syntax and names it contains are resolved.
121 * Thus, an {@code invokevirtual} instruction which invokes
122 * a method handle will always link, as long
123 * as the symbolic type descriptor is syntactically well-formed
124 * and the types exist.
125 * <p>
126 * When the {@code invokevirtual} is executed after linking,
127 * the receiving method handle's type is first checked by the JVM
128 * to ensure that it matches the symbolic type descriptor.
129 * If the type match fails, it means that the method which the
130 * caller is invoking is not present on the individual
131 * method handle being invoked.
132 * <p>
133 * In the case of {@code invokeExact}, the type descriptor of the invocation
134 * (after resolving symbolic type names) must exactly match the method type
137 * must be a valid argument to the receiver's {@link #asType asType} method.
138 * Thus, plain {@code invoke} is more permissive than {@code invokeExact}.
139 * <p>
140 * After type matching, a call to {@code invokeExact} directly
141 * and immediately invoke the method handle's underlying method
142 * (or other behavior, as the case may be).
143 * <p>
144 * A call to plain {@code invoke} works the same as a call to
145 * {@code invokeExact}, if the symbolic type descriptor specified by the caller
146 * exactly matches the method handle's own type.
147 * If there is a type mismatch, {@code invoke} attempts
148 * to adjust the type of the receiving method handle,
149 * as if by a call to {@link #asType asType},
150 * to obtain an exactly invokable method handle {@code M2}.
151 * This allows a more powerful negotiation of method type
152 * between caller and callee.
153 * <p>
154 * (<em>Note:</em> The adjusted method handle {@code M2} is not directly observable,
155 * and implementations are therefore not required to materialize it.)
156 *
157 * <h1>Invocation checking</h1>
158 * In typical programs, method handle type matching will usually succeed.
159 * But if a match fails, the JVM will throw a {@link WrongMethodTypeException},
160 * either directly (in the case of {@code invokeExact}) or indirectly as if
161 * by a failed call to {@code asType} (in the case of {@code invoke}).
162 * <p>
163 * Thus, a method type mismatch which might show up as a linkage error
164 * in a statically typed program can show up as
165 * a dynamic {@code WrongMethodTypeException}
166 * in a program which uses method handles.
167 * <p>
168 * Because method types contain "live" {@code Class} objects,
169 * method type matching takes into account both types names and class loaders.
170 * Thus, even if a method handle {@code M} is created in one
171 * class loader {@code L1} and used in another {@code L2},
172 * method handle calls are type-safe, because the caller's symbolic type
173 * descriptor, as resolved in {@code L2},
174 * is matched against the original callee method's symbolic type descriptor,
175 * as resolved in {@code L1}.
176 * The resolution in {@code L1} happens when {@code M} is created
177 * and its type is assigned, while the resolution in {@code L2} happens
178 * when the {@code invokevirtual} instruction is linked.
179 * <p>
180 * Apart from the checking of type descriptors,
181 * a method handle's capability to call its underlying method is unrestricted.
182 * If a method handle is formed on a non-public method by a class
183 * that has access to that method, the resulting handle can be used
184 * in any place by any caller who receives a reference to it.
185 * <p>
186 * Unlike with the Core Reflection API, where access is checked every time
187 * a reflective method is invoked,
188 * method handle access checking is performed
189 * <a href="MethodHandles.Lookup.html#access">when the method handle is created</a>.
190 * In the case of {@code ldc} (see below), access checking is performed as part of linking
191 * the constant pool entry underlying the constant method handle.
192 * <p>
193 * Thus, handles to non-public methods, or to methods in non-public classes,
194 * should generally be kept secret.
195 * They should not be passed to untrusted code unless their use from
196 * the untrusted code would be harmless.
197 *
198 * <h1>Method handle creation</h1>
199 * Java code can create a method handle that directly accesses
200 * any method, constructor, or field that is accessible to that code.
201 * This is done via a reflective, capability-based API called
202 * {@link java.lang.invoke.MethodHandles.Lookup MethodHandles.Lookup}
203 * For example, a static method handle can be obtained
204 * from {@link java.lang.invoke.MethodHandles.Lookup#findStatic Lookup.findStatic}.
205 * There are also conversion methods from Core Reflection API objects,
206 * such as {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
207 * <p>
208 * Like classes and strings, method handles that correspond to accessible
209 * fields, methods, and constructors can also be represented directly
210 * in a class file's constant pool as constants to be loaded by {@code ldc} bytecodes.
211 * A new type of constant pool entry, {@code CONSTANT_MethodHandle},
212 * refers directly to an associated {@code CONSTANT_Methodref},
213 * {@code CONSTANT_InterfaceMethodref}, or {@code CONSTANT_Fieldref}
214 * constant pool entry.
215 * (For full details on method handle constants,
216 * see sections 4.4.8 and 5.4.3.5 of the Java Virtual Machine Specification.)
217 * <p>
218 * Method handles produced by lookups or constant loads from methods or
232 * their corresponding bytecode instructions, and the {@code ldc} instruction
233 * will throw corresponding linkage errors if the bytecode behaviors would
234 * throw such errors.
235 * <p>
236 * As a corollary of this, access to protected members is restricted
237 * to receivers only of the accessing class, or one of its subclasses,
238 * and the accessing class must in turn be a subclass (or package sibling)
239 * of the protected member's defining class.
240 * If a method reference refers to a protected non-static method or field
241 * of a class outside the current package, the receiver argument will
242 * be narrowed to the type of the accessing class.
243 * <p>
244 * When a method handle to a virtual method is invoked, the method is
245 * always looked up in the receiver (that is, the first argument).
246 * <p>
247 * A non-virtual method handle to a specific virtual method implementation
248 * can also be created. These do not perform virtual lookup based on
249 * receiver type. Such a method handle simulates the effect of
250 * an {@code invokespecial} instruction to the same method.
251 *
252 * <h1>Usage examples</h1>
253 * Here are some examples of usage:
254 * <p><blockquote><pre>{@code
255 Object x, y; String s; int i;
256 MethodType mt; MethodHandle mh;
257 MethodHandles.Lookup lookup = MethodHandles.lookup();
258 // mt is (char,char)String
259 mt = MethodType.methodType(String.class, char.class, char.class);
260 mh = lookup.findVirtual(String.class, "replace", mt);
261 s = (String) mh.invokeExact("daddy",'d','n');
262 // invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
263 assertEquals(s, "nanny");
264 // weakly typed invocation (using MHs.invoke)
265 s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
266 assertEquals(s, "savvy");
267 // mt is (Object[])List
268 mt = MethodType.methodType(java.util.List.class, Object[].class);
269 mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
270 assert(mh.isVarargsCollector());
271 x = mh.invoke("one", "two");
272 // invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
278 // invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
279 assertEquals(x, java.util.Arrays.asList(1,2,3));
280 // mt is ()int
281 mt = MethodType.methodType(int.class);
282 mh = lookup.findVirtual(java.util.List.class, "size", mt);
283 i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
284 // invokeExact(Ljava/util/List;)I
285 assert(i == 3);
286 mt = MethodType.methodType(void.class, String.class);
287 mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
288 mh.invokeExact(System.out, "Hello, world.");
289 // invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
290 * }</pre></blockquote>
291 * Each of the above calls to {@code invokeExact} or plain {@code invoke}
292 * generates a single invokevirtual instruction with
293 * the symbolic type descriptor indicated in the following comment.
294 * In these examples, the helper method {@code assertEquals} is assumed to
295 * be a method which calls {@link java.util.Objects#equals(Object,Object) Objects.equals }
296 * on its arguments, and asserts that the result is true.
297 *
298 * <h1>Exceptions</h1>
299 * The methods {@code invokeExact} and {@code invoke} are declared
300 * to throw {@link java.lang.Throwable Throwable},
301 * which is to say that there is no static restriction on what a method handle
302 * can throw. Since the JVM does not distinguish between checked
303 * and unchecked exceptions (other than by their class, of course),
304 * there is no particular effect on bytecode shape from ascribing
305 * checked exceptions to method handle invocations. But in Java source
306 * code, methods which perform method handle calls must either explicitly
307 * throw {@code Throwable}, or else must catch all
308 * throwables locally, rethrowing only those which are legal in the context,
309 * and wrapping ones which are illegal.
310 *
311 * <h1><a name="sigpoly"></a>Signature polymorphism</h1>
312 * The unusual compilation and linkage behavior of
313 * {@code invokeExact} and plain {@code invoke}
314 * is referenced by the term <em>signature polymorphism</em>.
315 * As defined in the Java Language Specification,
316 * a signature polymorphic method is one which can operate with
317 * any of a wide range of call signatures and return types.
318 * <p>
319 * In source code, a call to a signature polymorphic method will
320 * compile, regardless of the requested symbolic type descriptor.
321 * As usual, the Java compiler emits an {@code invokevirtual}
322 * instruction with the given symbolic type descriptor against the named method.
323 * The unusual part is that the symbolic type descriptor is derived from
324 * the actual argument and return types, not from the method declaration.
325 * <p>
326 * When the JVM processes bytecode containing signature polymorphic calls,
327 * it will successfully link any such call, regardless of its symbolic type descriptor.
328 * (In order to retain type safety, the JVM will guard such calls with suitable
329 * dynamic type checks, as described elsewhere.)
330 * <p>
331 * Bytecode generators, including the compiler back end, are required to emit
332 * untransformed symbolic type descriptors for these methods.
333 * Tools which determine symbolic linkage are required to accept such
334 * untransformed descriptors, without reporting linkage errors.
335 *
336 * <h1>Interoperation between method handles and the Core Reflection API</h1>
337 * Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup Lookup} API,
338 * any class member represented by a Core Reflection API object
339 * can be converted to a behaviorally equivalent method handle.
340 * For example, a reflective {@link java.lang.reflect.Method Method} can
341 * be converted to a method handle using
342 * {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
343 * The resulting method handles generally provide more direct and efficient
344 * access to the underlying class members.
345 * <p>
346 * As a special case,
347 * when the Core Reflection API is used to view the signature polymorphic
348 * methods {@code invokeExact} or plain {@code invoke} in this class,
349 * they appear as ordinary non-polymorphic methods.
350 * Their reflective appearance, as viewed by
351 * {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod},
352 * is unaffected by their special status in this API.
353 * For example, {@link java.lang.reflect.Method#getModifiers Method.getModifiers}
354 * will report exactly those modifier bits required for any similarly
355 * declared method, including in this case {@code native} and {@code varargs} bits.
356 * <p>
358 * invoked via {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.
359 * However, such reflective calls do not result in method handle invocations.
360 * Such a call, if passed the required argument
361 * (a single one, of type {@code Object[]}), will ignore the argument and
362 * will throw an {@code UnsupportedOperationException}.
363 * <p>
364 * Since {@code invokevirtual} instructions can natively
365 * invoke method handles under any symbolic type descriptor, this reflective view conflicts
366 * with the normal presentation of these methods via bytecodes.
367 * Thus, these two native methods, when reflectively viewed by
368 * {@code Class.getDeclaredMethod}, may be regarded as placeholders only.
369 * <p>
370 * In order to obtain an invoker method for a particular type descriptor,
371 * use {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker},
372 * or {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}.
373 * The {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual}
374 * API is also able to return a method handle
375 * to call {@code invokeExact} or plain {@code invoke},
376 * for any specified type descriptor .
377 *
378 * <h1>Interoperation between method handles and Java generics</h1>
379 * A method handle can be obtained on a method, constructor, or field
380 * which is declared with Java generic types.
381 * As with the Core Reflection API, the type of the method handle
382 * will constructed from the erasure of the source-level type.
383 * When a method handle is invoked, the types of its arguments
384 * or the return value cast type may be generic types or type instances.
385 * If this occurs, the compiler will replace those
386 * types by their erasures when it constructs the symbolic type descriptor
387 * for the {@code invokevirtual} instruction.
388 * <p>
389 * Method handles do not represent
390 * their function-like types in terms of Java parameterized (generic) types,
391 * because there are three mismatches between function-like types and parameterized
392 * Java types.
393 * <ul>
394 * <li>Method types range over all possible arities,
395 * from no arguments to up to 255 of arguments (a limit imposed by the JVM).
396 * Generics are not variadic, and so cannot represent this.</li>
397 * <li>Method types can specify arguments of primitive types,
398 * which Java generic types cannot range over.</li>
440 type.getClass(); // explicit NPE
441 form.getClass(); // explicit NPE
442 this.type = type;
443 this.form = form;
444
445 form.prepare(); // TO DO: Try to delay this step until just before invocation.
446 }
447
448 /**
449 * Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match.
450 * The symbolic type descriptor at the call site of {@code invokeExact} must
451 * exactly match this method handle's {@link #type type}.
452 * No conversions are allowed on arguments or return values.
453 * <p>
454 * When this method is observed via the Core Reflection API,
455 * it will appear as a single native method, taking an object array and returning an object.
456 * If this native method is invoked directly via
457 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
458 * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
459 * it will throw an {@code UnsupportedOperationException}.
460 * @param args the signature-polymorphic parameter list, statically represented using varargs
461 * @return the signature-polymorphic result, statically represented using {@code Object}
462 * @throws WrongMethodTypeException if the target's type is not identical with the caller's symbolic type descriptor
463 * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
464 */
465 public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable;
466
467 /**
468 * Invokes the method handle, allowing any caller type descriptor,
469 * and optionally performing conversions on arguments and return values.
470 * <p>
471 * If the call site's symbolic type descriptor exactly matches this method handle's {@link #type type},
472 * the call proceeds as if by {@link #invokeExact invokeExact}.
473 * <p>
474 * Otherwise, the call proceeds as if this method handle were first
475 * adjusted by calling {@link #asType asType} to adjust this method handle
476 * to the required type, and then the call proceeds as if by
477 * {@link #invokeExact invokeExact} on the adjusted method handle.
478 * <p>
479 * There is no guarantee that the {@code asType} call is actually made.
480 * If the JVM can predict the results of making the call, it may perform
481 * adaptations directly on the caller's arguments,
482 * and call the target method handle according to its own exact type.
483 * <p>
484 * The resolved type descriptor at the call site of {@code invoke} must
485 * be a valid argument to the receivers {@code asType} method.
486 * In particular, the caller must specify the same argument arity
487 * as the callee's type,
488 * if the callee is not a {@linkplain #asVarargsCollector variable arity collector}.
489 * <p>
490 * When this method is observed via the Core Reflection API,
491 * it will appear as a single native method, taking an object array and returning an object.
492 * If this native method is invoked directly via
493 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
494 * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
495 * it will throw an {@code UnsupportedOperationException}.
496 * @param args the signature-polymorphic parameter list, statically represented using varargs
497 * @return the signature-polymorphic result, statically represented using {@code Object}
498 * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's symbolic type descriptor
499 * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails
500 * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
501 */
502 public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable;
503
504 /**
505 * Private method for trusted invocation of a method handle respecting simplified signatures.
506 * Type mismatches will not throw {@code WrongMethodTypeException}, but could crash the JVM.
507 * <p>
508 * The caller signature is restricted to the following basic types:
509 * Object, int, long, float, double, and void return.
510 * <p>
511 * The caller is responsible for maintaining type correctness by ensuring
512 * that the each outgoing argument value is a member of the range of the corresponding
513 * callee argument type.
514 * (The caller should therefore issue appropriate casts and integer narrowing
515 * operations on outgoing argument values.)
516 * The caller can assume that the incoming result value is part of the range
517 * of the callee's return type.
518 * @param args the signature-polymorphic parameter list, statically represented using varargs
519 * @return the signature-polymorphic result, statically represented using {@code Object}
520 */
521 /*non-public*/ final native @PolymorphicSignature Object invokeBasic(Object... args) throws Throwable;
522
523 /**
524 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeVirtual}.
525 * The caller signature is restricted to basic types as with {@code invokeBasic}.
526 * The trailing (not leading) argument must be a MemberName.
527 * @param args the signature-polymorphic parameter list, statically represented using varargs
528 * @return the signature-polymorphic result, statically represented using {@code Object}
529 */
530 /*non-public*/ static native @PolymorphicSignature Object linkToVirtual(Object... args) throws Throwable;
531
532 /**
533 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeStatic}.
534 * The caller signature is restricted to basic types as with {@code invokeBasic}.
535 * The trailing (not leading) argument must be a MemberName.
536 * @param args the signature-polymorphic parameter list, statically represented using varargs
537 * @return the signature-polymorphic result, statically represented using {@code Object}
538 */
539 /*non-public*/ static native @PolymorphicSignature Object linkToStatic(Object... args) throws Throwable;
540
541 /**
542 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeSpecial}.
543 * The caller signature is restricted to basic types as with {@code invokeBasic}.
544 * The trailing (not leading) argument must be a MemberName.
545 * @param args the signature-polymorphic parameter list, statically represented using varargs
546 * @return the signature-polymorphic result, statically represented using {@code Object}
547 */
548 /*non-public*/ static native @PolymorphicSignature Object linkToSpecial(Object... args) throws Throwable;
549
550 /**
551 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeInterface}.
552 * The caller signature is restricted to basic types as with {@code invokeBasic}.
553 * The trailing (not leading) argument must be a MemberName.
554 * @param args the signature-polymorphic parameter list, statically represented using varargs
555 * @return the signature-polymorphic result, statically represented using {@code Object}
556 */
557 /*non-public*/ static native @PolymorphicSignature Object linkToInterface(Object... args) throws Throwable;
558
559 /**
560 * Performs a variable arity invocation, passing the arguments in the given array
561 * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
562 * which mentions only the type {@code Object}, and whose arity is the length
563 * of the argument array.
564 * <p>
565 * Specifically, execution proceeds as if by the following steps,
566 * although the methods are not guaranteed to be called if the JVM
567 * can predict their effects.
568 * <ul>
569 * <li>Determine the length of the argument array as {@code N}.
570 * For a null reference, {@code N=0}. </li>
571 * <li>Determine the general type {@code TN} of {@code N} arguments as
572 * as {@code TN=MethodType.genericMethodType(N)}.</li>
573 * <li>Force the original target method handle {@code MH0} to the
574 * required type, as {@code MH1 = MH0.asType(TN)}. </li>
575 * <li>Spread the array into {@code N} separate arguments {@code A0, ...}. </li>
|