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