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