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