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