• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2008, 2017, 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.lang.reflect.*;
29 import java.nio.ByteOrder;
30 import java.util.List;
31 import java.util.Arrays;
32 import java.util.ArrayList;
33 import java.util.NoSuchElementException;
34 
35 import sun.invoke.util.VerifyAccess;
36 import sun.invoke.util.Wrapper;
37 import sun.reflect.Reflection;
38 
39 import static java.lang.invoke.MethodHandleStatics.*;
40 
41 /**
42  * This class consists exclusively of static methods that operate on or return
43  * method handles. They fall into several categories:
44  * <ul>
45  * <li>Lookup methods which help create method handles for methods and fields.
46  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
47  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
48  * </ul>
49  * <p>
50  * @author John Rose, JSR 292 EG
51  * @since 1.7
52  */
53 public class MethodHandles {
54 
MethodHandles()55     private MethodHandles() { }  // do not instantiate
56 
57     // Android-changed: We do not use MemberName / MethodHandleImpl.
58     //
59     // private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
60     // static { MethodHandleImpl.initStatics(); }
61     // See IMPL_LOOKUP below.
62 
63     //// Method handle creation from ordinary methods.
64 
65     /**
66      * Returns a {@link Lookup lookup object} with
67      * full capabilities to emulate all supported bytecode behaviors of the caller.
68      * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller.
69      * Factory methods on the lookup object can create
70      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
71      * for any member that the caller has access to via bytecodes,
72      * including protected and private fields and methods.
73      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
74      * Do not store it in place where untrusted code can access it.
75      * <p>
76      * This method is caller sensitive, which means that it may return different
77      * values to different callers.
78      * <p>
79      * For any given caller class {@code C}, the lookup object returned by this call
80      * has equivalent capabilities to any lookup object
81      * supplied by the JVM to the bootstrap method of an
82      * <a href="package-summary.html#indyinsn">invokedynamic instruction</a>
83      * executing in the same caller class {@code C}.
84      * @return a lookup object for the caller of this method, with private access
85      */
86     // Android-changed: Remove caller sensitive.
87     // @CallerSensitive
lookup()88     public static Lookup lookup() {
89         return new Lookup(Reflection.getCallerClass());
90     }
91 
92     /**
93      * Returns a {@link Lookup lookup object} which is trusted minimally.
94      * It can only be used to create method handles to
95      * publicly accessible fields and methods.
96      * <p>
97      * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class}
98      * of this lookup object will be {@link java.lang.Object}.
99      *
100      * <p style="font-size:smaller;">
101      * <em>Discussion:</em>
102      * The lookup class can be changed to any other class {@code C} using an expression of the form
103      * {@link Lookup#in publicLookup().in(C.class)}.
104      * Since all classes have equal access to public names,
105      * such a change would confer no new access rights.
106      * A public lookup object is always subject to
107      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
108      * Also, it cannot access
109      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
110      * @return a lookup object which is trusted minimally
111      */
publicLookup()112     public static Lookup publicLookup() {
113         return Lookup.PUBLIC_LOOKUP;
114     }
115 
116     /**
117      * Performs an unchecked "crack" of a
118      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
119      * The result is as if the user had obtained a lookup object capable enough
120      * to crack the target method handle, called
121      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
122      * on the target to obtain its symbolic reference, and then called
123      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
124      * to resolve the symbolic reference to a member.
125      * <p>
126      * If there is a security manager, its {@code checkPermission} method
127      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
128      * @param <T> the desired type of the result, either {@link Member} or a subtype
129      * @param target a direct method handle to crack into symbolic reference components
130      * @param expected a class object representing the desired result type {@code T}
131      * @return a reference to the method, constructor, or field object
132      * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
133      * @exception NullPointerException if either argument is {@code null}
134      * @exception IllegalArgumentException if the target is not a direct method handle
135      * @exception ClassCastException if the member is not of the expected type
136      * @since 1.8
137      */
138     public static <T extends Member> T
reflectAs(Class<T> expected, MethodHandle target)139     reflectAs(Class<T> expected, MethodHandle target) {
140         MethodHandleImpl directTarget = getMethodHandleImpl(target);
141         // Given that this is specified to be an "unchecked" crack, we can directly allocate
142         // a member from the underlying ArtField / Method and bypass all associated access checks.
143         return expected.cast(directTarget.getMemberInternal());
144     }
145 
146     /**
147      * A <em>lookup object</em> is a factory for creating method handles,
148      * when the creation requires access checking.
149      * Method handles do not perform
150      * access checks when they are called, but rather when they are created.
151      * Therefore, method handle access
152      * restrictions must be enforced when a method handle is created.
153      * The caller class against which those restrictions are enforced
154      * is known as the {@linkplain #lookupClass lookup class}.
155      * <p>
156      * A lookup class which needs to create method handles will call
157      * {@link #lookup MethodHandles.lookup} to create a factory for itself.
158      * When the {@code Lookup} factory object is created, the identity of the lookup class is
159      * determined, and securely stored in the {@code Lookup} object.
160      * The lookup class (or its delegates) may then use factory methods
161      * on the {@code Lookup} object to create method handles for access-checked members.
162      * This includes all methods, constructors, and fields which are allowed to the lookup class,
163      * even private ones.
164      *
165      * <h1><a name="lookups"></a>Lookup Factory Methods</h1>
166      * The factory methods on a {@code Lookup} object correspond to all major
167      * use cases for methods, constructors, and fields.
168      * Each method handle created by a factory method is the functional
169      * equivalent of a particular <em>bytecode behavior</em>.
170      * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
171      * Here is a summary of the correspondence between these factory methods and
172      * the behavior the resulting method handles:
173      * <table border=1 cellpadding=5 summary="lookup method behaviors">
174      * <tr>
175      *     <th><a name="equiv"></a>lookup expression</th>
176      *     <th>member</th>
177      *     <th>bytecode behavior</th>
178      * </tr>
179      * <tr>
180      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td>
181      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
182      * </tr>
183      * <tr>
184      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td>
185      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
186      * </tr>
187      * <tr>
188      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td>
189      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
190      * </tr>
191      * <tr>
192      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td>
193      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
194      * </tr>
195      * <tr>
196      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td>
197      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
198      * </tr>
199      * <tr>
200      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td>
201      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
202      * </tr>
203      * <tr>
204      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td>
205      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
206      * </tr>
207      * <tr>
208      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td>
209      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
210      * </tr>
211      * <tr>
212      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td>
213      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
214      * </tr>
215      * <tr>
216      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td>
217      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
218      * </tr>
219      * <tr>
220      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
221      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
222      * </tr>
223      * <tr>
224      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td>
225      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
226      * </tr>
227      * <tr>
228      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
229      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
230      * </tr>
231      * </table>
232      *
233      * Here, the type {@code C} is the class or interface being searched for a member,
234      * documented as a parameter named {@code refc} in the lookup methods.
235      * The method type {@code MT} is composed from the return type {@code T}
236      * and the sequence of argument types {@code A*}.
237      * The constructor also has a sequence of argument types {@code A*} and
238      * is deemed to return the newly-created object of type {@code C}.
239      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
240      * The formal parameter {@code this} stands for the self-reference of type {@code C};
241      * if it is present, it is always the leading argument to the method handle invocation.
242      * (In the case of some {@code protected} members, {@code this} may be
243      * restricted in type to the lookup class; see below.)
244      * The name {@code arg} stands for all the other method handle arguments.
245      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
246      * stands for a null reference if the accessed method or field is static,
247      * and {@code this} otherwise.
248      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
249      * for reflective objects corresponding to the given members.
250      * <p>
251      * In cases where the given member is of variable arity (i.e., a method or constructor)
252      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
253      * In all other cases, the returned method handle will be of fixed arity.
254      * <p style="font-size:smaller;">
255      * <em>Discussion:</em>
256      * The equivalence between looked-up method handles and underlying
257      * class members and bytecode behaviors
258      * can break down in a few ways:
259      * <ul style="font-size:smaller;">
260      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
261      * the lookup can still succeed, even when there is no equivalent
262      * Java expression or bytecoded constant.
263      * <li>Likewise, if {@code T} or {@code MT}
264      * is not symbolically accessible from the lookup class's loader,
265      * the lookup can still succeed.
266      * For example, lookups for {@code MethodHandle.invokeExact} and
267      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
268      * <li>If there is a security manager installed, it can forbid the lookup
269      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
270      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
271      * constant is not subject to security manager checks.
272      * <li>If the looked-up method has a
273      * <a href="MethodHandle.html#maxarity">very large arity</a>,
274      * the method handle creation may fail, due to the method handle
275      * type having too many parameters.
276      * </ul>
277      *
278      * <h1><a name="access"></a>Access checking</h1>
279      * Access checks are applied in the factory methods of {@code Lookup},
280      * when a method handle is created.
281      * This is a key difference from the Core Reflection API, since
282      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
283      * performs access checking against every caller, on every call.
284      * <p>
285      * All access checks start from a {@code Lookup} object, which
286      * compares its recorded lookup class against all requests to
287      * create method handles.
288      * A single {@code Lookup} object can be used to create any number
289      * of access-checked method handles, all checked against a single
290      * lookup class.
291      * <p>
292      * A {@code Lookup} object can be shared with other trusted code,
293      * such as a metaobject protocol.
294      * A shared {@code Lookup} object delegates the capability
295      * to create method handles on private members of the lookup class.
296      * Even if privileged code uses the {@code Lookup} object,
297      * the access checking is confined to the privileges of the
298      * original lookup class.
299      * <p>
300      * A lookup can fail, because
301      * the containing class is not accessible to the lookup class, or
302      * because the desired class member is missing, or because the
303      * desired class member is not accessible to the lookup class, or
304      * because the lookup object is not trusted enough to access the member.
305      * In any of these cases, a {@code ReflectiveOperationException} will be
306      * thrown from the attempted lookup.  The exact class will be one of
307      * the following:
308      * <ul>
309      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
310      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
311      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
312      * </ul>
313      * <p>
314      * In general, the conditions under which a method handle may be
315      * looked up for a method {@code M} are no more restrictive than the conditions
316      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
317      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
318      * a method handle lookup will generally raise a corresponding
319      * checked exception, such as {@code NoSuchMethodException}.
320      * And the effect of invoking the method handle resulting from the lookup
321      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
322      * to executing the compiled, verified, and resolved call to {@code M}.
323      * The same point is true of fields and constructors.
324      * <p style="font-size:smaller;">
325      * <em>Discussion:</em>
326      * Access checks only apply to named and reflected methods,
327      * constructors, and fields.
328      * Other method handle creation methods, such as
329      * {@link MethodHandle#asType MethodHandle.asType},
330      * do not require any access checks, and are used
331      * independently of any {@code Lookup} object.
332      * <p>
333      * If the desired member is {@code protected}, the usual JVM rules apply,
334      * including the requirement that the lookup class must be either be in the
335      * same package as the desired member, or must inherit that member.
336      * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.)
337      * In addition, if the desired member is a non-static field or method
338      * in a different package, the resulting method handle may only be applied
339      * to objects of the lookup class or one of its subclasses.
340      * This requirement is enforced by narrowing the type of the leading
341      * {@code this} parameter from {@code C}
342      * (which will necessarily be a superclass of the lookup class)
343      * to the lookup class itself.
344      * <p>
345      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
346      * that the receiver argument must match both the resolved method <em>and</em>
347      * the current class.  Again, this requirement is enforced by narrowing the
348      * type of the leading parameter to the resulting method handle.
349      * (See the Java Virtual Machine Specification, section 4.10.1.9.)
350      * <p>
351      * The JVM represents constructors and static initializer blocks as internal methods
352      * with special names ({@code "<init>"} and {@code "<clinit>"}).
353      * The internal syntax of invocation instructions allows them to refer to such internal
354      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
355      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
356      * <p>
357      * In some cases, access between nested classes is obtained by the Java compiler by creating
358      * an wrapper method to access a private method of another class
359      * in the same top-level declaration.
360      * For example, a nested class {@code C.D}
361      * can access private members within other related classes such as
362      * {@code C}, {@code C.D.E}, or {@code C.B},
363      * but the Java compiler may need to generate wrapper methods in
364      * those related classes.  In such cases, a {@code Lookup} object on
365      * {@code C.E} would be unable to those private members.
366      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
367      * which can transform a lookup on {@code C.E} into one on any of those other
368      * classes, without special elevation of privilege.
369      * <p>
370      * The accesses permitted to a given lookup object may be limited,
371      * according to its set of {@link #lookupModes lookupModes},
372      * to a subset of members normally accessible to the lookup class.
373      * For example, the {@link #publicLookup publicLookup}
374      * method produces a lookup object which is only allowed to access
375      * public members in public classes.
376      * The caller sensitive method {@link #lookup lookup}
377      * produces a lookup object with full capabilities relative to
378      * its caller class, to emulate all supported bytecode behaviors.
379      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
380      * with fewer access modes than the original lookup object.
381      *
382      * <p style="font-size:smaller;">
383      * <a name="privacc"></a>
384      * <em>Discussion of private access:</em>
385      * We say that a lookup has <em>private access</em>
386      * if its {@linkplain #lookupModes lookup modes}
387      * include the possibility of accessing {@code private} members.
388      * As documented in the relevant methods elsewhere,
389      * only lookups with private access possess the following capabilities:
390      * <ul style="font-size:smaller;">
391      * <li>access private fields, methods, and constructors of the lookup class
392      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
393      *     such as {@code Class.forName}
394      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
395      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
396      *     for classes accessible to the lookup class
397      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
398      *     within the same package member
399      * </ul>
400      * <p style="font-size:smaller;">
401      * Each of these permissions is a consequence of the fact that a lookup object
402      * with private access can be securely traced back to an originating class,
403      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
404      * can be reliably determined and emulated by method handles.
405      *
406      * <h1><a name="secmgr"></a>Security manager interactions</h1>
407      * Although bytecode instructions can only refer to classes in
408      * a related class loader, this API can search for methods in any
409      * class, as long as a reference to its {@code Class} object is
410      * available.  Such cross-loader references are also possible with the
411      * Core Reflection API, and are impossible to bytecode instructions
412      * such as {@code invokestatic} or {@code getfield}.
413      * There is a {@linkplain java.lang.SecurityManager security manager API}
414      * to allow applications to check such cross-loader references.
415      * These checks apply to both the {@code MethodHandles.Lookup} API
416      * and the Core Reflection API
417      * (as found on {@link java.lang.Class Class}).
418      * <p>
419      * If a security manager is present, member lookups are subject to
420      * additional checks.
421      * From one to three calls are made to the security manager.
422      * Any of these calls can refuse access by throwing a
423      * {@link java.lang.SecurityException SecurityException}.
424      * Define {@code smgr} as the security manager,
425      * {@code lookc} as the lookup class of the current lookup object,
426      * {@code refc} as the containing class in which the member
427      * is being sought, and {@code defc} as the class in which the
428      * member is actually defined.
429      * The value {@code lookc} is defined as <em>not present</em>
430      * if the current lookup object does not have
431      * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
432      * The calls are made according to the following rules:
433      * <ul>
434      * <li><b>Step 1:</b>
435      *     If {@code lookc} is not present, or if its class loader is not
436      *     the same as or an ancestor of the class loader of {@code refc},
437      *     then {@link SecurityManager#checkPackageAccess
438      *     smgr.checkPackageAccess(refcPkg)} is called,
439      *     where {@code refcPkg} is the package of {@code refc}.
440      * <li><b>Step 2:</b>
441      *     If the retrieved member is not public and
442      *     {@code lookc} is not present, then
443      *     {@link SecurityManager#checkPermission smgr.checkPermission}
444      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
445      * <li><b>Step 3:</b>
446      *     If the retrieved member is not public,
447      *     and if {@code lookc} is not present,
448      *     and if {@code defc} and {@code refc} are different,
449      *     then {@link SecurityManager#checkPackageAccess
450      *     smgr.checkPackageAccess(defcPkg)} is called,
451      *     where {@code defcPkg} is the package of {@code defc}.
452      * </ul>
453      * Security checks are performed after other access checks have passed.
454      * Therefore, the above rules presuppose a member that is public,
455      * or else that is being accessed from a lookup class that has
456      * rights to access the member.
457      *
458      * <h1><a name="callsens"></a>Caller sensitive methods</h1>
459      * A small number of Java methods have a special property called caller sensitivity.
460      * A <em>caller-sensitive</em> method can behave differently depending on the
461      * identity of its immediate caller.
462      * <p>
463      * If a method handle for a caller-sensitive method is requested,
464      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
465      * but they take account of the lookup class in a special way.
466      * The resulting method handle behaves as if it were called
467      * from an instruction contained in the lookup class,
468      * so that the caller-sensitive method detects the lookup class.
469      * (By contrast, the invoker of the method handle is disregarded.)
470      * Thus, in the case of caller-sensitive methods,
471      * different lookup classes may give rise to
472      * differently behaving method handles.
473      * <p>
474      * In cases where the lookup object is
475      * {@link #publicLookup publicLookup()},
476      * or some other lookup object without
477      * <a href="MethodHandles.Lookup.html#privacc">private access</a>,
478      * the lookup class is disregarded.
479      * In such cases, no caller-sensitive method handle can be created,
480      * access is forbidden, and the lookup fails with an
481      * {@code IllegalAccessException}.
482      * <p style="font-size:smaller;">
483      * <em>Discussion:</em>
484      * For example, the caller-sensitive method
485      * {@link java.lang.Class#forName(String) Class.forName(x)}
486      * can return varying classes or throw varying exceptions,
487      * depending on the class loader of the class that calls it.
488      * A public lookup of {@code Class.forName} will fail, because
489      * there is no reasonable way to determine its bytecode behavior.
490      * <p style="font-size:smaller;">
491      * If an application caches method handles for broad sharing,
492      * it should use {@code publicLookup()} to create them.
493      * If there is a lookup of {@code Class.forName}, it will fail,
494      * and the application must take appropriate action in that case.
495      * It may be that a later lookup, perhaps during the invocation of a
496      * bootstrap method, can incorporate the specific identity
497      * of the caller, making the method accessible.
498      * <p style="font-size:smaller;">
499      * The function {@code MethodHandles.lookup} is caller sensitive
500      * so that there can be a secure foundation for lookups.
501      * Nearly all other methods in the JSR 292 API rely on lookup
502      * objects to check access requests.
503      */
504     // Android-changed: Change link targets from MethodHandles#[public]Lookup to
505     // #[public]Lookup to work around complaints from javadoc.
506     public static final
507     class Lookup {
508         /** The class on behalf of whom the lookup is being performed. */
509         /* @NonNull */ private final Class<?> lookupClass;
510 
511         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
512         private final int allowedModes;
513 
514         /** A single-bit mask representing {@code public} access,
515          *  which may contribute to the result of {@link #lookupModes lookupModes}.
516          *  The value, {@code 0x01}, happens to be the same as the value of the
517          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
518          */
519         public static final int PUBLIC = Modifier.PUBLIC;
520 
521         /** A single-bit mask representing {@code private} access,
522          *  which may contribute to the result of {@link #lookupModes lookupModes}.
523          *  The value, {@code 0x02}, happens to be the same as the value of the
524          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
525          */
526         public static final int PRIVATE = Modifier.PRIVATE;
527 
528         /** A single-bit mask representing {@code protected} access,
529          *  which may contribute to the result of {@link #lookupModes lookupModes}.
530          *  The value, {@code 0x04}, happens to be the same as the value of the
531          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
532          */
533         public static final int PROTECTED = Modifier.PROTECTED;
534 
535         /** A single-bit mask representing {@code package} access (default access),
536          *  which may contribute to the result of {@link #lookupModes lookupModes}.
537          *  The value is {@code 0x08}, which does not correspond meaningfully to
538          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
539          */
540         public static final int PACKAGE = Modifier.STATIC;
541 
542         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE);
543 
544         // Android-note: Android has no notion of a trusted lookup. If required, such lookups
545         // are performed by the runtime. As a result, we always use lookupClass, which will always
546         // be non-null in our implementation.
547         //
548         // private static final int TRUSTED   = -1;
549 
fixmods(int mods)550         private static int fixmods(int mods) {
551             mods &= (ALL_MODES - PACKAGE);
552             return (mods != 0) ? mods : PACKAGE;
553         }
554 
555         /** Tells which class is performing the lookup.  It is this class against
556          *  which checks are performed for visibility and access permissions.
557          *  <p>
558          *  The class implies a maximum level of access permission,
559          *  but the permissions may be additionally limited by the bitmask
560          *  {@link #lookupModes lookupModes}, which controls whether non-public members
561          *  can be accessed.
562          *  @return the lookup class, on behalf of which this lookup object finds members
563          */
lookupClass()564         public Class<?> lookupClass() {
565             return lookupClass;
566         }
567 
568         /** Tells which access-protection classes of members this lookup object can produce.
569          *  The result is a bit-mask of the bits
570          *  {@linkplain #PUBLIC PUBLIC (0x01)},
571          *  {@linkplain #PRIVATE PRIVATE (0x02)},
572          *  {@linkplain #PROTECTED PROTECTED (0x04)},
573          *  and {@linkplain #PACKAGE PACKAGE (0x08)}.
574          *  <p>
575          *  A freshly-created lookup object
576          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
577          *  has all possible bits set, since the caller class can access all its own members.
578          *  A lookup object on a new lookup class
579          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
580          *  may have some mode bits set to zero.
581          *  The purpose of this is to restrict access via the new lookup object,
582          *  so that it can access only names which can be reached by the original
583          *  lookup object, and also by the new lookup class.
584          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
585          */
lookupModes()586         public int lookupModes() {
587             return allowedModes & ALL_MODES;
588         }
589 
590         /** Embody the current class (the lookupClass) as a lookup class
591          * for method handle creation.
592          * Must be called by from a method in this package,
593          * which in turn is called by a method not in this package.
594          */
Lookup(Class<?> lookupClass)595         Lookup(Class<?> lookupClass) {
596             this(lookupClass, ALL_MODES);
597             // make sure we haven't accidentally picked up a privileged class:
598             checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
599         }
600 
Lookup(Class<?> lookupClass, int allowedModes)601         private Lookup(Class<?> lookupClass, int allowedModes) {
602             this.lookupClass = lookupClass;
603             this.allowedModes = allowedModes;
604         }
605 
606         /**
607          * Creates a lookup on the specified new lookup class.
608          * The resulting object will report the specified
609          * class as its own {@link #lookupClass lookupClass}.
610          * <p>
611          * However, the resulting {@code Lookup} object is guaranteed
612          * to have no more access capabilities than the original.
613          * In particular, access capabilities can be lost as follows:<ul>
614          * <li>If the new lookup class differs from the old one,
615          * protected members will not be accessible by virtue of inheritance.
616          * (Protected members may continue to be accessible because of package sharing.)
617          * <li>If the new lookup class is in a different package
618          * than the old one, protected and default (package) members will not be accessible.
619          * <li>If the new lookup class is not within the same package member
620          * as the old one, private members will not be accessible.
621          * <li>If the new lookup class is not accessible to the old lookup class,
622          * then no members, not even public members, will be accessible.
623          * (In all other cases, public members will continue to be accessible.)
624          * </ul>
625          *
626          * @param requestedLookupClass the desired lookup class for the new lookup object
627          * @return a lookup object which reports the desired lookup class
628          * @throws NullPointerException if the argument is null
629          */
in(Class<?> requestedLookupClass)630         public Lookup in(Class<?> requestedLookupClass) {
631             requestedLookupClass.getClass();  // null check
632             // Android-changed: There's no notion of a trusted lookup.
633             // if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
634             //    return new Lookup(requestedLookupClass, ALL_MODES);
635 
636             if (requestedLookupClass == this.lookupClass)
637                 return this;  // keep same capabilities
638             int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
639             if ((newModes & PACKAGE) != 0
640                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
641                 newModes &= ~(PACKAGE|PRIVATE);
642             }
643             // Allow nestmate lookups to be created without special privilege:
644             if ((newModes & PRIVATE) != 0
645                 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
646                 newModes &= ~PRIVATE;
647             }
648             if ((newModes & PUBLIC) != 0
649                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
650                 // The requested class it not accessible from the lookup class.
651                 // No permissions.
652                 newModes = 0;
653             }
654             checkUnprivilegedlookupClass(requestedLookupClass, newModes);
655             return new Lookup(requestedLookupClass, newModes);
656         }
657 
658         // Make sure outer class is initialized first.
659         //
660         // Android-changed: Removed unnecessary reference to IMPL_NAMES.
661         // static { IMPL_NAMES.getClass(); }
662 
663         /** Version of lookup which is trusted minimally.
664          *  It can only be used to create method handles to
665          *  publicly accessible members.
666          */
667         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, PUBLIC);
668 
669         /** Package-private version of lookup which is trusted. */
670         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, ALL_MODES);
671 
checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes)672         private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) {
673             String name = lookupClass.getName();
674             if (name.startsWith("java.lang.invoke."))
675                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
676 
677             // For caller-sensitive MethodHandles.lookup()
678             // disallow lookup more restricted packages
679             //
680             // Android-changed: The bootstrap classloader isn't null.
681             if (allowedModes == ALL_MODES &&
682                     lookupClass.getClassLoader() == Object.class.getClassLoader()) {
683                 if (name.startsWith("java.") ||
684                         (name.startsWith("sun.")
685                                 && !name.startsWith("sun.invoke.")
686                                 && !name.equals("sun.reflect.ReflectionFactory"))) {
687                     throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
688                 }
689             }
690         }
691 
692         /**
693          * Displays the name of the class from which lookups are to be made.
694          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
695          * If there are restrictions on the access permitted to this lookup,
696          * this is indicated by adding a suffix to the class name, consisting
697          * of a slash and a keyword.  The keyword represents the strongest
698          * allowed access, and is chosen as follows:
699          * <ul>
700          * <li>If no access is allowed, the suffix is "/noaccess".
701          * <li>If only public access is allowed, the suffix is "/public".
702          * <li>If only public and package access are allowed, the suffix is "/package".
703          * <li>If only public, package, and private access are allowed, the suffix is "/private".
704          * </ul>
705          * If none of the above cases apply, it is the case that full
706          * access (public, package, private, and protected) is allowed.
707          * In this case, no suffix is added.
708          * This is true only of an object obtained originally from
709          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
710          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
711          * always have restricted access, and will display a suffix.
712          * <p>
713          * (It may seem strange that protected access should be
714          * stronger than private access.  Viewed independently from
715          * package access, protected access is the first to be lost,
716          * because it requires a direct subclass relationship between
717          * caller and callee.)
718          * @see #in
719          */
720         @Override
toString()721         public String toString() {
722             String cname = lookupClass.getName();
723             switch (allowedModes) {
724             case 0:  // no privileges
725                 return cname + "/noaccess";
726             case PUBLIC:
727                 return cname + "/public";
728             case PUBLIC|PACKAGE:
729                 return cname + "/package";
730             case ALL_MODES & ~PROTECTED:
731                 return cname + "/private";
732             case ALL_MODES:
733                 return cname;
734             // Android-changed: No support for TRUSTED callers.
735             // case TRUSTED:
736             //    return "/trusted";  // internal only; not exported
737             default:  // Should not happen, but it's a bitfield...
738                 cname = cname + "/" + Integer.toHexString(allowedModes);
739                 assert(false) : cname;
740                 return cname;
741             }
742         }
743 
744         /**
745          * Produces a method handle for a static method.
746          * The type of the method handle will be that of the method.
747          * (Since static methods do not take receivers, there is no
748          * additional receiver argument inserted into the method handle type,
749          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
750          * The method and all its argument types must be accessible to the lookup object.
751          * <p>
752          * The returned method handle will have
753          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
754          * the method's variable arity modifier bit ({@code 0x0080}) is set.
755          * <p>
756          * If the returned method handle is invoked, the method's class will
757          * be initialized, if it has not already been initialized.
758          * <p><b>Example:</b>
759          * <blockquote><pre>{@code
760 import static java.lang.invoke.MethodHandles.*;
761 import static java.lang.invoke.MethodType.*;
762 ...
763 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
764   "asList", methodType(List.class, Object[].class));
765 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
766          * }</pre></blockquote>
767          * @param refc the class from which the method is accessed
768          * @param name the name of the method
769          * @param type the type of the method
770          * @return the desired method handle
771          * @throws NoSuchMethodException if the method does not exist
772          * @throws IllegalAccessException if access checking fails,
773          *                                or if the method is not {@code static},
774          *                                or if the method's variable arity modifier bit
775          *                                is set and {@code asVarargsCollector} fails
776          * @exception SecurityException if a security manager is present and it
777          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
778          * @throws NullPointerException if any argument is null
779          */
780         public
findStatic(Class<?> refc, String name, MethodType type)781         MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
782             Method method = refc.getDeclaredMethod(name, type.ptypes());
783             final int modifiers = method.getModifiers();
784             if (!Modifier.isStatic(modifiers)) {
785                 throw new IllegalAccessException("Method" + method + " is not static");
786             }
787             checkReturnType(method, type);
788             checkAccess(refc, method.getDeclaringClass(), modifiers, method.getName());
789             return createMethodHandle(method, MethodHandle.INVOKE_STATIC, type);
790         }
791 
findVirtualForMH(String name, MethodType type)792         private MethodHandle findVirtualForMH(String name, MethodType type) {
793             // these names require special lookups because of the implicit MethodType argument
794             if ("invoke".equals(name))
795                 return invoker(type);
796             if ("invokeExact".equals(name))
797                 return exactInvoker(type);
798             return null;
799         }
800 
findVirtualForVH(String name, MethodType type)801         private MethodHandle findVirtualForVH(String name, MethodType type) {
802             VarHandle.AccessMode accessMode;
803             try {
804                 accessMode = VarHandle.AccessMode.valueFromMethodName(name);
805             } catch (IllegalArgumentException e) {
806                 return null;
807             }
808             return varHandleInvoker(accessMode, type);
809         }
810 
createMethodHandle(Method method, int handleKind, MethodType methodType)811         private static MethodHandle createMethodHandle(Method method, int handleKind,
812                                                        MethodType methodType) {
813             MethodHandle mh = new MethodHandleImpl(method.getArtMethod(), handleKind, methodType);
814             if (method.isVarArgs()) {
815                 return new Transformers.VarargsCollector(mh);
816             } else {
817                 return mh;
818             }
819         }
820 
821         /**
822          * Produces a method handle for a virtual method.
823          * The type of the method handle will be that of the method,
824          * with the receiver type (usually {@code refc}) prepended.
825          * The method and all its argument types must be accessible to the lookup object.
826          * <p>
827          * When called, the handle will treat the first argument as a receiver
828          * and dispatch on the receiver's type to determine which method
829          * implementation to enter.
830          * (The dispatching action is identical with that performed by an
831          * {@code invokevirtual} or {@code invokeinterface} instruction.)
832          * <p>
833          * The first argument will be of type {@code refc} if the lookup
834          * class has full privileges to access the member.  Otherwise
835          * the member must be {@code protected} and the first argument
836          * will be restricted in type to the lookup class.
837          * <p>
838          * The returned method handle will have
839          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
840          * the method's variable arity modifier bit ({@code 0x0080}) is set.
841          * <p>
842          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
843          * instructions and method handles produced by {@code findVirtual},
844          * if the class is {@code MethodHandle} and the name string is
845          * {@code invokeExact} or {@code invoke}, the resulting
846          * method handle is equivalent to one produced by
847          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
848          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
849          * with the same {@code type} argument.
850          *
851          * <b>Example:</b>
852          * <blockquote><pre>{@code
853 import static java.lang.invoke.MethodHandles.*;
854 import static java.lang.invoke.MethodType.*;
855 ...
856 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
857   "concat", methodType(String.class, String.class));
858 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
859   "hashCode", methodType(int.class));
860 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
861   "hashCode", methodType(int.class));
862 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
863 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
864 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
865 // interface method:
866 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
867   "subSequence", methodType(CharSequence.class, int.class, int.class));
868 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
869 // constructor "internal method" must be accessed differently:
870 MethodType MT_newString = methodType(void.class); //()V for new String()
871 try { assertEquals("impossible", lookup()
872         .findVirtual(String.class, "<init>", MT_newString));
873  } catch (NoSuchMethodException ex) { } // OK
874 MethodHandle MH_newString = publicLookup()
875   .findConstructor(String.class, MT_newString);
876 assertEquals("", (String) MH_newString.invokeExact());
877          * }</pre></blockquote>
878          *
879          * @param refc the class or interface from which the method is accessed
880          * @param name the name of the method
881          * @param type the type of the method, with the receiver argument omitted
882          * @return the desired method handle
883          * @throws NoSuchMethodException if the method does not exist
884          * @throws IllegalAccessException if access checking fails,
885          *                                or if the method is {@code static}
886          *                                or if the method's variable arity modifier bit
887          *                                is set and {@code asVarargsCollector} fails
888          * @exception SecurityException if a security manager is present and it
889          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
890          * @throws NullPointerException if any argument is null
891          */
findVirtual(Class<?> refc, String name, MethodType type)892         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
893             // Special case : when we're looking up a virtual method on the MethodHandles class
894             // itself, we can return one of our specialized invokers.
895             if (refc == MethodHandle.class) {
896                 MethodHandle mh = findVirtualForMH(name, type);
897                 if (mh != null) {
898                     return mh;
899                 }
900             } else if (refc == VarHandle.class) {
901                 // Returns an non-exact invoker.
902                 MethodHandle mh = findVirtualForVH(name, type);
903                 if (mh != null) {
904                     return mh;
905                 }
906             }
907 
908             Method method = refc.getInstanceMethod(name, type.ptypes());
909             if (method == null) {
910                 // This is pretty ugly and a consequence of the MethodHandles API. We have to throw
911                 // an IAE and not an NSME if the method exists but is static (even though the RI's
912                 // IAE has a message that says "no such method"). We confine the ugliness and
913                 // slowness to the failure case, and allow getInstanceMethod to remain fairly
914                 // general.
915                 try {
916                     Method m = refc.getDeclaredMethod(name, type.ptypes());
917                     if (Modifier.isStatic(m.getModifiers())) {
918                         throw new IllegalAccessException("Method" + m + " is static");
919                     }
920                 } catch (NoSuchMethodException ignored) {
921                 }
922 
923                 throw new NoSuchMethodException(name + " "  + Arrays.toString(type.ptypes()));
924             }
925             checkReturnType(method, type);
926 
927             // We have a valid method, perform access checks.
928             checkAccess(refc, method.getDeclaringClass(), method.getModifiers(), method.getName());
929 
930             // Insert the leading reference parameter.
931             MethodType handleType = type.insertParameterTypes(0, refc);
932             return createMethodHandle(method, MethodHandle.INVOKE_VIRTUAL, handleType);
933         }
934 
935         /**
936          * Produces a method handle which creates an object and initializes it, using
937          * the constructor of the specified type.
938          * The parameter types of the method handle will be those of the constructor,
939          * while the return type will be a reference to the constructor's class.
940          * The constructor and all its argument types must be accessible to the lookup object.
941          * <p>
942          * The requested type must have a return type of {@code void}.
943          * (This is consistent with the JVM's treatment of constructor type descriptors.)
944          * <p>
945          * The returned method handle will have
946          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
947          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
948          * <p>
949          * If the returned method handle is invoked, the constructor's class will
950          * be initialized, if it has not already been initialized.
951          * <p><b>Example:</b>
952          * <blockquote><pre>{@code
953 import static java.lang.invoke.MethodHandles.*;
954 import static java.lang.invoke.MethodType.*;
955 ...
956 MethodHandle MH_newArrayList = publicLookup().findConstructor(
957   ArrayList.class, methodType(void.class, Collection.class));
958 Collection orig = Arrays.asList("x", "y");
959 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
960 assert(orig != copy);
961 assertEquals(orig, copy);
962 // a variable-arity constructor:
963 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
964   ProcessBuilder.class, methodType(void.class, String[].class));
965 ProcessBuilder pb = (ProcessBuilder)
966   MH_newProcessBuilder.invoke("x", "y", "z");
967 assertEquals("[x, y, z]", pb.command().toString());
968          * }</pre></blockquote>
969          * @param refc the class or interface from which the method is accessed
970          * @param type the type of the method, with the receiver argument omitted, and a void return type
971          * @return the desired method handle
972          * @throws NoSuchMethodException if the constructor does not exist
973          * @throws IllegalAccessException if access checking fails
974          *                                or if the method's variable arity modifier bit
975          *                                is set and {@code asVarargsCollector} fails
976          * @exception SecurityException if a security manager is present and it
977          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
978          * @throws NullPointerException if any argument is null
979          */
findConstructor(Class<?> refc, MethodType type)980         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
981             if (refc.isArray()) {
982                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
983             }
984             // The queried |type| is (PT1,PT2,..)V
985             Constructor constructor = refc.getDeclaredConstructor(type.ptypes());
986             if (constructor == null) {
987                 throw new NoSuchMethodException(
988                     "No constructor for " + constructor.getDeclaringClass() + " matching " + type);
989             }
990             checkAccess(refc, constructor.getDeclaringClass(), constructor.getModifiers(),
991                     constructor.getName());
992 
993             return createMethodHandleForConstructor(constructor);
994         }
995 
createMethodHandleForConstructor(Constructor constructor)996         private MethodHandle createMethodHandleForConstructor(Constructor constructor) {
997             Class<?> refc = constructor.getDeclaringClass();
998             MethodType constructorType =
999                     MethodType.methodType(refc, constructor.getParameterTypes());
1000             MethodHandle mh;
1001             if (refc == String.class) {
1002                 // String constructors have optimized StringFactory methods
1003                 // that matches returned type. These factory methods combine the
1004                 // memory allocation and initialization calls for String objects.
1005                 mh = new MethodHandleImpl(constructor.getArtMethod(), MethodHandle.INVOKE_DIRECT,
1006                                           constructorType);
1007             } else {
1008                 // Constructors for all other classes use a Construct transformer to perform
1009                 // their memory allocation and call to <init>.
1010                 MethodType initType = initMethodType(constructorType);
1011                 MethodHandle initHandle = new MethodHandleImpl(
1012                     constructor.getArtMethod(), MethodHandle.INVOKE_DIRECT, initType);
1013                 mh = new Transformers.Construct(initHandle, constructorType);
1014             }
1015 
1016             if (constructor.isVarArgs()) {
1017                 mh = new Transformers.VarargsCollector(mh);
1018             }
1019             return mh;
1020         }
1021 
initMethodType(MethodType constructorType)1022         private static MethodType initMethodType(MethodType constructorType) {
1023             // Returns a MethodType appropriate for class <init>
1024             // methods. Constructor MethodTypes have the form
1025             // (PT1,PT2,...)C and class <init> MethodTypes have the
1026             // form (C,PT1,PT2,...)V.
1027             assert constructorType.rtype() != void.class;
1028 
1029             // Insert constructorType C as the first parameter type in
1030             // the MethodType for <init>.
1031             Class<?> [] initPtypes = new Class<?> [constructorType.ptypes().length + 1];
1032             initPtypes[0] = constructorType.rtype();
1033             System.arraycopy(constructorType.ptypes(), 0, initPtypes, 1,
1034                              constructorType.ptypes().length);
1035 
1036             // Set the return type for the <init> MethodType to be void.
1037             return MethodType.methodType(void.class, initPtypes);
1038         }
1039 
1040         /**
1041          * Produces an early-bound method handle for a virtual method.
1042          * It will bypass checks for overriding methods on the receiver,
1043          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1044          * instruction from within the explicitly specified {@code specialCaller}.
1045          * The type of the method handle will be that of the method,
1046          * with a suitably restricted receiver type prepended.
1047          * (The receiver type will be {@code specialCaller} or a subtype.)
1048          * The method and all its argument types must be accessible
1049          * to the lookup object.
1050          * <p>
1051          * Before method resolution,
1052          * if the explicitly specified caller class is not identical with the
1053          * lookup class, or if this lookup object does not have
1054          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1055          * privileges, the access fails.
1056          * <p>
1057          * The returned method handle will have
1058          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1059          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1060          * <p style="font-size:smaller;">
1061          * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
1062          * even though the {@code invokespecial} instruction can refer to them
1063          * in special circumstances.  Use {@link #findConstructor findConstructor}
1064          * to access instance initialization methods in a safe manner.)</em>
1065          * <p><b>Example:</b>
1066          * <blockquote><pre>{@code
1067 import static java.lang.invoke.MethodHandles.*;
1068 import static java.lang.invoke.MethodType.*;
1069 ...
1070 static class Listie extends ArrayList {
1071   public String toString() { return "[wee Listie]"; }
1072   static Lookup lookup() { return MethodHandles.lookup(); }
1073 }
1074 ...
1075 // no access to constructor via invokeSpecial:
1076 MethodHandle MH_newListie = Listie.lookup()
1077   .findConstructor(Listie.class, methodType(void.class));
1078 Listie l = (Listie) MH_newListie.invokeExact();
1079 try { assertEquals("impossible", Listie.lookup().findSpecial(
1080         Listie.class, "<init>", methodType(void.class), Listie.class));
1081  } catch (NoSuchMethodException ex) { } // OK
1082 // access to super and self methods via invokeSpecial:
1083 MethodHandle MH_super = Listie.lookup().findSpecial(
1084   ArrayList.class, "toString" , methodType(String.class), Listie.class);
1085 MethodHandle MH_this = Listie.lookup().findSpecial(
1086   Listie.class, "toString" , methodType(String.class), Listie.class);
1087 MethodHandle MH_duper = Listie.lookup().findSpecial(
1088   Object.class, "toString" , methodType(String.class), Listie.class);
1089 assertEquals("[]", (String) MH_super.invokeExact(l));
1090 assertEquals(""+l, (String) MH_this.invokeExact(l));
1091 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
1092 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
1093         String.class, "toString", methodType(String.class), Listie.class));
1094  } catch (IllegalAccessException ex) { } // OK
1095 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
1096 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
1097          * }</pre></blockquote>
1098          *
1099          * @param refc the class or interface from which the method is accessed
1100          * @param name the name of the method (which must not be "&lt;init&gt;")
1101          * @param type the type of the method, with the receiver argument omitted
1102          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
1103          * @return the desired method handle
1104          * @throws NoSuchMethodException if the method does not exist
1105          * @throws IllegalAccessException if access checking fails
1106          *                                or if the method's variable arity modifier bit
1107          *                                is set and {@code asVarargsCollector} fails
1108          * @exception SecurityException if a security manager is present and it
1109          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1110          * @throws NullPointerException if any argument is null
1111          */
findSpecial(Class<?> refc, String name, MethodType type, Class<?> specialCaller)1112         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
1113                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
1114             if (specialCaller == null) {
1115                 throw new NullPointerException("specialCaller == null");
1116             }
1117 
1118             if (type == null) {
1119                 throw new NullPointerException("type == null");
1120             }
1121 
1122             if (name == null) {
1123                 throw new NullPointerException("name == null");
1124             }
1125 
1126             if (refc == null) {
1127                 throw new NullPointerException("ref == null");
1128             }
1129 
1130             // Make sure that the special caller is identical to the lookup class or that we have
1131             // private access.
1132             checkSpecialCaller(specialCaller);
1133 
1134             // Even though constructors are invoked using a "special" invoke, handles to them can't
1135             // be created using findSpecial. Callers must use findConstructor instead. Similarly,
1136             // there is no path for calling static class initializers.
1137             if (name.startsWith("<")) {
1138                 throw new NoSuchMethodException(name + " is not a valid method name.");
1139             }
1140 
1141             Method method = refc.getDeclaredMethod(name, type.ptypes());
1142             checkReturnType(method, type);
1143             return findSpecial(method, type, refc, specialCaller);
1144         }
1145 
findSpecial(Method method, MethodType type, Class<?> refc, Class<?> specialCaller)1146         private MethodHandle findSpecial(Method method, MethodType type,
1147                                          Class<?> refc, Class<?> specialCaller)
1148                 throws IllegalAccessException {
1149             if (Modifier.isStatic(method.getModifiers())) {
1150                 throw new IllegalAccessException("expected a non-static method:" + method);
1151             }
1152 
1153             if (Modifier.isPrivate(method.getModifiers())) {
1154                 // Since this is a private method, we'll need to also make sure that the
1155                 // lookup class is the same as the refering class. We've already checked that
1156                 // the specialCaller is the same as the special lookup class, both of these must
1157                 // be the same as the declaring class(*) in order to access the private method.
1158                 //
1159                 // (*) Well, this isn't true for nested classes but OpenJDK doesn't support those
1160                 // either.
1161                 if (refc != lookupClass()) {
1162                     throw new IllegalAccessException("no private access for invokespecial : "
1163                             + refc + ", from" + this);
1164                 }
1165 
1166                 // This is a private method, so there's nothing special to do.
1167                 MethodType handleType = type.insertParameterTypes(0, refc);
1168                 return createMethodHandle(method, MethodHandle.INVOKE_DIRECT, handleType);
1169             }
1170 
1171             // This is a public, protected or package-private method, which means we're expecting
1172             // invoke-super semantics. We'll have to restrict the receiver type appropriately on the
1173             // handle once we check that there really is a "super" relationship between them.
1174             if (!method.getDeclaringClass().isAssignableFrom(specialCaller)) {
1175                 throw new IllegalAccessException(refc + "is not assignable from " + specialCaller);
1176             }
1177 
1178             // Note that we restrict the receiver to "specialCaller" instances.
1179             MethodType handleType = type.insertParameterTypes(0, specialCaller);
1180             return createMethodHandle(method, MethodHandle.INVOKE_SUPER, handleType);
1181         }
1182 
1183         /**
1184          * Produces a method handle giving read access to a non-static field.
1185          * The type of the method handle will have a return type of the field's
1186          * value type.
1187          * The method handle's single argument will be the instance containing
1188          * the field.
1189          * Access checking is performed immediately on behalf of the lookup class.
1190          * @param refc the class or interface from which the method is accessed
1191          * @param name the field's name
1192          * @param type the field's type
1193          * @return a method handle which can load values from the field
1194          * @throws NoSuchFieldException if the field does not exist
1195          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1196          * @exception SecurityException if a security manager is present and it
1197          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1198          * @throws NullPointerException if any argument is null
1199          */
findGetter(Class<?> refc, String name, Class<?> type)1200         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1201             return findAccessor(refc, name, type, MethodHandle.IGET);
1202         }
1203 
findAccessor(Class<?> refc, String name, Class<?> type, int kind)1204         private MethodHandle findAccessor(Class<?> refc, String name, Class<?> type, int kind)
1205             throws NoSuchFieldException, IllegalAccessException {
1206             final Field field = findFieldOfType(refc, name, type);
1207             return findAccessor(field, refc, type, kind, true /* performAccessChecks */);
1208         }
1209 
findAccessor(Field field, Class<?> refc, Class<?> type, int kind, boolean performAccessChecks)1210         private MethodHandle findAccessor(Field field, Class<?> refc, Class<?> type, int kind,
1211                                           boolean performAccessChecks)
1212                 throws IllegalAccessException {
1213             final boolean isSetterKind = kind == MethodHandle.IPUT || kind == MethodHandle.SPUT;
1214             final boolean isStaticKind = kind == MethodHandle.SGET || kind == MethodHandle.SPUT;
1215             commonFieldChecks(field, refc, type, isStaticKind, performAccessChecks);
1216             if (performAccessChecks) {
1217                 final int modifiers = field.getModifiers();
1218                 if (isSetterKind && Modifier.isFinal(modifiers)) {
1219                     throw new IllegalAccessException("Field " + field + " is final");
1220                 }
1221             }
1222 
1223             final MethodType methodType;
1224             switch (kind) {
1225                 case MethodHandle.SGET:
1226                     methodType = MethodType.methodType(type);
1227                     break;
1228                 case MethodHandle.SPUT:
1229                     methodType = MethodType.methodType(void.class, type);
1230                     break;
1231                 case MethodHandle.IGET:
1232                     methodType = MethodType.methodType(type, refc);
1233                     break;
1234                 case MethodHandle.IPUT:
1235                     methodType = MethodType.methodType(void.class, refc, type);
1236                     break;
1237                 default:
1238                     throw new IllegalArgumentException("Invalid kind " + kind);
1239             }
1240             return new MethodHandleImpl(field.getArtField(), kind, methodType);
1241         }
1242 
1243         /**
1244          * Produces a method handle giving write access to a non-static field.
1245          * The type of the method handle will have a void return type.
1246          * The method handle will take two arguments, the instance containing
1247          * the field, and the value to be stored.
1248          * The second argument will be of the field's value type.
1249          * Access checking is performed immediately on behalf of the lookup class.
1250          * @param refc the class or interface from which the method is accessed
1251          * @param name the field's name
1252          * @param type the field's type
1253          * @return a method handle which can store values into the field
1254          * @throws NoSuchFieldException if the field does not exist
1255          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1256          * @exception SecurityException if a security manager is present and it
1257          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1258          * @throws NullPointerException if any argument is null
1259          */
findSetter(Class<?> refc, String name, Class<?> type)1260         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1261             return findAccessor(refc, name, type, MethodHandle.IPUT);
1262         }
1263 
1264         // BEGIN Android-changed: OpenJDK 9+181 VarHandle API factory method.
1265         /**
1266          * Produces a VarHandle giving access to a non-static field {@code name}
1267          * of type {@code type} declared in a class of type {@code recv}.
1268          * The VarHandle's variable type is {@code type} and it has one
1269          * coordinate type, {@code recv}.
1270          * <p>
1271          * Access checking is performed immediately on behalf of the lookup
1272          * class.
1273          * <p>
1274          * Certain access modes of the returned VarHandle are unsupported under
1275          * the following conditions:
1276          * <ul>
1277          * <li>if the field is declared {@code final}, then the write, atomic
1278          *     update, numeric atomic update, and bitwise atomic update access
1279          *     modes are unsupported.
1280          * <li>if the field type is anything other than {@code byte},
1281          *     {@code short}, {@code char}, {@code int}, {@code long},
1282          *     {@code float}, or {@code double} then numeric atomic update
1283          *     access modes are unsupported.
1284          * <li>if the field type is anything other than {@code boolean},
1285          *     {@code byte}, {@code short}, {@code char}, {@code int} or
1286          *     {@code long} then bitwise atomic update access modes are
1287          *     unsupported.
1288          * </ul>
1289          * <p>
1290          * If the field is declared {@code volatile} then the returned VarHandle
1291          * will override access to the field (effectively ignore the
1292          * {@code volatile} declaration) in accordance to its specified
1293          * access modes.
1294          * <p>
1295          * If the field type is {@code float} or {@code double} then numeric
1296          * and atomic update access modes compare values using their bitwise
1297          * representation (see {@link Float#floatToRawIntBits} and
1298          * {@link Double#doubleToRawLongBits}, respectively).
1299          * @apiNote
1300          * Bitwise comparison of {@code float} values or {@code double} values,
1301          * as performed by the numeric and atomic update access modes, differ
1302          * from the primitive {@code ==} operator and the {@link Float#equals}
1303          * and {@link Double#equals} methods, specifically with respect to
1304          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
1305          * Care should be taken when performing a compare and set or a compare
1306          * and exchange operation with such values since the operation may
1307          * unexpectedly fail.
1308          * There are many possible NaN values that are considered to be
1309          * {@code NaN} in Java, although no IEEE 754 floating-point operation
1310          * provided by Java can distinguish between them.  Operation failure can
1311          * occur if the expected or witness value is a NaN value and it is
1312          * transformed (perhaps in a platform specific manner) into another NaN
1313          * value, and thus has a different bitwise representation (see
1314          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
1315          * details).
1316          * The values {@code -0.0} and {@code +0.0} have different bitwise
1317          * representations but are considered equal when using the primitive
1318          * {@code ==} operator.  Operation failure can occur if, for example, a
1319          * numeric algorithm computes an expected value to be say {@code -0.0}
1320          * and previously computed the witness value to be say {@code +0.0}.
1321          * @param recv the receiver class, of type {@code R}, that declares the
1322          * non-static field
1323          * @param name the field's name
1324          * @param type the field's type, of type {@code T}
1325          * @return a VarHandle giving access to non-static fields.
1326          * @throws NoSuchFieldException if the field does not exist
1327          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1328          * @exception SecurityException if a security manager is present and it
1329          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1330          * @throws NullPointerException if any argument is null
1331          * @since 9
1332          * @hide
1333          */
findVarHandle(Class<?> recv, String name, Class<?> type)1334         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1335             final Field field = findFieldOfType(recv, name, type);
1336             final boolean isStatic = false;
1337             final boolean performAccessChecks = true;
1338             commonFieldChecks(field, recv, type, isStatic, performAccessChecks);
1339             return FieldVarHandle.create(field);
1340         }
1341         // END Android-changed: OpenJDK 9+181 VarHandle API factory method.
1342 
1343         // BEGIN Android-added: Common field resolution and access check methods.
findFieldOfType(final Class<?> refc, String name, Class<?> type)1344         private Field findFieldOfType(final Class<?> refc, String name, Class<?> type)
1345                 throws NoSuchFieldException {
1346             Field field = null;
1347 
1348             // Search refc and super classes for the field.
1349             for (Class<?> cls = refc; cls != null; cls = cls.getSuperclass()) {
1350                 try {
1351                     field = cls.getDeclaredField(name);
1352                     break;
1353                 } catch (NoSuchFieldException e) {
1354                 }
1355             }
1356 
1357             if (field == null) {
1358                 // Force failure citing refc.
1359                 field = refc.getDeclaredField(name);
1360             }
1361 
1362             final Class<?> fieldType = field.getType();
1363             if (fieldType != type) {
1364                 throw new NoSuchFieldException(name);
1365             }
1366             return field;
1367         }
1368 
commonFieldChecks(Field field, Class<?> refc, Class<?> type, boolean isStatic, boolean performAccessChecks)1369         private void commonFieldChecks(Field field, Class<?> refc, Class<?> type,
1370                                        boolean isStatic, boolean performAccessChecks)
1371                 throws IllegalAccessException {
1372             final int modifiers = field.getModifiers();
1373             if (performAccessChecks) {
1374                 checkAccess(refc, field.getDeclaringClass(), modifiers, field.getName());
1375             }
1376             if (Modifier.isStatic(modifiers) != isStatic) {
1377                 String reason = "Field " + field + " is " +
1378                         (isStatic ? "not " : "") + "static";
1379                 throw new IllegalAccessException(reason);
1380             }
1381         }
1382         // END Android-added: Common field resolution and access check methods.
1383 
1384         /**
1385          * Produces a method handle giving read access to a static field.
1386          * The type of the method handle will have a return type of the field's
1387          * value type.
1388          * The method handle will take no arguments.
1389          * Access checking is performed immediately on behalf of the lookup class.
1390          * <p>
1391          * If the returned method handle is invoked, the field's class will
1392          * be initialized, if it has not already been initialized.
1393          * @param refc the class or interface from which the method is accessed
1394          * @param name the field's name
1395          * @param type the field's type
1396          * @return a method handle which can load values from the field
1397          * @throws NoSuchFieldException if the field does not exist
1398          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1399          * @exception SecurityException if a security manager is present and it
1400          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1401          * @throws NullPointerException if any argument is null
1402          */
findStaticGetter(Class<?> refc, String name, Class<?> type)1403         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1404             return findAccessor(refc, name, type, MethodHandle.SGET);
1405         }
1406 
1407         /**
1408          * Produces a method handle giving write access to a static field.
1409          * The type of the method handle will have a void return type.
1410          * The method handle will take a single
1411          * argument, of the field's value type, the value to be stored.
1412          * Access checking is performed immediately on behalf of the lookup class.
1413          * <p>
1414          * If the returned method handle is invoked, the field's class will
1415          * be initialized, if it has not already been initialized.
1416          * @param refc the class or interface from which the method is accessed
1417          * @param name the field's name
1418          * @param type the field's type
1419          * @return a method handle which can store values into the field
1420          * @throws NoSuchFieldException if the field does not exist
1421          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1422          * @exception SecurityException if a security manager is present and it
1423          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1424          * @throws NullPointerException if any argument is null
1425          */
findStaticSetter(Class<?> refc, String name, Class<?> type)1426         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1427             return findAccessor(refc, name, type, MethodHandle.SPUT);
1428         }
1429 
1430         // BEGIN Android-changed: OpenJDK 9+181 VarHandle API factory method.
1431         /**
1432          * Produces a VarHandle giving access to a static field {@code name} of
1433          * type {@code type} declared in a class of type {@code decl}.
1434          * The VarHandle's variable type is {@code type} and it has no
1435          * coordinate types.
1436          * <p>
1437          * Access checking is performed immediately on behalf of the lookup
1438          * class.
1439          * <p>
1440          * If the returned VarHandle is operated on, the declaring class will be
1441          * initialized, if it has not already been initialized.
1442          * <p>
1443          * Certain access modes of the returned VarHandle are unsupported under
1444          * the following conditions:
1445          * <ul>
1446          * <li>if the field is declared {@code final}, then the write, atomic
1447          *     update, numeric atomic update, and bitwise atomic update access
1448          *     modes are unsupported.
1449          * <li>if the field type is anything other than {@code byte},
1450          *     {@code short}, {@code char}, {@code int}, {@code long},
1451          *     {@code float}, or {@code double}, then numeric atomic update
1452          *     access modes are unsupported.
1453          * <li>if the field type is anything other than {@code boolean},
1454          *     {@code byte}, {@code short}, {@code char}, {@code int} or
1455          *     {@code long} then bitwise atomic update access modes are
1456          *     unsupported.
1457          * </ul>
1458          * <p>
1459          * If the field is declared {@code volatile} then the returned VarHandle
1460          * will override access to the field (effectively ignore the
1461          * {@code volatile} declaration) in accordance to its specified
1462          * access modes.
1463          * <p>
1464          * If the field type is {@code float} or {@code double} then numeric
1465          * and atomic update access modes compare values using their bitwise
1466          * representation (see {@link Float#floatToRawIntBits} and
1467          * {@link Double#doubleToRawLongBits}, respectively).
1468          * @apiNote
1469          * Bitwise comparison of {@code float} values or {@code double} values,
1470          * as performed by the numeric and atomic update access modes, differ
1471          * from the primitive {@code ==} operator and the {@link Float#equals}
1472          * and {@link Double#equals} methods, specifically with respect to
1473          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
1474          * Care should be taken when performing a compare and set or a compare
1475          * and exchange operation with such values since the operation may
1476          * unexpectedly fail.
1477          * There are many possible NaN values that are considered to be
1478          * {@code NaN} in Java, although no IEEE 754 floating-point operation
1479          * provided by Java can distinguish between them.  Operation failure can
1480          * occur if the expected or witness value is a NaN value and it is
1481          * transformed (perhaps in a platform specific manner) into another NaN
1482          * value, and thus has a different bitwise representation (see
1483          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
1484          * details).
1485          * The values {@code -0.0} and {@code +0.0} have different bitwise
1486          * representations but are considered equal when using the primitive
1487          * {@code ==} operator.  Operation failure can occur if, for example, a
1488          * numeric algorithm computes an expected value to be say {@code -0.0}
1489          * and previously computed the witness value to be say {@code +0.0}.
1490          * @param decl the class that declares the static field
1491          * @param name the field's name
1492          * @param type the field's type, of type {@code T}
1493          * @return a VarHandle giving access to a static field
1494          * @throws NoSuchFieldException if the field does not exist
1495          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1496          * @exception SecurityException if a security manager is present and it
1497          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1498          * @throws NullPointerException if any argument is null
1499          * @since 9
1500          * @hide
1501          */
findStaticVarHandle(Class<?> decl, String name, Class<?> type)1502         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1503             final Field field = findFieldOfType(decl, name, type);
1504             final boolean isStatic = true;
1505             final boolean performAccessChecks = true;
1506             commonFieldChecks(field, decl, type, isStatic, performAccessChecks);
1507             return FieldVarHandle.create(field);
1508         }
1509         // END Android-changed: OpenJDK 9+181 VarHandle API factory method.
1510 
1511         /**
1512          * Produces an early-bound method handle for a non-static method.
1513          * The receiver must have a supertype {@code defc} in which a method
1514          * of the given name and type is accessible to the lookup class.
1515          * The method and all its argument types must be accessible to the lookup object.
1516          * The type of the method handle will be that of the method,
1517          * without any insertion of an additional receiver parameter.
1518          * The given receiver will be bound into the method handle,
1519          * so that every call to the method handle will invoke the
1520          * requested method on the given receiver.
1521          * <p>
1522          * The returned method handle will have
1523          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1524          * the method's variable arity modifier bit ({@code 0x0080}) is set
1525          * <em>and</em> the trailing array argument is not the only argument.
1526          * (If the trailing array argument is the only argument,
1527          * the given receiver value will be bound to it.)
1528          * <p>
1529          * This is equivalent to the following code:
1530          * <blockquote><pre>{@code
1531 import static java.lang.invoke.MethodHandles.*;
1532 import static java.lang.invoke.MethodType.*;
1533 ...
1534 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
1535 MethodHandle mh1 = mh0.bindTo(receiver);
1536 MethodType mt1 = mh1.type();
1537 if (mh0.isVarargsCollector())
1538   mh1 = mh1.asVarargsCollector(mt1.parameterType(mt1.parameterCount()-1));
1539 return mh1;
1540          * }</pre></blockquote>
1541          * where {@code defc} is either {@code receiver.getClass()} or a super
1542          * type of that class, in which the requested method is accessible
1543          * to the lookup class.
1544          * (Note that {@code bindTo} does not preserve variable arity.)
1545          * @param receiver the object from which the method is accessed
1546          * @param name the name of the method
1547          * @param type the type of the method, with the receiver argument omitted
1548          * @return the desired method handle
1549          * @throws NoSuchMethodException if the method does not exist
1550          * @throws IllegalAccessException if access checking fails
1551          *                                or if the method's variable arity modifier bit
1552          *                                is set and {@code asVarargsCollector} fails
1553          * @exception SecurityException if a security manager is present and it
1554          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1555          * @throws NullPointerException if any argument is null
1556          * @see MethodHandle#bindTo
1557          * @see #findVirtual
1558          */
bind(Object receiver, String name, MethodType type)1559         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1560             MethodHandle handle = findVirtual(receiver.getClass(), name, type);
1561             MethodHandle adapter = handle.bindTo(receiver);
1562             MethodType adapterType = adapter.type();
1563             if (handle.isVarargsCollector()) {
1564                 adapter = adapter.asVarargsCollector(
1565                         adapterType.parameterType(adapterType.parameterCount() - 1));
1566             }
1567 
1568             return adapter;
1569         }
1570 
1571         /**
1572          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1573          * to <i>m</i>, if the lookup class has permission.
1574          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
1575          * If <i>m</i> is virtual, overriding is respected on every call.
1576          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
1577          * The type of the method handle will be that of the method,
1578          * with the receiver type prepended (but only if it is non-static).
1579          * If the method's {@code accessible} flag is not set,
1580          * access checking is performed immediately on behalf of the lookup class.
1581          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
1582          * <p>
1583          * The returned method handle will have
1584          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1585          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1586          * <p>
1587          * If <i>m</i> is static, and
1588          * if the returned method handle is invoked, the method's class will
1589          * be initialized, if it has not already been initialized.
1590          * @param m the reflected method
1591          * @return a method handle which can invoke the reflected method
1592          * @throws IllegalAccessException if access checking fails
1593          *                                or if the method's variable arity modifier bit
1594          *                                is set and {@code asVarargsCollector} fails
1595          * @throws NullPointerException if the argument is null
1596          */
unreflect(Method m)1597         public MethodHandle unreflect(Method m) throws IllegalAccessException {
1598             if (m == null) {
1599                 throw new NullPointerException("m == null");
1600             }
1601 
1602             MethodType methodType = MethodType.methodType(m.getReturnType(),
1603                     m.getParameterTypes());
1604 
1605             // We should only perform access checks if setAccessible hasn't been called yet.
1606             if (!m.isAccessible()) {
1607                 checkAccess(m.getDeclaringClass(), m.getDeclaringClass(), m.getModifiers(),
1608                         m.getName());
1609             }
1610 
1611             if (Modifier.isStatic(m.getModifiers())) {
1612                 return createMethodHandle(m, MethodHandle.INVOKE_STATIC, methodType);
1613             } else {
1614                 methodType = methodType.insertParameterTypes(0, m.getDeclaringClass());
1615                 return createMethodHandle(m, MethodHandle.INVOKE_VIRTUAL, methodType);
1616             }
1617         }
1618 
1619         /**
1620          * Produces a method handle for a reflected method.
1621          * It will bypass checks for overriding methods on the receiver,
1622          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1623          * instruction from within the explicitly specified {@code specialCaller}.
1624          * The type of the method handle will be that of the method,
1625          * with a suitably restricted receiver type prepended.
1626          * (The receiver type will be {@code specialCaller} or a subtype.)
1627          * If the method's {@code accessible} flag is not set,
1628          * access checking is performed immediately on behalf of the lookup class,
1629          * as if {@code invokespecial} instruction were being linked.
1630          * <p>
1631          * Before method resolution,
1632          * if the explicitly specified caller class is not identical with the
1633          * lookup class, or if this lookup object does not have
1634          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1635          * privileges, the access fails.
1636          * <p>
1637          * The returned method handle will have
1638          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1639          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1640          * @param m the reflected method
1641          * @param specialCaller the class nominally calling the method
1642          * @return a method handle which can invoke the reflected method
1643          * @throws IllegalAccessException if access checking fails
1644          *                                or if the method's variable arity modifier bit
1645          *                                is set and {@code asVarargsCollector} fails
1646          * @throws NullPointerException if any argument is null
1647          */
unreflectSpecial(Method m, Class<?> specialCaller)1648         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
1649             if (m == null) {
1650                 throw new NullPointerException("m == null");
1651             }
1652 
1653             if (specialCaller == null) {
1654                 throw new NullPointerException("specialCaller == null");
1655             }
1656 
1657             if (!m.isAccessible()) {
1658                 checkSpecialCaller(specialCaller);
1659             }
1660 
1661             final MethodType methodType = MethodType.methodType(m.getReturnType(),
1662                     m.getParameterTypes());
1663             return findSpecial(m, methodType, m.getDeclaringClass() /* refc */, specialCaller);
1664         }
1665 
1666         /**
1667          * Produces a method handle for a reflected constructor.
1668          * The type of the method handle will be that of the constructor,
1669          * with the return type changed to the declaring class.
1670          * The method handle will perform a {@code newInstance} operation,
1671          * creating a new instance of the constructor's class on the
1672          * arguments passed to the method handle.
1673          * <p>
1674          * If the constructor's {@code accessible} flag is not set,
1675          * access checking is performed immediately on behalf of the lookup class.
1676          * <p>
1677          * The returned method handle will have
1678          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1679          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
1680          * <p>
1681          * If the returned method handle is invoked, the constructor's class will
1682          * be initialized, if it has not already been initialized.
1683          * @param c the reflected constructor
1684          * @return a method handle which can invoke the reflected constructor
1685          * @throws IllegalAccessException if access checking fails
1686          *                                or if the method's variable arity modifier bit
1687          *                                is set and {@code asVarargsCollector} fails
1688          * @throws NullPointerException if the argument is null
1689          */
unreflectConstructor(Constructor<?> c)1690         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
1691             if (c == null) {
1692                 throw new NullPointerException("c == null");
1693             }
1694 
1695             if (!c.isAccessible()) {
1696                 checkAccess(c.getDeclaringClass(), c.getDeclaringClass(), c.getModifiers(),
1697                         c.getName());
1698             }
1699 
1700             return createMethodHandleForConstructor(c);
1701         }
1702 
1703         /**
1704          * Produces a method handle giving read access to a reflected field.
1705          * The type of the method handle will have a return type of the field's
1706          * value type.
1707          * If the field is static, the method handle will take no arguments.
1708          * Otherwise, its single argument will be the instance containing
1709          * the field.
1710          * If the field's {@code accessible} flag is not set,
1711          * access checking is performed immediately on behalf of the lookup class.
1712          * <p>
1713          * If the field is static, and
1714          * if the returned method handle is invoked, the field's class will
1715          * be initialized, if it has not already been initialized.
1716          * @param f the reflected field
1717          * @return a method handle which can load values from the reflected field
1718          * @throws IllegalAccessException if access checking fails
1719          * @throws NullPointerException if the argument is null
1720          */
unreflectGetter(Field f)1721         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
1722             return findAccessor(f, f.getDeclaringClass(), f.getType(),
1723                     Modifier.isStatic(f.getModifiers()) ? MethodHandle.SGET : MethodHandle.IGET,
1724                     !f.isAccessible() /* performAccessChecks */);
1725         }
1726 
1727         /**
1728          * Produces a method handle giving write access to a reflected field.
1729          * The type of the method handle will have a void return type.
1730          * If the field is static, the method handle will take a single
1731          * argument, of the field's value type, the value to be stored.
1732          * Otherwise, the two arguments will be the instance containing
1733          * the field, and the value to be stored.
1734          * If the field's {@code accessible} flag is not set,
1735          * access checking is performed immediately on behalf of the lookup class.
1736          * <p>
1737          * If the field is static, and
1738          * if the returned method handle is invoked, the field's class will
1739          * be initialized, if it has not already been initialized.
1740          * @param f the reflected field
1741          * @return a method handle which can store values into the reflected field
1742          * @throws IllegalAccessException if access checking fails
1743          * @throws NullPointerException if the argument is null
1744          */
unreflectSetter(Field f)1745         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
1746             return findAccessor(f, f.getDeclaringClass(), f.getType(),
1747                     Modifier.isStatic(f.getModifiers()) ? MethodHandle.SPUT : MethodHandle.IPUT,
1748                     !f.isAccessible() /* performAccessChecks */);
1749         }
1750 
1751         // BEGIN Android-changed: OpenJDK 9+181 VarHandle API factory method.
1752         /**
1753          * Produces a VarHandle giving access to a reflected field {@code f}
1754          * of type {@code T} declared in a class of type {@code R}.
1755          * The VarHandle's variable type is {@code T}.
1756          * If the field is non-static the VarHandle has one coordinate type,
1757          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
1758          * coordinate types.
1759          * <p>
1760          * Access checking is performed immediately on behalf of the lookup
1761          * class, regardless of the value of the field's {@code accessible}
1762          * flag.
1763          * <p>
1764          * If the field is static, and if the returned VarHandle is operated
1765          * on, the field's declaring class will be initialized, if it has not
1766          * already been initialized.
1767          * <p>
1768          * Certain access modes of the returned VarHandle are unsupported under
1769          * the following conditions:
1770          * <ul>
1771          * <li>if the field is declared {@code final}, then the write, atomic
1772          *     update, numeric atomic update, and bitwise atomic update access
1773          *     modes are unsupported.
1774          * <li>if the field type is anything other than {@code byte},
1775          *     {@code short}, {@code char}, {@code int}, {@code long},
1776          *     {@code float}, or {@code double} then numeric atomic update
1777          *     access modes are unsupported.
1778          * <li>if the field type is anything other than {@code boolean},
1779          *     {@code byte}, {@code short}, {@code char}, {@code int} or
1780          *     {@code long} then bitwise atomic update access modes are
1781          *     unsupported.
1782          * </ul>
1783          * <p>
1784          * If the field is declared {@code volatile} then the returned VarHandle
1785          * will override access to the field (effectively ignore the
1786          * {@code volatile} declaration) in accordance to its specified
1787          * access modes.
1788          * <p>
1789          * If the field type is {@code float} or {@code double} then numeric
1790          * and atomic update access modes compare values using their bitwise
1791          * representation (see {@link Float#floatToRawIntBits} and
1792          * {@link Double#doubleToRawLongBits}, respectively).
1793          * @apiNote
1794          * Bitwise comparison of {@code float} values or {@code double} values,
1795          * as performed by the numeric and atomic update access modes, differ
1796          * from the primitive {@code ==} operator and the {@link Float#equals}
1797          * and {@link Double#equals} methods, specifically with respect to
1798          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
1799          * Care should be taken when performing a compare and set or a compare
1800          * and exchange operation with such values since the operation may
1801          * unexpectedly fail.
1802          * There are many possible NaN values that are considered to be
1803          * {@code NaN} in Java, although no IEEE 754 floating-point operation
1804          * provided by Java can distinguish between them.  Operation failure can
1805          * occur if the expected or witness value is a NaN value and it is
1806          * transformed (perhaps in a platform specific manner) into another NaN
1807          * value, and thus has a different bitwise representation (see
1808          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
1809          * details).
1810          * The values {@code -0.0} and {@code +0.0} have different bitwise
1811          * representations but are considered equal when using the primitive
1812          * {@code ==} operator.  Operation failure can occur if, for example, a
1813          * numeric algorithm computes an expected value to be say {@code -0.0}
1814          * and previously computed the witness value to be say {@code +0.0}.
1815          * @param f the reflected field, with a field of type {@code T}, and
1816          * a declaring class of type {@code R}
1817          * @return a VarHandle giving access to non-static fields or a static
1818          * field
1819          * @throws IllegalAccessException if access checking fails
1820          * @throws NullPointerException if the argument is null
1821          * @since 9
1822          * @hide
1823          */
unreflectVarHandle(Field f)1824         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
1825             final boolean isStatic = Modifier.isStatic(f.getModifiers());
1826             final boolean performAccessChecks = true;
1827             commonFieldChecks(f, f.getDeclaringClass(), f.getType(), isStatic, performAccessChecks);
1828             return FieldVarHandle.create(f);
1829         }
1830         // END Android-changed: OpenJDK 9+181 VarHandle API factory method.
1831 
1832         /**
1833          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1834          * created by this lookup object or a similar one.
1835          * Security and access checks are performed to ensure that this lookup object
1836          * is capable of reproducing the target method handle.
1837          * This means that the cracking may fail if target is a direct method handle
1838          * but was created by an unrelated lookup object.
1839          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
1840          * and was created by a lookup object for a different class.
1841          * @param target a direct method handle to crack into symbolic reference components
1842          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
1843          * @exception SecurityException if a security manager is present and it
1844          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1845          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
1846          * @exception NullPointerException if the target is {@code null}
1847          * @see MethodHandleInfo
1848          * @since 1.8
1849          */
revealDirect(MethodHandle target)1850         public MethodHandleInfo revealDirect(MethodHandle target) {
1851             MethodHandleImpl directTarget = getMethodHandleImpl(target);
1852             MethodHandleInfo info = directTarget.reveal();
1853 
1854             try {
1855                 checkAccess(lookupClass(), info.getDeclaringClass(), info.getModifiers(),
1856                         info.getName());
1857             } catch (IllegalAccessException exception) {
1858                 throw new IllegalArgumentException("Unable to access memeber.", exception);
1859             }
1860 
1861             return info;
1862         }
1863 
hasPrivateAccess()1864         private boolean hasPrivateAccess() {
1865             return (allowedModes & PRIVATE) != 0;
1866         }
1867 
1868         /** Check public/protected/private bits on the symbolic reference class and its member. */
checkAccess(Class<?> refc, Class<?> defc, int mods, String methName)1869         void checkAccess(Class<?> refc, Class<?> defc, int mods, String methName)
1870                 throws IllegalAccessException {
1871             int allowedModes = this.allowedModes;
1872 
1873             if (Modifier.isProtected(mods) &&
1874                     defc == Object.class &&
1875                     "clone".equals(methName) &&
1876                     refc.isArray()) {
1877                 // The JVM does this hack also.
1878                 // (See ClassVerifier::verify_invoke_instructions
1879                 // and LinkResolver::check_method_accessability.)
1880                 // Because the JVM does not allow separate methods on array types,
1881                 // there is no separate method for int[].clone.
1882                 // All arrays simply inherit Object.clone.
1883                 // But for access checking logic, we make Object.clone
1884                 // (normally protected) appear to be public.
1885                 // Later on, when the DirectMethodHandle is created,
1886                 // its leading argument will be restricted to the
1887                 // requested array type.
1888                 // N.B. The return type is not adjusted, because
1889                 // that is *not* the bytecode behavior.
1890                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
1891             }
1892 
1893             if (Modifier.isProtected(mods) && Modifier.isConstructor(mods)) {
1894                 // cannot "new" a protected ctor in a different package
1895                 mods ^= Modifier.PROTECTED;
1896             }
1897 
1898             if (Modifier.isPublic(mods) && Modifier.isPublic(refc.getModifiers()) && allowedModes != 0)
1899                 return;  // common case
1900             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
1901             if ((requestedModes & allowedModes) != 0) {
1902                 if (VerifyAccess.isMemberAccessible(refc, defc, mods, lookupClass(), allowedModes))
1903                     return;
1904             } else {
1905                 // Protected members can also be checked as if they were package-private.
1906                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
1907                         && VerifyAccess.isSamePackage(defc, lookupClass()))
1908                     return;
1909             }
1910 
1911             throwMakeAccessException(accessFailedMessage(refc, defc, mods), this);
1912         }
1913 
accessFailedMessage(Class<?> refc, Class<?> defc, int mods)1914         String accessFailedMessage(Class<?> refc, Class<?> defc, int mods) {
1915             // check the class first:
1916             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
1917                     (defc == refc ||
1918                             Modifier.isPublic(refc.getModifiers())));
1919             if (!classOK && (allowedModes & PACKAGE) != 0) {
1920                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
1921                         (defc == refc ||
1922                                 VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
1923             }
1924             if (!classOK)
1925                 return "class is not public";
1926             if (Modifier.isPublic(mods))
1927                 return "access to public member failed";  // (how?)
1928             if (Modifier.isPrivate(mods))
1929                 return "member is private";
1930             if (Modifier.isProtected(mods))
1931                 return "member is protected";
1932             return "member is private to package";
1933         }
1934 
1935         // Android-changed: checkSpecialCaller assumes that ALLOW_NESTMATE_ACCESS = false,
1936         // as in upstream OpenJDK.
1937         //
1938         // private static final boolean ALLOW_NESTMATE_ACCESS = false;
1939 
checkSpecialCaller(Class<?> specialCaller)1940         private void checkSpecialCaller(Class<?> specialCaller) throws IllegalAccessException {
1941             // Android-changed: No support for TRUSTED lookups. Also construct the
1942             // IllegalAccessException by hand because the upstream code implicitly assumes
1943             // that the lookupClass == specialCaller.
1944             //
1945             // if (allowedModes == TRUSTED)  return;
1946             if (!hasPrivateAccess() || (specialCaller != lookupClass())) {
1947                 throw new IllegalAccessException("no private access for invokespecial : "
1948                         + specialCaller + ", from" + this);
1949             }
1950         }
1951 
throwMakeAccessException(String message, Object from)1952         private void throwMakeAccessException(String message, Object from) throws
1953                 IllegalAccessException{
1954             message = message + ": "+ toString();
1955             if (from != null)  message += ", from " + from;
1956             throw new IllegalAccessException(message);
1957         }
1958 
checkReturnType(Method method, MethodType methodType)1959         private void checkReturnType(Method method, MethodType methodType)
1960                 throws NoSuchMethodException {
1961             if (method.getReturnType() != methodType.rtype()) {
1962                 throw new NoSuchMethodException(method.getName() + methodType);
1963             }
1964         }
1965     }
1966 
1967     /**
1968      * "Cracks" {@code target} to reveal the underlying {@code MethodHandleImpl}.
1969      */
getMethodHandleImpl(MethodHandle target)1970     private static MethodHandleImpl getMethodHandleImpl(MethodHandle target) {
1971         // Special case : We implement handles to constructors as transformers,
1972         // so we must extract the underlying handle from the transformer.
1973         if (target instanceof Transformers.Construct) {
1974             target = ((Transformers.Construct) target).getConstructorHandle();
1975         }
1976 
1977         // Special case: Var-args methods are also implemented as Transformers,
1978         // so we should get the underlying handle in that case as well.
1979         if (target instanceof Transformers.VarargsCollector) {
1980             target = target.asFixedArity();
1981         }
1982 
1983         if (target instanceof MethodHandleImpl) {
1984             return (MethodHandleImpl) target;
1985         }
1986 
1987         throw new IllegalArgumentException(target + " is not a direct handle");
1988     }
1989 
1990     // BEGIN Android-added: method to check if a class is an array.
checkClassIsArray(Class<?> c)1991     private static void checkClassIsArray(Class<?> c) {
1992         if (!c.isArray()) {
1993             throw new IllegalArgumentException("Not an array type: " + c);
1994         }
1995     }
1996 
checkTypeIsViewable(Class<?> componentType)1997     private static void checkTypeIsViewable(Class<?> componentType) {
1998         if (componentType == short.class ||
1999             componentType == char.class ||
2000             componentType == int.class ||
2001             componentType == long.class ||
2002             componentType == float.class ||
2003             componentType == double.class) {
2004             return;
2005         }
2006         throw new UnsupportedOperationException("Component type not supported: " + componentType);
2007     }
2008     // END Android-added: method to check if a class is an array.
2009 
2010     /**
2011      * Produces a method handle giving read access to elements of an array.
2012      * The type of the method handle will have a return type of the array's
2013      * element type.  Its first argument will be the array type,
2014      * and the second will be {@code int}.
2015      * @param arrayClass an array type
2016      * @return a method handle which can load values from the given array type
2017      * @throws NullPointerException if the argument is null
2018      * @throws  IllegalArgumentException if arrayClass is not an array type
2019      */
2020     public static
arrayElementGetter(Class<?> arrayClass)2021     MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
2022         checkClassIsArray(arrayClass);
2023         final Class<?> componentType = arrayClass.getComponentType();
2024         if (componentType.isPrimitive()) {
2025             try {
2026                 return Lookup.PUBLIC_LOOKUP.findStatic(MethodHandles.class,
2027                         "arrayElementGetter",
2028                         MethodType.methodType(componentType, arrayClass, int.class));
2029             } catch (NoSuchMethodException | IllegalAccessException exception) {
2030                 throw new AssertionError(exception);
2031             }
2032         }
2033 
2034         return new Transformers.ReferenceArrayElementGetter(arrayClass);
2035     }
2036 
arrayElementGetter(byte[] array, int i)2037     /** @hide */ public static byte arrayElementGetter(byte[] array, int i) { return array[i]; }
arrayElementGetter(boolean[] array, int i)2038     /** @hide */ public static boolean arrayElementGetter(boolean[] array, int i) { return array[i]; }
arrayElementGetter(char[] array, int i)2039     /** @hide */ public static char arrayElementGetter(char[] array, int i) { return array[i]; }
arrayElementGetter(short[] array, int i)2040     /** @hide */ public static short arrayElementGetter(short[] array, int i) { return array[i]; }
arrayElementGetter(int[] array, int i)2041     /** @hide */ public static int arrayElementGetter(int[] array, int i) { return array[i]; }
arrayElementGetter(long[] array, int i)2042     /** @hide */ public static long arrayElementGetter(long[] array, int i) { return array[i]; }
arrayElementGetter(float[] array, int i)2043     /** @hide */ public static float arrayElementGetter(float[] array, int i) { return array[i]; }
arrayElementGetter(double[] array, int i)2044     /** @hide */ public static double arrayElementGetter(double[] array, int i) { return array[i]; }
2045 
2046     /**
2047      * Produces a method handle giving write access to elements of an array.
2048      * The type of the method handle will have a void return type.
2049      * Its last argument will be the array's element type.
2050      * The first and second arguments will be the array type and int.
2051      * @param arrayClass the class of an array
2052      * @return a method handle which can store values into the array type
2053      * @throws NullPointerException if the argument is null
2054      * @throws IllegalArgumentException if arrayClass is not an array type
2055      */
2056     public static
arrayElementSetter(Class<?> arrayClass)2057     MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
2058         checkClassIsArray(arrayClass);
2059         final Class<?> componentType = arrayClass.getComponentType();
2060         if (componentType.isPrimitive()) {
2061             try {
2062                 return Lookup.PUBLIC_LOOKUP.findStatic(MethodHandles.class,
2063                         "arrayElementSetter",
2064                         MethodType.methodType(void.class, arrayClass, int.class, componentType));
2065             } catch (NoSuchMethodException | IllegalAccessException exception) {
2066                 throw new AssertionError(exception);
2067             }
2068         }
2069 
2070         return new Transformers.ReferenceArrayElementSetter(arrayClass);
2071     }
2072 
2073     /** @hide */
arrayElementSetter(byte[] array, int i, byte val)2074     public static void arrayElementSetter(byte[] array, int i, byte val) { array[i] = val; }
2075     /** @hide */
arrayElementSetter(boolean[] array, int i, boolean val)2076     public static void arrayElementSetter(boolean[] array, int i, boolean val) { array[i] = val; }
2077     /** @hide */
arrayElementSetter(char[] array, int i, char val)2078     public static void arrayElementSetter(char[] array, int i, char val) { array[i] = val; }
2079     /** @hide */
arrayElementSetter(short[] array, int i, short val)2080     public static void arrayElementSetter(short[] array, int i, short val) { array[i] = val; }
2081     /** @hide */
arrayElementSetter(int[] array, int i, int val)2082     public static void arrayElementSetter(int[] array, int i, int val) { array[i] = val; }
2083     /** @hide */
arrayElementSetter(long[] array, int i, long val)2084     public static void arrayElementSetter(long[] array, int i, long val) { array[i] = val; }
2085     /** @hide */
arrayElementSetter(float[] array, int i, float val)2086     public static void arrayElementSetter(float[] array, int i, float val) { array[i] = val; }
2087     /** @hide */
arrayElementSetter(double[] array, int i, double val)2088     public static void arrayElementSetter(double[] array, int i, double val) { array[i] = val; }
2089 
2090     // BEGIN Android-changed: OpenJDK 9+181 VarHandle API factory methods.
2091     /**
2092      * Produces a VarHandle giving access to elements of an array of type
2093      * {@code arrayClass}.  The VarHandle's variable type is the component type
2094      * of {@code arrayClass} and the list of coordinate types is
2095      * {@code (arrayClass, int)}, where the {@code int} coordinate type
2096      * corresponds to an argument that is an index into an array.
2097      * <p>
2098      * Certain access modes of the returned VarHandle are unsupported under
2099      * the following conditions:
2100      * <ul>
2101      * <li>if the component type is anything other than {@code byte},
2102      *     {@code short}, {@code char}, {@code int}, {@code long},
2103      *     {@code float}, or {@code double} then numeric atomic update access
2104      *     modes are unsupported.
2105      * <li>if the field type is anything other than {@code boolean},
2106      *     {@code byte}, {@code short}, {@code char}, {@code int} or
2107      *     {@code long} then bitwise atomic update access modes are
2108      *     unsupported.
2109      * </ul>
2110      * <p>
2111      * If the component type is {@code float} or {@code double} then numeric
2112      * and atomic update access modes compare values using their bitwise
2113      * representation (see {@link Float#floatToRawIntBits} and
2114      * {@link Double#doubleToRawLongBits}, respectively).
2115      * @apiNote
2116      * Bitwise comparison of {@code float} values or {@code double} values,
2117      * as performed by the numeric and atomic update access modes, differ
2118      * from the primitive {@code ==} operator and the {@link Float#equals}
2119      * and {@link Double#equals} methods, specifically with respect to
2120      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
2121      * Care should be taken when performing a compare and set or a compare
2122      * and exchange operation with such values since the operation may
2123      * unexpectedly fail.
2124      * There are many possible NaN values that are considered to be
2125      * {@code NaN} in Java, although no IEEE 754 floating-point operation
2126      * provided by Java can distinguish between them.  Operation failure can
2127      * occur if the expected or witness value is a NaN value and it is
2128      * transformed (perhaps in a platform specific manner) into another NaN
2129      * value, and thus has a different bitwise representation (see
2130      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
2131      * details).
2132      * The values {@code -0.0} and {@code +0.0} have different bitwise
2133      * representations but are considered equal when using the primitive
2134      * {@code ==} operator.  Operation failure can occur if, for example, a
2135      * numeric algorithm computes an expected value to be say {@code -0.0}
2136      * and previously computed the witness value to be say {@code +0.0}.
2137      * @param arrayClass the class of an array, of type {@code T[]}
2138      * @return a VarHandle giving access to elements of an array
2139      * @throws NullPointerException if the arrayClass is null
2140      * @throws IllegalArgumentException if arrayClass is not an array type
2141      * @since 9
2142      * @hide
2143      */
2144     public static
arrayElementVarHandle(Class<?> arrayClass)2145     VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
2146         checkClassIsArray(arrayClass);
2147         return ArrayElementVarHandle.create(arrayClass);
2148     }
2149 
2150     /**
2151      * Produces a VarHandle giving access to elements of a {@code byte[]} array
2152      * viewed as if it were a different primitive array type, such as
2153      * {@code int[]} or {@code long[]}.
2154      * The VarHandle's variable type is the component type of
2155      * {@code viewArrayClass} and the list of coordinate types is
2156      * {@code (byte[], int)}, where the {@code int} coordinate type
2157      * corresponds to an argument that is an index into a {@code byte[]} array.
2158      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
2159      * array, composing bytes to or from a value of the component type of
2160      * {@code viewArrayClass} according to the given endianness.
2161      * <p>
2162      * The supported component types (variables types) are {@code short},
2163      * {@code char}, {@code int}, {@code long}, {@code float} and
2164      * {@code double}.
2165      * <p>
2166      * Access of bytes at a given index will result in an
2167      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
2168      * or greater than the {@code byte[]} array length minus the size (in bytes)
2169      * of {@code T}.
2170      * <p>
2171      * Access of bytes at an index may be aligned or misaligned for {@code T},
2172      * with respect to the underlying memory address, {@code A} say, associated
2173      * with the array and index.
2174      * If access is misaligned then access for anything other than the
2175      * {@code get} and {@code set} access modes will result in an
2176      * {@code IllegalStateException}.  In such cases atomic access is only
2177      * guaranteed with respect to the largest power of two that divides the GCD
2178      * of {@code A} and the size (in bytes) of {@code T}.
2179      * If access is aligned then following access modes are supported and are
2180      * guaranteed to support atomic access:
2181      * <ul>
2182      * <li>read write access modes for all {@code T}, with the exception of
2183      *     access modes {@code get} and {@code set} for {@code long} and
2184      *     {@code double} on 32-bit platforms.
2185      * <li>atomic update access modes for {@code int}, {@code long},
2186      *     {@code float} or {@code double}.
2187      *     (Future major platform releases of the JDK may support additional
2188      *     types for certain currently unsupported access modes.)
2189      * <li>numeric atomic update access modes for {@code int} and {@code long}.
2190      *     (Future major platform releases of the JDK may support additional
2191      *     numeric types for certain currently unsupported access modes.)
2192      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
2193      *     (Future major platform releases of the JDK may support additional
2194      *     numeric types for certain currently unsupported access modes.)
2195      * </ul>
2196      * <p>
2197      * Misaligned access, and therefore atomicity guarantees, may be determined
2198      * for {@code byte[]} arrays without operating on a specific array.  Given
2199      * an {@code index}, {@code T} and it's corresponding boxed type,
2200      * {@code T_BOX}, misalignment may be determined as follows:
2201      * <pre>{@code
2202      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
2203      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
2204      *     alignmentOffset(0, sizeOfT);
2205      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
2206      * boolean isMisaligned = misalignedAtIndex != 0;
2207      * }</pre>
2208      * <p>
2209      * If the variable type is {@code float} or {@code double} then atomic
2210      * update access modes compare values using their bitwise representation
2211      * (see {@link Float#floatToRawIntBits} and
2212      * {@link Double#doubleToRawLongBits}, respectively).
2213      * @param viewArrayClass the view array class, with a component type of
2214      * type {@code T}
2215      * @param byteOrder the endianness of the view array elements, as
2216      * stored in the underlying {@code byte} array
2217      * @return a VarHandle giving access to elements of a {@code byte[]} array
2218      * viewed as if elements corresponding to the components type of the view
2219      * array class
2220      * @throws NullPointerException if viewArrayClass or byteOrder is null
2221      * @throws IllegalArgumentException if viewArrayClass is not an array type
2222      * @throws UnsupportedOperationException if the component type of
2223      * viewArrayClass is not supported as a variable type
2224      * @since 9
2225      * @hide
2226      */
2227     public static
byteArrayViewVarHandle(Class<?> viewArrayClass, ByteOrder byteOrder)2228     VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
2229                                      ByteOrder byteOrder) throws IllegalArgumentException {
2230         checkClassIsArray(viewArrayClass);
2231         checkTypeIsViewable(viewArrayClass.getComponentType());
2232         return ByteArrayViewVarHandle.create(viewArrayClass, byteOrder);
2233     }
2234 
2235     /**
2236      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
2237      * viewed as if it were an array of elements of a different primitive
2238      * component type to that of {@code byte}, such as {@code int[]} or
2239      * {@code long[]}.
2240      * The VarHandle's variable type is the component type of
2241      * {@code viewArrayClass} and the list of coordinate types is
2242      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
2243      * corresponds to an argument that is an index into a {@code byte[]} array.
2244      * The returned VarHandle accesses bytes at an index in a
2245      * {@code ByteBuffer}, composing bytes to or from a value of the component
2246      * type of {@code viewArrayClass} according to the given endianness.
2247      * <p>
2248      * The supported component types (variables types) are {@code short},
2249      * {@code char}, {@code int}, {@code long}, {@code float} and
2250      * {@code double}.
2251      * <p>
2252      * Access will result in a {@code ReadOnlyBufferException} for anything
2253      * other than the read access modes if the {@code ByteBuffer} is read-only.
2254      * <p>
2255      * Access of bytes at a given index will result in an
2256      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
2257      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
2258      * {@code T}.
2259      * <p>
2260      * Access of bytes at an index may be aligned or misaligned for {@code T},
2261      * with respect to the underlying memory address, {@code A} say, associated
2262      * with the {@code ByteBuffer} and index.
2263      * If access is misaligned then access for anything other than the
2264      * {@code get} and {@code set} access modes will result in an
2265      * {@code IllegalStateException}.  In such cases atomic access is only
2266      * guaranteed with respect to the largest power of two that divides the GCD
2267      * of {@code A} and the size (in bytes) of {@code T}.
2268      * If access is aligned then following access modes are supported and are
2269      * guaranteed to support atomic access:
2270      * <ul>
2271      * <li>read write access modes for all {@code T}, with the exception of
2272      *     access modes {@code get} and {@code set} for {@code long} and
2273      *     {@code double} on 32-bit platforms.
2274      * <li>atomic update access modes for {@code int}, {@code long},
2275      *     {@code float} or {@code double}.
2276      *     (Future major platform releases of the JDK may support additional
2277      *     types for certain currently unsupported access modes.)
2278      * <li>numeric atomic update access modes for {@code int} and {@code long}.
2279      *     (Future major platform releases of the JDK may support additional
2280      *     numeric types for certain currently unsupported access modes.)
2281      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
2282      *     (Future major platform releases of the JDK may support additional
2283      *     numeric types for certain currently unsupported access modes.)
2284      * </ul>
2285      * <p>
2286      * Misaligned access, and therefore atomicity guarantees, may be determined
2287      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
2288      * {@code index}, {@code T} and it's corresponding boxed type,
2289      * {@code T_BOX}, as follows:
2290      * <pre>{@code
2291      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
2292      * ByteBuffer bb = ...
2293      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
2294      * boolean isMisaligned = misalignedAtIndex != 0;
2295      * }</pre>
2296      * <p>
2297      * If the variable type is {@code float} or {@code double} then atomic
2298      * update access modes compare values using their bitwise representation
2299      * (see {@link Float#floatToRawIntBits} and
2300      * {@link Double#doubleToRawLongBits}, respectively).
2301      * @param viewArrayClass the view array class, with a component type of
2302      * type {@code T}
2303      * @param byteOrder the endianness of the view array elements, as
2304      * stored in the underlying {@code ByteBuffer} (Note this overrides the
2305      * endianness of a {@code ByteBuffer})
2306      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
2307      * viewed as if elements corresponding to the components type of the view
2308      * array class
2309      * @throws NullPointerException if viewArrayClass or byteOrder is null
2310      * @throws IllegalArgumentException if viewArrayClass is not an array type
2311      * @throws UnsupportedOperationException if the component type of
2312      * viewArrayClass is not supported as a variable type
2313      * @since 9
2314      * @hide
2315      */
2316     public static
byteBufferViewVarHandle(Class<?> viewArrayClass, ByteOrder byteOrder)2317     VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
2318                                       ByteOrder byteOrder) throws IllegalArgumentException {
2319         checkClassIsArray(viewArrayClass);
2320         checkTypeIsViewable(viewArrayClass.getComponentType());
2321         return ByteBufferViewVarHandle.create(viewArrayClass, byteOrder);
2322     }
2323     // END Android-changed: OpenJDK 9+181 VarHandle API factory methods.
2324 
2325     /// method handle invocation (reflective style)
2326 
2327     /**
2328      * Produces a method handle which will invoke any method handle of the
2329      * given {@code type}, with a given number of trailing arguments replaced by
2330      * a single trailing {@code Object[]} array.
2331      * The resulting invoker will be a method handle with the following
2332      * arguments:
2333      * <ul>
2334      * <li>a single {@code MethodHandle} target
2335      * <li>zero or more leading values (counted by {@code leadingArgCount})
2336      * <li>an {@code Object[]} array containing trailing arguments
2337      * </ul>
2338      * <p>
2339      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
2340      * the indicated {@code type}.
2341      * That is, if the target is exactly of the given {@code type}, it will behave
2342      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
2343      * is used to convert the target to the required {@code type}.
2344      * <p>
2345      * The type of the returned invoker will not be the given {@code type}, but rather
2346      * will have all parameters except the first {@code leadingArgCount}
2347      * replaced by a single array of type {@code Object[]}, which will be
2348      * the final parameter.
2349      * <p>
2350      * Before invoking its target, the invoker will spread the final array, apply
2351      * reference casts as necessary, and unbox and widen primitive arguments.
2352      * If, when the invoker is called, the supplied array argument does
2353      * not have the correct number of elements, the invoker will throw
2354      * an {@link IllegalArgumentException} instead of invoking the target.
2355      * <p>
2356      * This method is equivalent to the following code (though it may be more efficient):
2357      * <blockquote><pre>{@code
2358 MethodHandle invoker = MethodHandles.invoker(type);
2359 int spreadArgCount = type.parameterCount() - leadingArgCount;
2360 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
2361 return invoker;
2362      * }</pre></blockquote>
2363      * This method throws no reflective or security exceptions.
2364      * @param type the desired target type
2365      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
2366      * @return a method handle suitable for invoking any method handle of the given type
2367      * @throws NullPointerException if {@code type} is null
2368      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
2369      *                  the range from 0 to {@code type.parameterCount()} inclusive,
2370      *                  or if the resulting method handle's type would have
2371      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2372      */
2373     static public
spreadInvoker(MethodType type, int leadingArgCount)2374     MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
2375         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
2376             throw newIllegalArgumentException("bad argument count", leadingArgCount);
2377 
2378         MethodHandle invoker = MethodHandles.invoker(type);
2379         int spreadArgCount = type.parameterCount() - leadingArgCount;
2380         invoker = invoker.asSpreader(Object[].class, spreadArgCount);
2381         return invoker;
2382     }
2383 
2384     /**
2385      * Produces a special <em>invoker method handle</em> which can be used to
2386      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
2387      * The resulting invoker will have a type which is
2388      * exactly equal to the desired type, except that it will accept
2389      * an additional leading argument of type {@code MethodHandle}.
2390      * <p>
2391      * This method is equivalent to the following code (though it may be more efficient):
2392      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
2393      *
2394      * <p style="font-size:smaller;">
2395      * <em>Discussion:</em>
2396      * Invoker method handles can be useful when working with variable method handles
2397      * of unknown types.
2398      * For example, to emulate an {@code invokeExact} call to a variable method
2399      * handle {@code M}, extract its type {@code T},
2400      * look up the invoker method {@code X} for {@code T},
2401      * and call the invoker method, as {@code X.invoke(T, A...)}.
2402      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
2403      * is unknown.)
2404      * If spreading, collecting, or other argument transformations are required,
2405      * they can be applied once to the invoker {@code X} and reused on many {@code M}
2406      * method handle values, as long as they are compatible with the type of {@code X}.
2407      * <p style="font-size:smaller;">
2408      * <em>(Note:  The invoker method is not available via the Core Reflection API.
2409      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
2410      * on the declared {@code invokeExact} or {@code invoke} method will raise an
2411      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
2412      * <p>
2413      * This method throws no reflective or security exceptions.
2414      * @param type the desired target type
2415      * @return a method handle suitable for invoking any method handle of the given type
2416      * @throws IllegalArgumentException if the resulting method handle's type would have
2417      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2418      */
2419     static public
exactInvoker(MethodType type)2420     MethodHandle exactInvoker(MethodType type) {
2421         return new Transformers.Invoker(type, true /* isExactInvoker */);
2422     }
2423 
2424     /**
2425      * Produces a special <em>invoker method handle</em> which can be used to
2426      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
2427      * The resulting invoker will have a type which is
2428      * exactly equal to the desired type, except that it will accept
2429      * an additional leading argument of type {@code MethodHandle}.
2430      * <p>
2431      * Before invoking its target, if the target differs from the expected type,
2432      * the invoker will apply reference casts as
2433      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
2434      * Similarly, the return value will be converted as necessary.
2435      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
2436      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
2437      * <p>
2438      * This method is equivalent to the following code (though it may be more efficient):
2439      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
2440      * <p style="font-size:smaller;">
2441      * <em>Discussion:</em>
2442      * A {@linkplain MethodType#genericMethodType general method type} is one which
2443      * mentions only {@code Object} arguments and return values.
2444      * An invoker for such a type is capable of calling any method handle
2445      * of the same arity as the general type.
2446      * <p style="font-size:smaller;">
2447      * <em>(Note:  The invoker method is not available via the Core Reflection API.
2448      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
2449      * on the declared {@code invokeExact} or {@code invoke} method will raise an
2450      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
2451      * <p>
2452      * This method throws no reflective or security exceptions.
2453      * @param type the desired target type
2454      * @return a method handle suitable for invoking any method handle convertible to the given type
2455      * @throws IllegalArgumentException if the resulting method handle's type would have
2456      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2457      */
2458     static public
invoker(MethodType type)2459     MethodHandle invoker(MethodType type) {
2460         return new Transformers.Invoker(type, false /* isExactInvoker */);
2461     }
2462 
2463     // BEGIN Android-added: resolver for VarHandle accessor methods.
methodHandleForVarHandleAccessor(VarHandle.AccessMode accessMode, MethodType type, boolean isExactInvoker)2464     static private MethodHandle methodHandleForVarHandleAccessor(VarHandle.AccessMode accessMode,
2465                                                                  MethodType type,
2466                                                                  boolean isExactInvoker) {
2467         Class<?> refc = VarHandle.class;
2468         Method method;
2469         try {
2470             method = refc.getDeclaredMethod(accessMode.methodName(), Object[].class);
2471         } catch (NoSuchMethodException e) {
2472             throw new InternalError("No method for AccessMode " + accessMode, e);
2473         }
2474         MethodType methodType = type.insertParameterTypes(0, VarHandle.class);
2475         int kind = isExactInvoker ? MethodHandle.INVOKE_VAR_HANDLE_EXACT
2476                                   : MethodHandle.INVOKE_VAR_HANDLE;
2477         return new MethodHandleImpl(method.getArtMethod(), kind, methodType);
2478     }
2479     // END Android-added: resolver for VarHandle accessor methods.
2480 
2481     /**
2482      * Produces a special <em>invoker method handle</em> which can be used to
2483      * invoke a signature-polymorphic access mode method on any VarHandle whose
2484      * associated access mode type is compatible with the given type.
2485      * The resulting invoker will have a type which is exactly equal to the
2486      * desired given type, except that it will accept an additional leading
2487      * argument of type {@code VarHandle}.
2488      *
2489      * @param accessMode the VarHandle access mode
2490      * @param type the desired target type
2491      * @return a method handle suitable for invoking an access mode method of
2492      *         any VarHandle whose access mode type is of the given type.
2493      * @since 9
2494      * @hide
2495      */
2496     static public
varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type)2497     MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
2498         return methodHandleForVarHandleAccessor(accessMode, type, true /* isExactInvoker */);
2499     }
2500 
2501     /**
2502      * Produces a special <em>invoker method handle</em> which can be used to
2503      * invoke a signature-polymorphic access mode method on any VarHandle whose
2504      * associated access mode type is compatible with the given type.
2505      * The resulting invoker will have a type which is exactly equal to the
2506      * desired given type, except that it will accept an additional leading
2507      * argument of type {@code VarHandle}.
2508      * <p>
2509      * Before invoking its target, if the access mode type differs from the
2510      * desired given type, the invoker will apply reference casts as necessary
2511      * and box, unbox, or widen primitive values, as if by
2512      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
2513      * converted as necessary.
2514      * <p>
2515      * This method is equivalent to the following code (though it may be more
2516      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
2517      *
2518      * @param accessMode the VarHandle access mode
2519      * @param type the desired target type
2520      * @return a method handle suitable for invoking an access mode method of
2521      *         any VarHandle whose access mode type is convertible to the given
2522      *         type.
2523      * @since 9
2524      * @hide
2525      */
2526     static public
varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type)2527     MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
2528         return methodHandleForVarHandleAccessor(accessMode, type, false /* isExactInvoker */);
2529     }
2530 
2531     // Android-changed: Basic invokers are not supported.
2532     //
2533     // static /*non-public*/
2534     // MethodHandle basicInvoker(MethodType type) {
2535     //     return type.invokers().basicInvoker();
2536     // }
2537 
2538      /// method handle modification (creation from other method handles)
2539 
2540     /**
2541      * Produces a method handle which adapts the type of the
2542      * given method handle to a new type by pairwise argument and return type conversion.
2543      * The original type and new type must have the same number of arguments.
2544      * The resulting method handle is guaranteed to report a type
2545      * which is equal to the desired new type.
2546      * <p>
2547      * If the original type and new type are equal, returns target.
2548      * <p>
2549      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
2550      * and some additional conversions are also applied if those conversions fail.
2551      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
2552      * if possible, before or instead of any conversions done by {@code asType}:
2553      * <ul>
2554      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
2555      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
2556      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
2557      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
2558      *     the boolean is converted to a byte value, 1 for true, 0 for false.
2559      *     (This treatment follows the usage of the bytecode verifier.)
2560      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
2561      *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
2562      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
2563      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
2564      *     then a Java casting conversion (JLS 5.5) is applied.
2565      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
2566      *     widening and/or narrowing.)
2567      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
2568      *     conversion will be applied at runtime, possibly followed
2569      *     by a Java casting conversion (JLS 5.5) on the primitive value,
2570      *     possibly followed by a conversion from byte to boolean by testing
2571      *     the low-order bit.
2572      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
2573      *     and if the reference is null at runtime, a zero value is introduced.
2574      * </ul>
2575      * @param target the method handle to invoke after arguments are retyped
2576      * @param newType the expected type of the new method handle
2577      * @return a method handle which delegates to the target after performing
2578      *           any necessary argument conversions, and arranges for any
2579      *           necessary return value conversions
2580      * @throws NullPointerException if either argument is null
2581      * @throws WrongMethodTypeException if the conversion cannot be made
2582      * @see MethodHandle#asType
2583      */
2584     public static
explicitCastArguments(MethodHandle target, MethodType newType)2585     MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
2586         explicitCastArgumentsChecks(target, newType);
2587         // use the asTypeCache when possible:
2588         MethodType oldType = target.type();
2589         if (oldType == newType) return target;
2590         if (oldType.explicitCastEquivalentToAsType(newType)) {
2591             return target.asFixedArity().asType(newType);
2592         }
2593 
2594         return new Transformers.ExplicitCastArguments(target, newType);
2595     }
2596 
explicitCastArgumentsChecks(MethodHandle target, MethodType newType)2597     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
2598         if (target.type().parameterCount() != newType.parameterCount()) {
2599             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
2600         }
2601     }
2602 
2603     /**
2604      * Produces a method handle which adapts the calling sequence of the
2605      * given method handle to a new type, by reordering the arguments.
2606      * The resulting method handle is guaranteed to report a type
2607      * which is equal to the desired new type.
2608      * <p>
2609      * The given array controls the reordering.
2610      * Call {@code #I} the number of incoming parameters (the value
2611      * {@code newType.parameterCount()}, and call {@code #O} the number
2612      * of outgoing parameters (the value {@code target.type().parameterCount()}).
2613      * Then the length of the reordering array must be {@code #O},
2614      * and each element must be a non-negative number less than {@code #I}.
2615      * For every {@code N} less than {@code #O}, the {@code N}-th
2616      * outgoing argument will be taken from the {@code I}-th incoming
2617      * argument, where {@code I} is {@code reorder[N]}.
2618      * <p>
2619      * No argument or return value conversions are applied.
2620      * The type of each incoming argument, as determined by {@code newType},
2621      * must be identical to the type of the corresponding outgoing parameter
2622      * or parameters in the target method handle.
2623      * The return type of {@code newType} must be identical to the return
2624      * type of the original target.
2625      * <p>
2626      * The reordering array need not specify an actual permutation.
2627      * An incoming argument will be duplicated if its index appears
2628      * more than once in the array, and an incoming argument will be dropped
2629      * if its index does not appear in the array.
2630      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
2631      * incoming arguments which are not mentioned in the reordering array
2632      * are may be any type, as determined only by {@code newType}.
2633      * <blockquote><pre>{@code
2634 import static java.lang.invoke.MethodHandles.*;
2635 import static java.lang.invoke.MethodType.*;
2636 ...
2637 MethodType intfn1 = methodType(int.class, int.class);
2638 MethodType intfn2 = methodType(int.class, int.class, int.class);
2639 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
2640 assert(sub.type().equals(intfn2));
2641 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
2642 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
2643 assert((int)rsub.invokeExact(1, 100) == 99);
2644 MethodHandle add = ... (int x, int y) -> (x+y) ...;
2645 assert(add.type().equals(intfn2));
2646 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
2647 assert(twice.type().equals(intfn1));
2648 assert((int)twice.invokeExact(21) == 42);
2649      * }</pre></blockquote>
2650      * @param target the method handle to invoke after arguments are reordered
2651      * @param newType the expected type of the new method handle
2652      * @param reorder an index array which controls the reordering
2653      * @return a method handle which delegates to the target after it
2654      *           drops unused arguments and moves and/or duplicates the other arguments
2655      * @throws NullPointerException if any argument is null
2656      * @throws IllegalArgumentException if the index array length is not equal to
2657      *                  the arity of the target, or if any index array element
2658      *                  not a valid index for a parameter of {@code newType},
2659      *                  or if two corresponding parameter types in
2660      *                  {@code target.type()} and {@code newType} are not identical,
2661      */
2662     public static
permuteArguments(MethodHandle target, MethodType newType, int... reorder)2663     MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
2664         reorder = reorder.clone();  // get a private copy
2665         MethodType oldType = target.type();
2666         permuteArgumentChecks(reorder, newType, oldType);
2667 
2668         return new Transformers.PermuteArguments(newType, target, reorder);
2669     }
2670 
2671     // Android-changed: findFirstDupOrDrop is unused and removed.
2672     // private static int findFirstDupOrDrop(int[] reorder, int newArity);
2673 
permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType)2674     private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
2675         if (newType.returnType() != oldType.returnType())
2676             throw newIllegalArgumentException("return types do not match",
2677                     oldType, newType);
2678         if (reorder.length == oldType.parameterCount()) {
2679             int limit = newType.parameterCount();
2680             boolean bad = false;
2681             for (int j = 0; j < reorder.length; j++) {
2682                 int i = reorder[j];
2683                 if (i < 0 || i >= limit) {
2684                     bad = true; break;
2685                 }
2686                 Class<?> src = newType.parameterType(i);
2687                 Class<?> dst = oldType.parameterType(j);
2688                 if (src != dst)
2689                     throw newIllegalArgumentException("parameter types do not match after reorder",
2690                             oldType, newType);
2691             }
2692             if (!bad)  return true;
2693         }
2694         throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
2695     }
2696 
2697     /**
2698      * Produces a method handle of the requested return type which returns the given
2699      * constant value every time it is invoked.
2700      * <p>
2701      * Before the method handle is returned, the passed-in value is converted to the requested type.
2702      * If the requested type is primitive, widening primitive conversions are attempted,
2703      * else reference conversions are attempted.
2704      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
2705      * @param type the return type of the desired method handle
2706      * @param value the value to return
2707      * @return a method handle of the given return type and no arguments, which always returns the given value
2708      * @throws NullPointerException if the {@code type} argument is null
2709      * @throws ClassCastException if the value cannot be converted to the required return type
2710      * @throws IllegalArgumentException if the given type is {@code void.class}
2711      */
2712     public static
constant(Class<?> type, Object value)2713     MethodHandle constant(Class<?> type, Object value) {
2714         if (type.isPrimitive()) {
2715             if (type == void.class)
2716                 throw newIllegalArgumentException("void type");
2717             Wrapper w = Wrapper.forPrimitiveType(type);
2718             value = w.convert(value, type);
2719         }
2720 
2721         return new Transformers.Constant(type, value);
2722     }
2723 
2724     /**
2725      * Produces a method handle which returns its sole argument when invoked.
2726      * @param type the type of the sole parameter and return value of the desired method handle
2727      * @return a unary method handle which accepts and returns the given type
2728      * @throws NullPointerException if the argument is null
2729      * @throws IllegalArgumentException if the given type is {@code void.class}
2730      */
2731     public static
identity(Class<?> type)2732     MethodHandle identity(Class<?> type) {
2733         if (type == null) {
2734             throw new NullPointerException("type == null");
2735         }
2736 
2737         if (type.isPrimitive()) {
2738             try {
2739                 return Lookup.PUBLIC_LOOKUP.findStatic(MethodHandles.class, "identity",
2740                         MethodType.methodType(type, type));
2741             } catch (NoSuchMethodException | IllegalAccessException e) {
2742                 throw new AssertionError(e);
2743             }
2744         }
2745 
2746         return new Transformers.ReferenceIdentity(type);
2747     }
2748 
identity(byte val)2749     /** @hide */ public static byte identity(byte val) { return val; }
identity(boolean val)2750     /** @hide */ public static boolean identity(boolean val) { return val; }
identity(char val)2751     /** @hide */ public static char identity(char val) { return val; }
identity(short val)2752     /** @hide */ public static short identity(short val) { return val; }
identity(int val)2753     /** @hide */ public static int identity(int val) { return val; }
identity(long val)2754     /** @hide */ public static long identity(long val) { return val; }
identity(float val)2755     /** @hide */ public static float identity(float val) { return val; }
identity(double val)2756     /** @hide */ public static double identity(double val) { return val; }
2757 
2758     /**
2759      * Provides a target method handle with one or more <em>bound arguments</em>
2760      * in advance of the method handle's invocation.
2761      * The formal parameters to the target corresponding to the bound
2762      * arguments are called <em>bound parameters</em>.
2763      * Returns a new method handle which saves away the bound arguments.
2764      * When it is invoked, it receives arguments for any non-bound parameters,
2765      * binds the saved arguments to their corresponding parameters,
2766      * and calls the original target.
2767      * <p>
2768      * The type of the new method handle will drop the types for the bound
2769      * parameters from the original target type, since the new method handle
2770      * will no longer require those arguments to be supplied by its callers.
2771      * <p>
2772      * Each given argument object must match the corresponding bound parameter type.
2773      * If a bound parameter type is a primitive, the argument object
2774      * must be a wrapper, and will be unboxed to produce the primitive value.
2775      * <p>
2776      * The {@code pos} argument selects which parameters are to be bound.
2777      * It may range between zero and <i>N-L</i> (inclusively),
2778      * where <i>N</i> is the arity of the target method handle
2779      * and <i>L</i> is the length of the values array.
2780      * @param target the method handle to invoke after the argument is inserted
2781      * @param pos where to insert the argument (zero for the first)
2782      * @param values the series of arguments to insert
2783      * @return a method handle which inserts an additional argument,
2784      *         before calling the original method handle
2785      * @throws NullPointerException if the target or the {@code values} array is null
2786      * @see MethodHandle#bindTo
2787      */
2788     public static
insertArguments(MethodHandle target, int pos, Object... values)2789     MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
2790         int insCount = values.length;
2791         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
2792         if (insCount == 0)  {
2793             return target;
2794         }
2795 
2796         // Throw ClassCastExceptions early if we can't cast any of the provided values
2797         // to the required type.
2798         for (int i = 0; i < insCount; i++) {
2799             final Class<?> ptype = ptypes[pos + i];
2800             if (!ptype.isPrimitive()) {
2801                 ptypes[pos + i].cast(values[i]);
2802             } else {
2803                 // Will throw a ClassCastException if something terrible happens.
2804                 values[i] = Wrapper.forPrimitiveType(ptype).convert(values[i], ptype);
2805             }
2806         }
2807 
2808         return new Transformers.InsertArguments(target, pos, values);
2809     }
2810 
2811     // Android-changed: insertArgumentPrimitive is unused.
2812     //
2813     // private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
2814     //                                                          Class<?> ptype, Object value) {
2815     //     Wrapper w = Wrapper.forPrimitiveType(ptype);
2816     //     // perform unboxing and/or primitive conversion
2817     //     value = w.convert(value, ptype);
2818     //     switch (w) {
2819     //     case INT:     return result.bindArgumentI(pos, (int)value);
2820     //     case LONG:    return result.bindArgumentJ(pos, (long)value);
2821     //     case FLOAT:   return result.bindArgumentF(pos, (float)value);
2822     //     case DOUBLE:  return result.bindArgumentD(pos, (double)value);
2823     //     default:      return result.bindArgumentI(pos, ValueConversions.widenSubword(value));
2824     //     }
2825     // }
2826 
insertArgumentsChecks(MethodHandle target, int insCount, int pos)2827     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
2828         MethodType oldType = target.type();
2829         int outargs = oldType.parameterCount();
2830         int inargs  = outargs - insCount;
2831         if (inargs < 0)
2832             throw newIllegalArgumentException("too many values to insert");
2833         if (pos < 0 || pos > inargs)
2834             throw newIllegalArgumentException("no argument type to append");
2835         return oldType.ptypes();
2836     }
2837 
2838     /**
2839      * Produces a method handle which will discard some dummy arguments
2840      * before calling some other specified <i>target</i> method handle.
2841      * The type of the new method handle will be the same as the target's type,
2842      * except it will also include the dummy argument types,
2843      * at some given position.
2844      * <p>
2845      * The {@code pos} argument may range between zero and <i>N</i>,
2846      * where <i>N</i> is the arity of the target.
2847      * If {@code pos} is zero, the dummy arguments will precede
2848      * the target's real arguments; if {@code pos} is <i>N</i>
2849      * they will come after.
2850      * <p>
2851      * <b>Example:</b>
2852      * <blockquote><pre>{@code
2853 import static java.lang.invoke.MethodHandles.*;
2854 import static java.lang.invoke.MethodType.*;
2855 ...
2856 MethodHandle cat = lookup().findVirtual(String.class,
2857   "concat", methodType(String.class, String.class));
2858 assertEquals("xy", (String) cat.invokeExact("x", "y"));
2859 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
2860 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
2861 assertEquals(bigType, d0.type());
2862 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
2863      * }</pre></blockquote>
2864      * <p>
2865      * This method is also equivalent to the following code:
2866      * <blockquote><pre>
2867      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
2868      * </pre></blockquote>
2869      * @param target the method handle to invoke after the arguments are dropped
2870      * @param valueTypes the type(s) of the argument(s) to drop
2871      * @param pos position of first argument to drop (zero for the leftmost)
2872      * @return a method handle which drops arguments of the given types,
2873      *         before calling the original method handle
2874      * @throws NullPointerException if the target is null,
2875      *                              or if the {@code valueTypes} list or any of its elements is null
2876      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
2877      *                  or if {@code pos} is negative or greater than the arity of the target,
2878      *                  or if the new method handle's type would have too many parameters
2879      */
2880     public static
dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes)2881     MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
2882         valueTypes = copyTypes(valueTypes);
2883         MethodType oldType = target.type();  // get NPE
2884         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
2885 
2886         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
2887         if (dropped == 0) {
2888             return target;
2889         }
2890 
2891         return new Transformers.DropArguments(newType, target, pos, valueTypes.size());
2892     }
2893 
copyTypes(List<Class<?>> types)2894     private static List<Class<?>> copyTypes(List<Class<?>> types) {
2895         Object[] a = types.toArray();
2896         return Arrays.asList(Arrays.copyOf(a, a.length, Class[].class));
2897     }
2898 
dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes)2899     private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
2900         int dropped = valueTypes.size();
2901         MethodType.checkSlotCount(dropped);
2902         int outargs = oldType.parameterCount();
2903         int inargs  = outargs + dropped;
2904         if (pos < 0 || pos > outargs)
2905             throw newIllegalArgumentException("no argument type to remove"
2906                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
2907                     );
2908         return dropped;
2909     }
2910 
2911     /**
2912      * Produces a method handle which will discard some dummy arguments
2913      * before calling some other specified <i>target</i> method handle.
2914      * The type of the new method handle will be the same as the target's type,
2915      * except it will also include the dummy argument types,
2916      * at some given position.
2917      * <p>
2918      * The {@code pos} argument may range between zero and <i>N</i>,
2919      * where <i>N</i> is the arity of the target.
2920      * If {@code pos} is zero, the dummy arguments will precede
2921      * the target's real arguments; if {@code pos} is <i>N</i>
2922      * they will come after.
2923      * <p>
2924      * <b>Example:</b>
2925      * <blockquote><pre>{@code
2926 import static java.lang.invoke.MethodHandles.*;
2927 import static java.lang.invoke.MethodType.*;
2928 ...
2929 MethodHandle cat = lookup().findVirtual(String.class,
2930   "concat", methodType(String.class, String.class));
2931 assertEquals("xy", (String) cat.invokeExact("x", "y"));
2932 MethodHandle d0 = dropArguments(cat, 0, String.class);
2933 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
2934 MethodHandle d1 = dropArguments(cat, 1, String.class);
2935 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
2936 MethodHandle d2 = dropArguments(cat, 2, String.class);
2937 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
2938 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
2939 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
2940      * }</pre></blockquote>
2941      * <p>
2942      * This method is also equivalent to the following code:
2943      * <blockquote><pre>
2944      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
2945      * </pre></blockquote>
2946      * @param target the method handle to invoke after the arguments are dropped
2947      * @param valueTypes the type(s) of the argument(s) to drop
2948      * @param pos position of first argument to drop (zero for the leftmost)
2949      * @return a method handle which drops arguments of the given types,
2950      *         before calling the original method handle
2951      * @throws NullPointerException if the target is null,
2952      *                              or if the {@code valueTypes} array or any of its elements is null
2953      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
2954      *                  or if {@code pos} is negative or greater than the arity of the target,
2955      *                  or if the new method handle's type would have
2956      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
2957      */
2958     public static
dropArguments(MethodHandle target, int pos, Class<?>... valueTypes)2959     MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
2960         return dropArguments(target, pos, Arrays.asList(valueTypes));
2961     }
2962 
2963     /**
2964      * Adapts a target method handle by pre-processing
2965      * one or more of its arguments, each with its own unary filter function,
2966      * and then calling the target with each pre-processed argument
2967      * replaced by the result of its corresponding filter function.
2968      * <p>
2969      * The pre-processing is performed by one or more method handles,
2970      * specified in the elements of the {@code filters} array.
2971      * The first element of the filter array corresponds to the {@code pos}
2972      * argument of the target, and so on in sequence.
2973      * <p>
2974      * Null arguments in the array are treated as identity functions,
2975      * and the corresponding arguments left unchanged.
2976      * (If there are no non-null elements in the array, the original target is returned.)
2977      * Each filter is applied to the corresponding argument of the adapter.
2978      * <p>
2979      * If a filter {@code F} applies to the {@code N}th argument of
2980      * the target, then {@code F} must be a method handle which
2981      * takes exactly one argument.  The type of {@code F}'s sole argument
2982      * replaces the corresponding argument type of the target
2983      * in the resulting adapted method handle.
2984      * The return type of {@code F} must be identical to the corresponding
2985      * parameter type of the target.
2986      * <p>
2987      * It is an error if there are elements of {@code filters}
2988      * (null or not)
2989      * which do not correspond to argument positions in the target.
2990      * <p><b>Example:</b>
2991      * <blockquote><pre>{@code
2992 import static java.lang.invoke.MethodHandles.*;
2993 import static java.lang.invoke.MethodType.*;
2994 ...
2995 MethodHandle cat = lookup().findVirtual(String.class,
2996   "concat", methodType(String.class, String.class));
2997 MethodHandle upcase = lookup().findVirtual(String.class,
2998   "toUpperCase", methodType(String.class));
2999 assertEquals("xy", (String) cat.invokeExact("x", "y"));
3000 MethodHandle f0 = filterArguments(cat, 0, upcase);
3001 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
3002 MethodHandle f1 = filterArguments(cat, 1, upcase);
3003 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
3004 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
3005 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
3006      * }</pre></blockquote>
3007      * <p> Here is pseudocode for the resulting adapter:
3008      * <blockquote><pre>{@code
3009      * V target(P... p, A[i]... a[i], B... b);
3010      * A[i] filter[i](V[i]);
3011      * T adapter(P... p, V[i]... v[i], B... b) {
3012      *   return target(p..., f[i](v[i])..., b...);
3013      * }
3014      * }</pre></blockquote>
3015      *
3016      * @param target the method handle to invoke after arguments are filtered
3017      * @param pos the position of the first argument to filter
3018      * @param filters method handles to call initially on filtered arguments
3019      * @return method handle which incorporates the specified argument filtering logic
3020      * @throws NullPointerException if the target is null
3021      *                              or if the {@code filters} array is null
3022      * @throws IllegalArgumentException if a non-null element of {@code filters}
3023      *          does not match a corresponding argument type of target as described above,
3024      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
3025      *          or if the resulting method handle's type would have
3026      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
3027      */
3028     public static
filterArguments(MethodHandle target, int pos, MethodHandle... filters)3029     MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
3030         filterArgumentsCheckArity(target, pos, filters);
3031 
3032         for (int i = 0; i < filters.length; ++i) {
3033             filterArgumentChecks(target, i + pos, filters[i]);
3034         }
3035 
3036         return new Transformers.FilterArguments(target, pos, filters);
3037     }
3038 
filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters)3039     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
3040         MethodType targetType = target.type();
3041         int maxPos = targetType.parameterCount();
3042         if (pos + filters.length > maxPos)
3043             throw newIllegalArgumentException("too many filters");
3044     }
3045 
filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter)3046     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
3047         MethodType targetType = target.type();
3048         MethodType filterType = filter.type();
3049         if (filterType.parameterCount() != 1
3050             || filterType.returnType() != targetType.parameterType(pos))
3051             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3052     }
3053 
3054     /**
3055      * Adapts a target method handle by pre-processing
3056      * a sub-sequence of its arguments with a filter (another method handle).
3057      * The pre-processed arguments are replaced by the result (if any) of the
3058      * filter function.
3059      * The target is then called on the modified (usually shortened) argument list.
3060      * <p>
3061      * If the filter returns a value, the target must accept that value as
3062      * its argument in position {@code pos}, preceded and/or followed by
3063      * any arguments not passed to the filter.
3064      * If the filter returns void, the target must accept all arguments
3065      * not passed to the filter.
3066      * No arguments are reordered, and a result returned from the filter
3067      * replaces (in order) the whole subsequence of arguments originally
3068      * passed to the adapter.
3069      * <p>
3070      * The argument types (if any) of the filter
3071      * replace zero or one argument types of the target, at position {@code pos},
3072      * in the resulting adapted method handle.
3073      * The return type of the filter (if any) must be identical to the
3074      * argument type of the target at position {@code pos}, and that target argument
3075      * is supplied by the return value of the filter.
3076      * <p>
3077      * In all cases, {@code pos} must be greater than or equal to zero, and
3078      * {@code pos} must also be less than or equal to the target's arity.
3079      * <p><b>Example:</b>
3080      * <blockquote><pre>{@code
3081 import static java.lang.invoke.MethodHandles.*;
3082 import static java.lang.invoke.MethodType.*;
3083 ...
3084 MethodHandle deepToString = publicLookup()
3085   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
3086 
3087 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
3088 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
3089 
3090 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
3091 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
3092 
3093 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
3094 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
3095 assertEquals("[top, [up, down], strange]",
3096              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
3097 
3098 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
3099 assertEquals("[top, [up, down], [strange]]",
3100              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
3101 
3102 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
3103 assertEquals("[top, [[up, down, strange], charm], bottom]",
3104              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
3105      * }</pre></blockquote>
3106      * <p> Here is pseudocode for the resulting adapter:
3107      * <blockquote><pre>{@code
3108      * T target(A...,V,C...);
3109      * V filter(B...);
3110      * T adapter(A... a,B... b,C... c) {
3111      *   V v = filter(b...);
3112      *   return target(a...,v,c...);
3113      * }
3114      * // and if the filter has no arguments:
3115      * T target2(A...,V,C...);
3116      * V filter2();
3117      * T adapter2(A... a,C... c) {
3118      *   V v = filter2();
3119      *   return target2(a...,v,c...);
3120      * }
3121      * // and if the filter has a void return:
3122      * T target3(A...,C...);
3123      * void filter3(B...);
3124      * void adapter3(A... a,B... b,C... c) {
3125      *   filter3(b...);
3126      *   return target3(a...,c...);
3127      * }
3128      * }</pre></blockquote>
3129      * <p>
3130      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
3131      * one which first "folds" the affected arguments, and then drops them, in separate
3132      * steps as follows:
3133      * <blockquote><pre>{@code
3134      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
3135      * mh = MethodHandles.foldArguments(mh, coll); //step 1
3136      * }</pre></blockquote>
3137      * If the target method handle consumes no arguments besides than the result
3138      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
3139      * is equivalent to {@code filterReturnValue(coll, mh)}.
3140      * If the filter method handle {@code coll} consumes one argument and produces
3141      * a non-void result, then {@code collectArguments(mh, N, coll)}
3142      * is equivalent to {@code filterArguments(mh, N, coll)}.
3143      * Other equivalences are possible but would require argument permutation.
3144      *
3145      * @param target the method handle to invoke after filtering the subsequence of arguments
3146      * @param pos the position of the first adapter argument to pass to the filter,
3147      *            and/or the target argument which receives the result of the filter
3148      * @param filter method handle to call on the subsequence of arguments
3149      * @return method handle which incorporates the specified argument subsequence filtering logic
3150      * @throws NullPointerException if either argument is null
3151      * @throws IllegalArgumentException if the return type of {@code filter}
3152      *          is non-void and is not the same as the {@code pos} argument of the target,
3153      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
3154      *          or if the resulting method handle's type would have
3155      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
3156      * @see MethodHandles#foldArguments
3157      * @see MethodHandles#filterArguments
3158      * @see MethodHandles#filterReturnValue
3159      */
3160     public static
collectArguments(MethodHandle target, int pos, MethodHandle filter)3161     MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
3162         MethodType newType = collectArgumentsChecks(target, pos, filter);
3163         return new Transformers.CollectArguments(target, filter, pos, newType);
3164     }
3165 
collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter)3166     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
3167         MethodType targetType = target.type();
3168         MethodType filterType = filter.type();
3169         Class<?> rtype = filterType.returnType();
3170         List<Class<?>> filterArgs = filterType.parameterList();
3171         if (rtype == void.class) {
3172             return targetType.insertParameterTypes(pos, filterArgs);
3173         }
3174         if (rtype != targetType.parameterType(pos)) {
3175             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3176         }
3177         return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
3178     }
3179 
3180     /**
3181      * Adapts a target method handle by post-processing
3182      * its return value (if any) with a filter (another method handle).
3183      * The result of the filter is returned from the adapter.
3184      * <p>
3185      * If the target returns a value, the filter must accept that value as
3186      * its only argument.
3187      * If the target returns void, the filter must accept no arguments.
3188      * <p>
3189      * The return type of the filter
3190      * replaces the return type of the target
3191      * in the resulting adapted method handle.
3192      * The argument type of the filter (if any) must be identical to the
3193      * return type of the target.
3194      * <p><b>Example:</b>
3195      * <blockquote><pre>{@code
3196 import static java.lang.invoke.MethodHandles.*;
3197 import static java.lang.invoke.MethodType.*;
3198 ...
3199 MethodHandle cat = lookup().findVirtual(String.class,
3200   "concat", methodType(String.class, String.class));
3201 MethodHandle length = lookup().findVirtual(String.class,
3202   "length", methodType(int.class));
3203 System.out.println((String) cat.invokeExact("x", "y")); // xy
3204 MethodHandle f0 = filterReturnValue(cat, length);
3205 System.out.println((int) f0.invokeExact("x", "y")); // 2
3206      * }</pre></blockquote>
3207      * <p> Here is pseudocode for the resulting adapter:
3208      * <blockquote><pre>{@code
3209      * V target(A...);
3210      * T filter(V);
3211      * T adapter(A... a) {
3212      *   V v = target(a...);
3213      *   return filter(v);
3214      * }
3215      * // and if the target has a void return:
3216      * void target2(A...);
3217      * T filter2();
3218      * T adapter2(A... a) {
3219      *   target2(a...);
3220      *   return filter2();
3221      * }
3222      * // and if the filter has a void return:
3223      * V target3(A...);
3224      * void filter3(V);
3225      * void adapter3(A... a) {
3226      *   V v = target3(a...);
3227      *   filter3(v);
3228      * }
3229      * }</pre></blockquote>
3230      * @param target the method handle to invoke before filtering the return value
3231      * @param filter method handle to call on the return value
3232      * @return method handle which incorporates the specified return value filtering logic
3233      * @throws NullPointerException if either argument is null
3234      * @throws IllegalArgumentException if the argument list of {@code filter}
3235      *          does not match the return type of target as described above
3236      */
3237     public static
filterReturnValue(MethodHandle target, MethodHandle filter)3238     MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
3239         MethodType targetType = target.type();
3240         MethodType filterType = filter.type();
3241         filterReturnValueChecks(targetType, filterType);
3242 
3243         return new Transformers.FilterReturnValue(target, filter);
3244     }
3245 
filterReturnValueChecks(MethodType targetType, MethodType filterType)3246     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
3247         Class<?> rtype = targetType.returnType();
3248         int filterValues = filterType.parameterCount();
3249         if (filterValues == 0
3250                 ? (rtype != void.class)
3251                 : (rtype != filterType.parameterType(0) || filterValues != 1))
3252             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3253     }
3254 
3255     /**
3256      * Adapts a target method handle by pre-processing
3257      * some of its arguments, and then calling the target with
3258      * the result of the pre-processing, inserted into the original
3259      * sequence of arguments.
3260      * <p>
3261      * The pre-processing is performed by {@code combiner}, a second method handle.
3262      * Of the arguments passed to the adapter, the first {@code N} arguments
3263      * are copied to the combiner, which is then called.
3264      * (Here, {@code N} is defined as the parameter count of the combiner.)
3265      * After this, control passes to the target, with any result
3266      * from the combiner inserted before the original {@code N} incoming
3267      * arguments.
3268      * <p>
3269      * If the combiner returns a value, the first parameter type of the target
3270      * must be identical with the return type of the combiner, and the next
3271      * {@code N} parameter types of the target must exactly match the parameters
3272      * of the combiner.
3273      * <p>
3274      * If the combiner has a void return, no result will be inserted,
3275      * and the first {@code N} parameter types of the target
3276      * must exactly match the parameters of the combiner.
3277      * <p>
3278      * The resulting adapter is the same type as the target, except that the
3279      * first parameter type is dropped,
3280      * if it corresponds to the result of the combiner.
3281      * <p>
3282      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
3283      * that either the combiner or the target does not wish to receive.
3284      * If some of the incoming arguments are destined only for the combiner,
3285      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
3286      * arguments will not need to be live on the stack on entry to the
3287      * target.)
3288      * <p><b>Example:</b>
3289      * <blockquote><pre>{@code
3290 import static java.lang.invoke.MethodHandles.*;
3291 import static java.lang.invoke.MethodType.*;
3292 ...
3293 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
3294   "println", methodType(void.class, String.class))
3295     .bindTo(System.out);
3296 MethodHandle cat = lookup().findVirtual(String.class,
3297   "concat", methodType(String.class, String.class));
3298 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
3299 MethodHandle catTrace = foldArguments(cat, trace);
3300 // also prints "boo":
3301 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
3302      * }</pre></blockquote>
3303      * <p> Here is pseudocode for the resulting adapter:
3304      * <blockquote><pre>{@code
3305      * // there are N arguments in A...
3306      * T target(V, A[N]..., B...);
3307      * V combiner(A...);
3308      * T adapter(A... a, B... b) {
3309      *   V v = combiner(a...);
3310      *   return target(v, a..., b...);
3311      * }
3312      * // and if the combiner has a void return:
3313      * T target2(A[N]..., B...);
3314      * void combiner2(A...);
3315      * T adapter2(A... a, B... b) {
3316      *   combiner2(a...);
3317      *   return target2(a..., b...);
3318      * }
3319      * }</pre></blockquote>
3320      * @param target the method handle to invoke after arguments are combined
3321      * @param combiner method handle to call initially on the incoming arguments
3322      * @return method handle which incorporates the specified argument folding logic
3323      * @throws NullPointerException if either argument is null
3324      * @throws IllegalArgumentException if {@code combiner}'s return type
3325      *          is non-void and not the same as the first argument type of
3326      *          the target, or if the initial {@code N} argument types
3327      *          of the target
3328      *          (skipping one matching the {@code combiner}'s return type)
3329      *          are not identical with the argument types of {@code combiner}
3330      */
3331     public static
foldArguments(MethodHandle target, MethodHandle combiner)3332     MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
3333         int foldPos = 0;
3334         MethodType targetType = target.type();
3335         MethodType combinerType = combiner.type();
3336         Class<?> rtype = foldArgumentChecks(foldPos, targetType, combinerType);
3337 
3338         return new Transformers.FoldArguments(target, combiner);
3339     }
3340 
foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType)3341     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
3342         int foldArgs   = combinerType.parameterCount();
3343         Class<?> rtype = combinerType.returnType();
3344         int foldVals = rtype == void.class ? 0 : 1;
3345         int afterInsertPos = foldPos + foldVals;
3346         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
3347         if (ok && !(combinerType.parameterList()
3348                     .equals(targetType.parameterList().subList(afterInsertPos,
3349                                                                afterInsertPos + foldArgs))))
3350             ok = false;
3351         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(0))
3352             ok = false;
3353         if (!ok)
3354             throw misMatchedTypes("target and combiner types", targetType, combinerType);
3355         return rtype;
3356     }
3357 
3358     /**
3359      * Makes a method handle which adapts a target method handle,
3360      * by guarding it with a test, a boolean-valued method handle.
3361      * If the guard fails, a fallback handle is called instead.
3362      * All three method handles must have the same corresponding
3363      * argument and return types, except that the return type
3364      * of the test must be boolean, and the test is allowed
3365      * to have fewer arguments than the other two method handles.
3366      * <p> Here is pseudocode for the resulting adapter:
3367      * <blockquote><pre>{@code
3368      * boolean test(A...);
3369      * T target(A...,B...);
3370      * T fallback(A...,B...);
3371      * T adapter(A... a,B... b) {
3372      *   if (test(a...))
3373      *     return target(a..., b...);
3374      *   else
3375      *     return fallback(a..., b...);
3376      * }
3377      * }</pre></blockquote>
3378      * Note that the test arguments ({@code a...} in the pseudocode) cannot
3379      * be modified by execution of the test, and so are passed unchanged
3380      * from the caller to the target or fallback as appropriate.
3381      * @param test method handle used for test, must return boolean
3382      * @param target method handle to call if test passes
3383      * @param fallback method handle to call if test fails
3384      * @return method handle which incorporates the specified if/then/else logic
3385      * @throws NullPointerException if any argument is null
3386      * @throws IllegalArgumentException if {@code test} does not return boolean,
3387      *          or if all three method types do not match (with the return
3388      *          type of {@code test} changed to match that of the target).
3389      */
3390     public static
guardWithTest(MethodHandle test, MethodHandle target, MethodHandle fallback)3391     MethodHandle guardWithTest(MethodHandle test,
3392                                MethodHandle target,
3393                                MethodHandle fallback) {
3394         MethodType gtype = test.type();
3395         MethodType ttype = target.type();
3396         MethodType ftype = fallback.type();
3397         if (!ttype.equals(ftype))
3398             throw misMatchedTypes("target and fallback types", ttype, ftype);
3399         if (gtype.returnType() != boolean.class)
3400             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
3401         List<Class<?>> targs = ttype.parameterList();
3402         List<Class<?>> gargs = gtype.parameterList();
3403         if (!targs.equals(gargs)) {
3404             int gpc = gargs.size(), tpc = targs.size();
3405             if (gpc >= tpc || !targs.subList(0, gpc).equals(gargs))
3406                 throw misMatchedTypes("target and test types", ttype, gtype);
3407             test = dropArguments(test, gpc, targs.subList(gpc, tpc));
3408             gtype = test.type();
3409         }
3410 
3411         return new Transformers.GuardWithTest(test, target, fallback);
3412     }
3413 
misMatchedTypes(String what, MethodType t1, MethodType t2)3414     static RuntimeException misMatchedTypes(String what, MethodType t1, MethodType t2) {
3415         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
3416     }
3417 
3418     /**
3419      * Makes a method handle which adapts a target method handle,
3420      * by running it inside an exception handler.
3421      * If the target returns normally, the adapter returns that value.
3422      * If an exception matching the specified type is thrown, the fallback
3423      * handle is called instead on the exception, plus the original arguments.
3424      * <p>
3425      * The target and handler must have the same corresponding
3426      * argument and return types, except that handler may omit trailing arguments
3427      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
3428      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
3429      * <p> Here is pseudocode for the resulting adapter:
3430      * <blockquote><pre>{@code
3431      * T target(A..., B...);
3432      * T handler(ExType, A...);
3433      * T adapter(A... a, B... b) {
3434      *   try {
3435      *     return target(a..., b...);
3436      *   } catch (ExType ex) {
3437      *     return handler(ex, a...);
3438      *   }
3439      * }
3440      * }</pre></blockquote>
3441      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
3442      * be modified by execution of the target, and so are passed unchanged
3443      * from the caller to the handler, if the handler is invoked.
3444      * <p>
3445      * The target and handler must return the same type, even if the handler
3446      * always throws.  (This might happen, for instance, because the handler
3447      * is simulating a {@code finally} clause).
3448      * To create such a throwing handler, compose the handler creation logic
3449      * with {@link #throwException throwException},
3450      * in order to create a method handle of the correct return type.
3451      * @param target method handle to call
3452      * @param exType the type of exception which the handler will catch
3453      * @param handler method handle to call if a matching exception is thrown
3454      * @return method handle which incorporates the specified try/catch logic
3455      * @throws NullPointerException if any argument is null
3456      * @throws IllegalArgumentException if {@code handler} does not accept
3457      *          the given exception type, or if the method handle types do
3458      *          not match in their return types and their
3459      *          corresponding parameters
3460      */
3461     public static
catchException(MethodHandle target, Class<? extends Throwable> exType, MethodHandle handler)3462     MethodHandle catchException(MethodHandle target,
3463                                 Class<? extends Throwable> exType,
3464                                 MethodHandle handler) {
3465         MethodType ttype = target.type();
3466         MethodType htype = handler.type();
3467         if (htype.parameterCount() < 1 ||
3468             !htype.parameterType(0).isAssignableFrom(exType))
3469             throw newIllegalArgumentException("handler does not accept exception type "+exType);
3470         if (htype.returnType() != ttype.returnType())
3471             throw misMatchedTypes("target and handler return types", ttype, htype);
3472         List<Class<?>> targs = ttype.parameterList();
3473         List<Class<?>> hargs = htype.parameterList();
3474         hargs = hargs.subList(1, hargs.size());  // omit leading parameter from handler
3475         if (!targs.equals(hargs)) {
3476             int hpc = hargs.size(), tpc = targs.size();
3477             if (hpc >= tpc || !targs.subList(0, hpc).equals(hargs))
3478                 throw misMatchedTypes("target and handler types", ttype, htype);
3479         }
3480 
3481         return new Transformers.CatchException(target, handler, exType);
3482     }
3483 
3484     /**
3485      * Produces a method handle which will throw exceptions of the given {@code exType}.
3486      * The method handle will accept a single argument of {@code exType},
3487      * and immediately throw it as an exception.
3488      * The method type will nominally specify a return of {@code returnType}.
3489      * The return type may be anything convenient:  It doesn't matter to the
3490      * method handle's behavior, since it will never return normally.
3491      * @param returnType the return type of the desired method handle
3492      * @param exType the parameter type of the desired method handle
3493      * @return method handle which can throw the given exceptions
3494      * @throws NullPointerException if either argument is null
3495      */
3496     public static
throwException(Class<?> returnType, Class<? extends Throwable> exType)3497     MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
3498         if (!Throwable.class.isAssignableFrom(exType))
3499             throw new ClassCastException(exType.getName());
3500 
3501         return new Transformers.AlwaysThrow(returnType, exType);
3502     }
3503 }
3504