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