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.security.AccessController;
  30 import java.security.PrivilegedAction;
  31 import java.util.List;
  32 import java.util.ArrayList;
  33 import java.util.Arrays;
  34 
  35 import sun.invoke.util.ValueConversions;
  36 import sun.invoke.util.VerifyAccess;
  37 import sun.invoke.util.Wrapper;
  38 import sun.reflect.CallerSensitive;
  39 import sun.reflect.Reflection;
  40 import sun.reflect.misc.ReflectUtil;
  41 import sun.security.util.SecurityConstants;
  42 import static java.lang.invoke.MethodHandleStatics.*;
  43 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  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  * <li>Wrapper methods which can convert between method handles and interface types.
  53  * </ul>
  54  * <p>
  55  * @author John Rose, JSR 292 EG
  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} on the caller,
  69      * which has the capability to access any method handle that the caller has access to,
  70      * including direct method handles to private fields and methods.
  71      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
  72      * Do not store it in place where untrusted code can access it.
  73      * @return a lookup object for the caller of this method
  74      */
  75     @CallerSensitive
  76     public static Lookup lookup() {
  77         return new Lookup(Reflection.getCallerClass());
  78     }
  79 
  80     /**
  81      * Returns a {@link Lookup lookup object} which is trusted minimally.
  82      * It can only be used to create method handles to
  83      * publicly accessible fields and methods.
  84      * <p>
  85      * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class}
  86      * of this lookup object will be {@link java.lang.Object}.
  87      * <p>
  88      * The lookup class can be changed to any other class {@code C} using an expression of the form
  89      * {@linkplain Lookup#in <code>publicLookup().in(C.class)</code>}.
  90      * Since all classes have equal access to public names,
  91      * such a change would confer no new access rights.
  92      * @return a lookup object which is trusted minimally
  93      */
  94     public static Lookup publicLookup() {
  95         return Lookup.PUBLIC_LOOKUP;
  96     }
  97 
  98     /**
  99      * A <em>lookup object</em> is a factory for creating method handles,
 100      * when the creation requires access checking.
 101      * Method handles do not perform
 102      * access checks when they are called, but rather when they are created.
 103      * Therefore, method handle access
 104      * restrictions must be enforced when a method handle is created.
 105      * The caller class against which those restrictions are enforced
 106      * is known as the {@linkplain #lookupClass lookup class}.
 107      * <p>
 108      * A lookup class which needs to create method handles will call
 109      * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself.
 110      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 111      * determined, and securely stored in the {@code Lookup} object.
 112      * The lookup class (or its delegates) may then use factory methods
 113      * on the {@code Lookup} object to create method handles for access-checked members.
 114      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 115      * even private ones.
 116      *
 117      * <h1><a name="lookups"></a>Lookup Factory Methods</h1>
 118      * The factory methods on a {@code Lookup} object correspond to all major
 119      * use cases for methods, constructors, and fields.
 120      * Here is a summary of the correspondence between these factory methods and
 121      * the behavior the resulting method handles:
 122      * <table border=1 cellpadding=5 summary="lookup method behaviors">
 123      * <tr><th>lookup expression</th><th>member</th><th>behavior</th></tr>
 124      * <tr>
 125      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td>
 126      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 127      * </tr>
 128      * <tr>
 129      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td>
 130      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
 131      * </tr>
 132      * <tr>
 133      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td>
 134      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 135      * </tr>
 136      * <tr>
 137      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td>
 138      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 139      * </tr>
 140      * <tr>
 141      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td>
 142      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 143      * </tr>
 144      * <tr>
 145      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td>
 146      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 147      * </tr>
 148      * <tr>
 149      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td>
 150      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 151      * </tr>
 152      * <tr>
 153      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td>
 154      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 155      * </tr>
 156      * <tr>
 157      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td>
 158      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 159      * </tr>
 160      * <tr>
 161      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td>
 162      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 163      * </tr>
 164      * <tr>
 165      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
 166      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 167      * </tr>
 168      * <tr>
 169      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td>
 170      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 171      * </tr>
 172      * <tr>
 173      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
 174      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 175      * </tr>
 176      * </table>
 177      *
 178      * Here, the type {@code C} is the class or interface being searched for a member,
 179      * documented as a parameter named {@code refc} in the lookup methods.
 180      * The method type {@code MT} is composed from the return type {@code T}
 181      * and the sequence of argument types {@code A*}.
 182      * The constructor also has a sequence of argument types {@code A*} and
 183      * is deemed to return the newly-created object of type {@code C}.
 184      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 185      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 186      * if it is present, it is always the leading argument to the method handle invocation.
 187      * (In the case of some {@code protected} members, {@code this} may be
 188      * restricted in type to the lookup class; see below.)
 189      * The name {@code arg} stands for all the other method handle arguments.
 190      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 191      * stands for a null reference if the accessed method or field is static,
 192      * and {@code this} otherwise.
 193      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 194      * for reflective objects corresponding to the given members.
 195      * <p>
 196      * In cases where the given member is of variable arity (i.e., a method or constructor)
 197      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 198      * In all other cases, the returned method handle will be of fixed arity.
 199      * <p>
 200      * The equivalence between looked-up method handles and underlying
 201      * class members can break down in a few ways:
 202      * <ul>
 203      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 204      * the lookup can still succeed, even when there is no equivalent
 205      * Java expression or bytecoded constant.
 206      * <li>Likewise, if {@code T} or {@code MT}
 207      * is not symbolically accessible from the lookup class's loader,
 208      * the lookup can still succeed.
 209      * For example, lookups for {@code MethodHandle.invokeExact} and
 210      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 211      * <li>If there is a security manager installed, it can forbid the lookup
 212      * on various grounds (<a href="#secmgr">see below</a>).
 213      * By contrast, the {@code ldc} instruction is not subject to
 214      * security manager checks.
 215      * </ul>
 216      *
 217      * <h1><a name="access"></a>Access checking</h1>
 218      * Access checks are applied in the factory methods of {@code Lookup},
 219      * when a method handle is created.
 220      * This is a key difference from the Core Reflection API, since
 221      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 222      * performs access checking against every caller, on every call.
 223      * <p>
 224      * All access checks start from a {@code Lookup} object, which
 225      * compares its recorded lookup class against all requests to
 226      * create method handles.
 227      * A single {@code Lookup} object can be used to create any number
 228      * of access-checked method handles, all checked against a single
 229      * lookup class.
 230      * <p>
 231      * A {@code Lookup} object can be shared with other trusted code,
 232      * such as a metaobject protocol.
 233      * A shared {@code Lookup} object delegates the capability
 234      * to create method handles on private members of the lookup class.
 235      * Even if privileged code uses the {@code Lookup} object,
 236      * the access checking is confined to the privileges of the
 237      * original lookup class.
 238      * <p>
 239      * A lookup can fail, because
 240      * the containing class is not accessible to the lookup class, or
 241      * because the desired class member is missing, or because the
 242      * desired class member is not accessible to the lookup class.
 243      * In any of these cases, a {@code ReflectiveOperationException} will be
 244      * thrown from the attempted lookup.  The exact class will be one of
 245      * the following:
 246      * <ul>
 247      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 248      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 249      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 250      * </ul>
 251      * <p>
 252      * In general, the conditions under which a method handle may be
 253      * looked up for a method {@code M} are exactly equivalent to the conditions
 254      * under which the lookup class could have compiled and resolved a call to {@code M}.
 255      * And the effect of invoking the method handle resulting from the lookup
 256      * is exactly equivalent to executing the compiled and resolved call to {@code M}.
 257      * The same point is true of fields and constructors.
 258      * <p>
 259      * If the desired member is {@code protected}, the usual JVM rules apply,
 260      * including the requirement that the lookup class must be either be in the
 261      * same package as the desired member, or must inherit that member.
 262      * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.)
 263      * In addition, if the desired member is a non-static field or method
 264      * in a different package, the resulting method handle may only be applied
 265      * to objects of the lookup class or one of its subclasses.
 266      * This requirement is enforced by narrowing the type of the leading
 267      * {@code this} parameter from {@code C}
 268      * (which will necessarily be a superclass of the lookup class)
 269      * to the lookup class itself.
 270      * <p>
 271      * In some cases, access between nested classes is obtained by the Java compiler by creating
 272      * an wrapper method to access a private method of another class
 273      * in the same top-level declaration.
 274      * For example, a nested class {@code C.D}
 275      * can access private members within other related classes such as
 276      * {@code C}, {@code C.D.E}, or {@code C.B},
 277      * but the Java compiler may need to generate wrapper methods in
 278      * those related classes.  In such cases, a {@code Lookup} object on
 279      * {@code C.E} would be unable to those private members.
 280      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 281      * which can transform a lookup on {@code C.E} into one on any of those other
 282      * classes, without special elevation of privilege.
 283      * <p>
 284      * Although bytecode instructions can only refer to classes in
 285      * a related class loader, this API can search for methods in any
 286      * class, as long as a reference to its {@code Class} object is
 287      * available.  Such cross-loader references are also possible with the
 288      * Core Reflection API, and are impossible to bytecode instructions
 289      * such as {@code invokestatic} or {@code getfield}.
 290      * There is a {@linkplain java.lang.SecurityManager security manager API}
 291      * to allow applications to check such cross-loader references.
 292      * These checks apply to both the {@code MethodHandles.Lookup} API
 293      * and the Core Reflection API
 294      * (as found on {@link java.lang.Class Class}).
 295      * <p>
 296      * Access checks only apply to named and reflected methods,
 297      * constructors, and fields.
 298      * Other method handle creation methods, such as
 299      * {@link MethodHandle#asType MethodHandle.asType},
 300      * do not require any access checks, and are done
 301      * with static methods of {@link MethodHandles},
 302      * independently of any {@code Lookup} object.
 303      *
 304      * <h1>Security manager interactions</h1>
 305      * <a name="secmgr"></a>
 306      * If a security manager is present, member lookups are subject to
 307      * additional checks.
 308      * From one to four calls are made to the security manager.
 309      * Any of these calls can refuse access by throwing a
 310      * {@link java.lang.SecurityException SecurityException}.
 311      * Define {@code smgr} as the security manager,
 312      * {@code refc} as the containing class in which the member
 313      * is being sought, and {@code defc} as the class in which the
 314      * member is actually defined.
 315      * The calls are made according to the following rules:
 316      * <ul>
 317      * <li>In all cases, {@link SecurityManager#checkMemberAccess
 318      *     smgr.checkMemberAccess(refc, Member.PUBLIC)} is called.
 319      * <li>If the class loader of the lookup class is not
 320      *     the same as or an ancestor of the class loader of {@code refc},
 321      *     then {@link SecurityManager#checkPackageAccess
 322      *     smgr.checkPackageAccess(refcPkg)} is called,
 323      *     where {@code refcPkg} is the package of {@code refc}.
 324      * <li>If the retrieved member is not public,
 325      *     {@link SecurityManager#checkMemberAccess
 326      *     smgr.checkMemberAccess(defc, Member.DECLARED)} is called.
 327      *     (Note that {@code defc} might be the same as {@code refc}.)
 328      *     The default implementation of this security manager method
 329      *     inspects the stack to determine the original caller of
 330      *     the reflective request (such as {@code findStatic}),
 331      *     and performs additional permission checks if the
 332      *     class loader of {@code defc} differs from the class
 333      *     loader of the class from which the reflective request came.
 334      * <li>If the retrieved member is not public,
 335      *     and if {@code defc} and {@code refc} are in different class loaders,
 336      *     and if the class loader of the lookup class is not
 337      *     the same as or an ancestor of the class loader of {@code defc},
 338      *     then {@link SecurityManager#checkPackageAccess
 339      *     smgr.checkPackageAccess(defcPkg)} is called,
 340      *     where {@code defcPkg} is the package of {@code defc}.
 341      * </ul>
 342      */
 343     // FIXME in MR1: clarify that the bytecode behavior of a caller-ID method (like Class.forName) is relative to the lookupClass used to create the method handle, not the dynamic caller of the method handle
 344     public static final
 345     class Lookup {
 346         /** The class on behalf of whom the lookup is being performed. */
 347         private final Class<?> lookupClass;
 348 
 349         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
 350         private final int allowedModes;
 351 
 352         /** A single-bit mask representing {@code public} access,
 353          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 354          *  The value, {@code 0x01}, happens to be the same as the value of the
 355          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
 356          */
 357         public static final int PUBLIC = Modifier.PUBLIC;
 358 
 359         /** A single-bit mask representing {@code private} access,
 360          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 361          *  The value, {@code 0x02}, happens to be the same as the value of the
 362          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
 363          */
 364         public static final int PRIVATE = Modifier.PRIVATE;
 365 
 366         /** A single-bit mask representing {@code protected} access,
 367          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 368          *  The value, {@code 0x04}, happens to be the same as the value of the
 369          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
 370          */
 371         public static final int PROTECTED = Modifier.PROTECTED;
 372 
 373         /** A single-bit mask representing {@code package} access (default access),
 374          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 375          *  The value is {@code 0x08}, which does not correspond meaningfully to
 376          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
 377          */
 378         public static final int PACKAGE = Modifier.STATIC;
 379 
 380         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE);
 381         private static final int TRUSTED   = -1;
 382 
 383         private static int fixmods(int mods) {
 384             mods &= (ALL_MODES - PACKAGE);
 385             return (mods != 0) ? mods : PACKAGE;
 386         }
 387 
 388         /** Tells which class is performing the lookup.  It is this class against
 389          *  which checks are performed for visibility and access permissions.
 390          *  <p>
 391          *  The class implies a maximum level of access permission,
 392          *  but the permissions may be additionally limited by the bitmask
 393          *  {@link #lookupModes lookupModes}, which controls whether non-public members
 394          *  can be accessed.
 395          *  @return the lookup class, on behalf of which this lookup object finds members
 396          */
 397         public Class<?> lookupClass() {
 398             return lookupClass;
 399         }
 400 
 401         // This is just for calling out to MethodHandleImpl.
 402         private Class<?> lookupClassOrNull() {
 403             return (allowedModes == TRUSTED) ? null : lookupClass;
 404         }
 405 
 406         /** Tells which access-protection classes of members this lookup object can produce.
 407          *  The result is a bit-mask of the bits
 408          *  {@linkplain #PUBLIC PUBLIC (0x01)},
 409          *  {@linkplain #PRIVATE PRIVATE (0x02)},
 410          *  {@linkplain #PROTECTED PROTECTED (0x04)},
 411          *  and {@linkplain #PACKAGE PACKAGE (0x08)}.
 412          *  <p>
 413          *  A freshly-created lookup object
 414          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
 415          *  has all possible bits set, since the caller class can access all its own members.
 416          *  A lookup object on a new lookup class
 417          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
 418          *  may have some mode bits set to zero.
 419          *  The purpose of this is to restrict access via the new lookup object,
 420          *  so that it can access only names which can be reached by the original
 421          *  lookup object, and also by the new lookup class.
 422          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
 423          */
 424         public int lookupModes() {
 425             return allowedModes & ALL_MODES;
 426         }
 427 
 428         /** Embody the current class (the lookupClass) as a lookup class
 429          * for method handle creation.
 430          * Must be called by from a method in this package,
 431          * which in turn is called by a method not in this package.
 432          */
 433         Lookup(Class<?> lookupClass) {
 434             this(lookupClass, ALL_MODES);
 435             // make sure we haven't accidentally picked up a privileged class:
 436             checkUnprivilegedlookupClass(lookupClass);
 437         }
 438 
 439         private Lookup(Class<?> lookupClass, int allowedModes) {
 440             this.lookupClass = lookupClass;
 441             this.allowedModes = allowedModes;
 442         }
 443 
 444         /**
 445          * Creates a lookup on the specified new lookup class.
 446          * The resulting object will report the specified
 447          * class as its own {@link #lookupClass lookupClass}.
 448          * <p>
 449          * However, the resulting {@code Lookup} object is guaranteed
 450          * to have no more access capabilities than the original.
 451          * In particular, access capabilities can be lost as follows:<ul>
 452          * <li>If the new lookup class differs from the old one,
 453          * protected members will not be accessible by virtue of inheritance.
 454          * (Protected members may continue to be accessible because of package sharing.)
 455          * <li>If the new lookup class is in a different package
 456          * than the old one, protected and default (package) members will not be accessible.
 457          * <li>If the new lookup class is not within the same package member
 458          * as the old one, private members will not be accessible.
 459          * <li>If the new lookup class is not accessible to the old lookup class,
 460          * then no members, not even public members, will be accessible.
 461          * (In all other cases, public members will continue to be accessible.)
 462          * </ul>
 463          *
 464          * @param requestedLookupClass the desired lookup class for the new lookup object
 465          * @return a lookup object which reports the desired lookup class
 466          * @throws NullPointerException if the argument is null
 467          */
 468         public Lookup in(Class<?> requestedLookupClass) {
 469             requestedLookupClass.getClass();  // null check
 470             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
 471                 return new Lookup(requestedLookupClass, ALL_MODES);
 472             if (requestedLookupClass == this.lookupClass)
 473                 return this;  // keep same capabilities
 474             int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
 475             if ((newModes & PACKAGE) != 0
 476                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
 477                 newModes &= ~(PACKAGE|PRIVATE);
 478             }
 479             // Allow nestmate lookups to be created without special privilege:
 480             if ((newModes & PRIVATE) != 0
 481                 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
 482                 newModes &= ~PRIVATE;
 483             }
 484             if ((newModes & PUBLIC) != 0
 485                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
 486                 // The requested class it not accessible from the lookup class.
 487                 // No permissions.
 488                 newModes = 0;
 489             }
 490             checkUnprivilegedlookupClass(requestedLookupClass);
 491             return new Lookup(requestedLookupClass, newModes);
 492         }
 493 
 494         // Make sure outer class is initialized first.
 495         static { IMPL_NAMES.getClass(); }
 496 
 497         /** Version of lookup which is trusted minimally.
 498          *  It can only be used to create method handles to
 499          *  publicly accessible members.
 500          */
 501         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, PUBLIC);
 502 
 503         /** Package-private version of lookup which is trusted. */
 504         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
 505 
 506         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
 507             String name = lookupClass.getName();
 508             if (name.startsWith("java.lang.invoke."))
 509                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
 510         }
 511 
 512         /**
 513          * Displays the name of the class from which lookups are to be made.
 514          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
 515          * If there are restrictions on the access permitted to this lookup,
 516          * this is indicated by adding a suffix to the class name, consisting
 517          * of a slash and a keyword.  The keyword represents the strongest
 518          * allowed access, and is chosen as follows:
 519          * <ul>
 520          * <li>If no access is allowed, the suffix is "/noaccess".
 521          * <li>If only public access is allowed, the suffix is "/public".
 522          * <li>If only public and package access are allowed, the suffix is "/package".
 523          * <li>If only public, package, and private access are allowed, the suffix is "/private".
 524          * </ul>
 525          * If none of the above cases apply, it is the case that full
 526          * access (public, package, private, and protected) is allowed.
 527          * In this case, no suffix is added.
 528          * This is true only of an object obtained originally from
 529          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
 530          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
 531          * always have restricted access, and will display a suffix.
 532          * <p>
 533          * (It may seem strange that protected access should be
 534          * stronger than private access.  Viewed independently from
 535          * package access, protected access is the first to be lost,
 536          * because it requires a direct subclass relationship between
 537          * caller and callee.)
 538          * @see #in
 539          */
 540         @Override
 541         public String toString() {
 542             String cname = lookupClass.getName();
 543             switch (allowedModes) {
 544             case 0:  // no privileges
 545                 return cname + "/noaccess";
 546             case PUBLIC:
 547                 return cname + "/public";
 548             case PUBLIC|PACKAGE:
 549                 return cname + "/package";
 550             case ALL_MODES & ~PROTECTED:
 551                 return cname + "/private";
 552             case ALL_MODES:
 553                 return cname;
 554             case TRUSTED:
 555                 return "/trusted";  // internal only; not exported
 556             default:  // Should not happen, but it's a bitfield...
 557                 cname = cname + "/" + Integer.toHexString(allowedModes);
 558                 assert(false) : cname;
 559                 return cname;
 560             }
 561         }
 562 
 563         /**
 564          * Produces a method handle for a static method.
 565          * The type of the method handle will be that of the method.
 566          * (Since static methods do not take receivers, there is no
 567          * additional receiver argument inserted into the method handle type,
 568          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
 569          * The method and all its argument types must be accessible to the lookup class.
 570          * If the method's class has not yet been initialized, that is done
 571          * immediately, before the method handle is returned.
 572          * <p>
 573          * The returned method handle will have
 574          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 575          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 576          * @param refc the class from which the method is accessed
 577          * @param name the name of the method
 578          * @param type the type of the method
 579          * @return the desired method handle
 580          * @throws NoSuchMethodException if the method does not exist
 581          * @throws IllegalAccessException if access checking fails,
 582          *                                or if the method is not {@code static},
 583          *                                or if the method's variable arity modifier bit
 584          *                                is set and {@code asVarargsCollector} fails
 585          * @exception SecurityException if a security manager is present and it
 586          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 587          * @throws NullPointerException if any argument is null
 588          */
 589         public
 590         MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 591             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
 592             checkSecurityManager(refc, method);
 593             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method));
 594         }
 595 
 596         /**
 597          * Produces a method handle for a virtual method.
 598          * The type of the method handle will be that of the method,
 599          * with the receiver type (usually {@code refc}) prepended.
 600          * The method and all its argument types must be accessible to the lookup class.
 601          * <p>
 602          * When called, the handle will treat the first argument as a receiver
 603          * and dispatch on the receiver's type to determine which method
 604          * implementation to enter.
 605          * (The dispatching action is identical with that performed by an
 606          * {@code invokevirtual} or {@code invokeinterface} instruction.)
 607          * <p>
 608          * The first argument will be of type {@code refc} if the lookup
 609          * class has full privileges to access the member.  Otherwise
 610          * the member must be {@code protected} and the first argument
 611          * will be restricted in type to the lookup class.
 612          * <p>
 613          * The returned method handle will have
 614          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 615          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 616          * <p>
 617          * Because of the general equivalence between {@code invokevirtual}
 618          * instructions and method handles produced by {@code findVirtual},
 619          * if the class is {@code MethodHandle} and the name string is
 620          * {@code invokeExact} or {@code invoke}, the resulting
 621          * method handle is equivalent to one produced by
 622          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
 623          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
 624          * with the same {@code type} argument.
 625          *
 626          * @param refc the class or interface from which the method is accessed
 627          * @param name the name of the method
 628          * @param type the type of the method, with the receiver argument omitted
 629          * @return the desired method handle
 630          * @throws NoSuchMethodException if the method does not exist
 631          * @throws IllegalAccessException if access checking fails,
 632          *                                or if the method is {@code static}
 633          *                                or if the method's variable arity modifier bit
 634          *                                is set and {@code asVarargsCollector} fails
 635          * @exception SecurityException if a security manager is present and it
 636          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 637          * @throws NullPointerException if any argument is null
 638          */
 639         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 640             if (refc == MethodHandle.class) {
 641                 MethodHandle mh = findVirtualForMH(name, type);
 642                 if (mh != null)  return mh;
 643             }
 644             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
 645             MemberName method = resolveOrFail(refKind, refc, name, type);
 646             checkSecurityManager(refc, method);
 647             return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
 648         }
 649         private MethodHandle findVirtualForMH(String name, MethodType type) {
 650             // these names require special lookups because of the implicit MethodType argument
 651             if ("invoke".equals(name))
 652                 return invoker(type);
 653             if ("invokeExact".equals(name))
 654                 return exactInvoker(type);
 655             return null;
 656         }
 657 
 658         /**
 659          * Produces a method handle which creates an object and initializes it, using
 660          * the constructor of the specified type.
 661          * The parameter types of the method handle will be those of the constructor,
 662          * while the return type will be a reference to the constructor's class.
 663          * The constructor and all its argument types must be accessible to the lookup class.
 664          * If the constructor's class has not yet been initialized, that is done
 665          * immediately, before the method handle is returned.
 666          * <p>
 667          * Note:  The requested type must have a return type of {@code void}.
 668          * This is consistent with the JVM's treatment of constructor type descriptors.
 669          * <p>
 670          * The returned method handle will have
 671          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 672          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
 673          * @param refc the class or interface from which the method is accessed
 674          * @param type the type of the method, with the receiver argument omitted, and a void return type
 675          * @return the desired method handle
 676          * @throws NoSuchMethodException if the constructor does not exist
 677          * @throws IllegalAccessException if access checking fails
 678          *                                or if the method's variable arity modifier bit
 679          *                                is set and {@code asVarargsCollector} fails
 680          * @exception SecurityException if a security manager is present and it
 681          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 682          * @throws NullPointerException if any argument is null
 683          */
 684         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 685             String name = "<init>";
 686             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
 687             checkSecurityManager(refc, ctor);
 688             return getDirectConstructor(refc, ctor);
 689         }
 690 
 691         /**
 692          * Produces an early-bound method handle for a virtual method,
 693          * as if called from an {@code invokespecial}
 694          * instruction from {@code caller}.
 695          * The type of the method handle will be that of the method,
 696          * with a suitably restricted receiver type (such as {@code caller}) prepended.
 697          * The method and all its argument types must be accessible
 698          * to the caller.
 699          * <p>
 700          * When called, the handle will treat the first argument as a receiver,
 701          * but will not dispatch on the receiver's type.
 702          * (This direct invocation action is identical with that performed by an
 703          * {@code invokespecial} instruction.)
 704          * <p>
 705          * If the explicitly specified caller class is not identical with the
 706          * lookup class, or if this lookup object does not have private access
 707          * privileges, the access fails.
 708          * <p>
 709          * The returned method handle will have
 710          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 711          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 712          * @param refc the class or interface from which the method is accessed
 713          * @param name the name of the method (which must not be "&lt;init&gt;")
 714          * @param type the type of the method, with the receiver argument omitted
 715          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
 716          * @return the desired method handle
 717          * @throws NoSuchMethodException if the method does not exist
 718          * @throws IllegalAccessException if access checking fails
 719          *                                or if the method's variable arity modifier bit
 720          *                                is set and {@code asVarargsCollector} fails
 721          * @exception SecurityException if a security manager is present and it
 722          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 723          * @throws NullPointerException if any argument is null
 724          */
 725         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
 726                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
 727             checkSpecialCaller(specialCaller);
 728             Lookup specialLookup = this.in(specialCaller);
 729             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
 730             checkSecurityManager(refc, method);
 731             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
 732         }
 733 
 734         /**
 735          * Produces a method handle giving read access to a non-static field.
 736          * The type of the method handle will have a return type of the field's
 737          * value type.
 738          * The method handle's single argument will be the instance containing
 739          * the field.
 740          * Access checking is performed immediately on behalf of the lookup class.
 741          * @param refc the class or interface from which the method is accessed
 742          * @param name the field's name
 743          * @param type the field's type
 744          * @return a method handle which can load values from the field
 745          * @throws NoSuchFieldException if the field does not exist
 746          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
 747          * @exception SecurityException if a security manager is present and it
 748          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 749          * @throws NullPointerException if any argument is null
 750          */
 751         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
 752             MemberName field = resolveOrFail(REF_getField, refc, name, type);
 753             checkSecurityManager(refc, field);
 754             return getDirectField(REF_getField, refc, field);
 755         }
 756 
 757         /**
 758          * Produces a method handle giving write access to a non-static field.
 759          * The type of the method handle will have a void return type.
 760          * The method handle will take two arguments, the instance containing
 761          * the field, and the value to be stored.
 762          * The second argument will be of the field's value type.
 763          * Access checking is performed immediately on behalf of the lookup class.
 764          * @param refc the class or interface from which the method is accessed
 765          * @param name the field's name
 766          * @param type the field's type
 767          * @return a method handle which can store values into the field
 768          * @throws NoSuchFieldException if the field does not exist
 769          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
 770          * @exception SecurityException if a security manager is present and it
 771          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 772          * @throws NullPointerException if any argument is null
 773          */
 774         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
 775             MemberName field = resolveOrFail(REF_putField, refc, name, type);
 776             checkSecurityManager(refc, field);
 777             return getDirectField(REF_putField, refc, field);
 778         }
 779 
 780         /**
 781          * Produces a method handle giving read access to a static field.
 782          * The type of the method handle will have a return type of the field's
 783          * value type.
 784          * The method handle will take no arguments.
 785          * Access checking is performed immediately on behalf of the lookup class.
 786          * @param refc the class or interface from which the method is accessed
 787          * @param name the field's name
 788          * @param type the field's type
 789          * @return a method handle which can load values from the field
 790          * @throws NoSuchFieldException if the field does not exist
 791          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
 792          * @exception SecurityException if a security manager is present and it
 793          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 794          * @throws NullPointerException if any argument is null
 795          */
 796         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
 797             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
 798             checkSecurityManager(refc, field);
 799             return getDirectField(REF_getStatic, refc, field);
 800         }
 801 
 802         /**
 803          * Produces a method handle giving write access to a static field.
 804          * The type of the method handle will have a void return type.
 805          * The method handle will take a single
 806          * argument, of the field's value type, the value to be stored.
 807          * Access checking is performed immediately on behalf of the lookup class.
 808          * @param refc the class or interface from which the method is accessed
 809          * @param name the field's name
 810          * @param type the field's type
 811          * @return a method handle which can store values into the field
 812          * @throws NoSuchFieldException if the field does not exist
 813          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
 814          * @exception SecurityException if a security manager is present and it
 815          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 816          * @throws NullPointerException if any argument is null
 817          */
 818         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
 819             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
 820             checkSecurityManager(refc, field);
 821             return getDirectField(REF_putStatic, refc, field);
 822         }
 823 
 824         /**
 825          * Produces an early-bound method handle for a non-static method.
 826          * The receiver must have a supertype {@code defc} in which a method
 827          * of the given name and type is accessible to the lookup class.
 828          * The method and all its argument types must be accessible to the lookup class.
 829          * The type of the method handle will be that of the method,
 830          * without any insertion of an additional receiver parameter.
 831          * The given receiver will be bound into the method handle,
 832          * so that every call to the method handle will invoke the
 833          * requested method on the given receiver.
 834          * <p>
 835          * The returned method handle will have
 836          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 837          * the method's variable arity modifier bit ({@code 0x0080}) is set
 838          * <em>and</em> the trailing array argument is not the only argument.
 839          * (If the trailing array argument is the only argument,
 840          * the given receiver value will be bound to it.)
 841          * <p>
 842          * This is equivalent to the following code:
 843          * <blockquote><pre>
 844 import static java.lang.invoke.MethodHandles.*;
 845 import static java.lang.invoke.MethodType.*;
 846 ...
 847 MethodHandle mh0 = lookup().{@link #findVirtual findVirtual}(defc, name, type);
 848 MethodHandle mh1 = mh0.{@link MethodHandle#bindTo bindTo}(receiver);
 849 MethodType mt1 = mh1.type();
 850 if (mh0.isVarargsCollector())
 851   mh1 = mh1.asVarargsCollector(mt1.parameterType(mt1.parameterCount()-1));
 852 return mh1;
 853          * </pre></blockquote>
 854          * where {@code defc} is either {@code receiver.getClass()} or a super
 855          * type of that class, in which the requested method is accessible
 856          * to the lookup class.
 857          * (Note that {@code bindTo} does not preserve variable arity.)
 858          * @param receiver the object from which the method is accessed
 859          * @param name the name of the method
 860          * @param type the type of the method, with the receiver argument omitted
 861          * @return the desired method handle
 862          * @throws NoSuchMethodException if the method does not exist
 863          * @throws IllegalAccessException if access checking fails
 864          *                                or if the method's variable arity modifier bit
 865          *                                is set and {@code asVarargsCollector} fails
 866          * @exception SecurityException if a security manager is present and it
 867          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 868          * @throws NullPointerException if any argument is null
 869          */
 870         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 871             Class<? extends Object> refc = receiver.getClass(); // may get NPE
 872             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
 873             checkSecurityManager(refc, method);
 874             MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
 875             return mh.bindReceiver(receiver).setVarargs(method);
 876         }
 877 
 878         /**
 879          * Makes a direct method handle to <i>m</i>, if the lookup class has permission.
 880          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
 881          * If <i>m</i> is virtual, overriding is respected on every call.
 882          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
 883          * The type of the method handle will be that of the method,
 884          * with the receiver type prepended (but only if it is non-static).
 885          * If the method's {@code accessible} flag is not set,
 886          * access checking is performed immediately on behalf of the lookup class.
 887          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
 888          * <p>
 889          * The returned method handle will have
 890          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 891          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 892          * @param m the reflected method
 893          * @return a method handle which can invoke the reflected method
 894          * @throws IllegalAccessException if access checking fails
 895          *                                or if the method's variable arity modifier bit
 896          *                                is set and {@code asVarargsCollector} fails
 897          * @throws NullPointerException if the argument is null
 898          */
 899         public MethodHandle unreflect(Method m) throws IllegalAccessException {
 900             MemberName method = new MemberName(m);
 901             byte refKind = method.getReferenceKind();
 902             if (refKind == REF_invokeSpecial)
 903                 refKind = REF_invokeVirtual;
 904             assert(method.isMethod());
 905             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
 906             return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
 907         }
 908 
 909         /**
 910          * Produces a method handle for a reflected method.
 911          * It will bypass checks for overriding methods on the receiver,
 912          * as if by a {@code invokespecial} instruction from within the {@code specialCaller}.
 913          * The type of the method handle will be that of the method,
 914          * with the special caller type prepended (and <em>not</em> the receiver of the method).
 915          * If the method's {@code accessible} flag is not set,
 916          * access checking is performed immediately on behalf of the lookup class,
 917          * as if {@code invokespecial} instruction were being linked.
 918          * <p>
 919          * The returned method handle will have
 920          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 921          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 922          * @param m the reflected method
 923          * @param specialCaller the class nominally calling the method
 924          * @return a method handle which can invoke the reflected method
 925          * @throws IllegalAccessException if access checking fails
 926          *                                or if the method's variable arity modifier bit
 927          *                                is set and {@code asVarargsCollector} fails
 928          * @throws NullPointerException if any argument is null
 929          */
 930         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
 931             checkSpecialCaller(specialCaller);
 932             Lookup specialLookup = this.in(specialCaller);
 933             MemberName method = new MemberName(m, true);
 934             assert(method.isMethod());
 935             // ignore m.isAccessible:  this is a new kind of access
 936             return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
 937         }
 938 
 939         /**
 940          * Produces a method handle for a reflected constructor.
 941          * The type of the method handle will be that of the constructor,
 942          * with the return type changed to the declaring class.
 943          * The method handle will perform a {@code newInstance} operation,
 944          * creating a new instance of the constructor's class on the
 945          * arguments passed to the method handle.
 946          * <p>
 947          * If the constructor's {@code accessible} flag is not set,
 948          * access checking is performed immediately on behalf of the lookup class.
 949          * <p>
 950          * The returned method handle will have
 951          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 952          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
 953          * @param c the reflected constructor
 954          * @return a method handle which can invoke the reflected constructor
 955          * @throws IllegalAccessException if access checking fails
 956          *                                or if the method's variable arity modifier bit
 957          *                                is set and {@code asVarargsCollector} fails
 958          * @throws NullPointerException if the argument is null
 959          */
 960         @SuppressWarnings("rawtypes")  // Will be Constructor<?> after JSR 292 MR
 961         public MethodHandle unreflectConstructor(Constructor c) throws IllegalAccessException {
 962             MemberName ctor = new MemberName(c);
 963             assert(ctor.isConstructor());
 964             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
 965             return lookup.getDirectConstructor(ctor.getDeclaringClass(), ctor);
 966         }
 967 
 968         /**
 969          * Produces a method handle giving read access to a reflected field.
 970          * The type of the method handle will have a return type of the field's
 971          * value type.
 972          * If the field is static, the method handle will take no arguments.
 973          * Otherwise, its single argument will be the instance containing
 974          * the field.
 975          * If the field's {@code accessible} flag is not set,
 976          * access checking is performed immediately on behalf of the lookup class.
 977          * @param f the reflected field
 978          * @return a method handle which can load values from the reflected field
 979          * @throws IllegalAccessException if access checking fails
 980          * @throws NullPointerException if the argument is null
 981          */
 982         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
 983             return unreflectField(f, false);
 984         }
 985         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
 986             MemberName field = new MemberName(f, isSetter);
 987             assert(isSetter
 988                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
 989                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
 990             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
 991             return lookup.getDirectField(field.getReferenceKind(), f.getDeclaringClass(), field);
 992         }
 993 
 994         /**
 995          * Produces a method handle giving write access to a reflected field.
 996          * The type of the method handle will have a void return type.
 997          * If the field is static, the method handle will take a single
 998          * argument, of the field's value type, the value to be stored.
 999          * Otherwise, the two arguments will be the instance containing
1000          * the field, and the value to be stored.
1001          * If the field's {@code accessible} flag is not set,
1002          * access checking is performed immediately on behalf of the lookup class.
1003          * @param f the reflected field
1004          * @return a method handle which can store values into the reflected field
1005          * @throws IllegalAccessException if access checking fails
1006          * @throws NullPointerException if the argument is null
1007          */
1008         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
1009             return unreflectField(f, true);
1010         }
1011 
1012         /// Helper methods, all package-private.
1013 
1014         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1015             checkSymbolicClass(refc);  // do this before attempting to resolve
1016             name.getClass(); type.getClass();  // NPE
1017             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1018                                             NoSuchFieldException.class);
1019         }
1020 
1021         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1022             checkSymbolicClass(refc);  // do this before attempting to resolve
1023             name.getClass(); type.getClass();  // NPE
1024             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1025                                             NoSuchMethodException.class);
1026         }
1027 
1028         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
1029             Class<?> caller = lookupClassOrNull();
1030             if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes))
1031                 throw new MemberName(refc).makeAccessException("symbolic reference class is not public", this);
1032         }
1033 
1034         /**
1035          * Find my trustable caller class if m is a caller sensitive method.
1036          * If this lookup object has private access, then the caller class is the lookupClass.
1037          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
1038          */
1039         Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
1040             Class<?> callerClass = null;
1041             if (MethodHandleNatives.isCallerSensitive(m)) {
1042                 // Only full-power lookup is allowed to resolve caller-sensitive methods
1043                 if (isFullPowerLookup()) {
1044                     callerClass = lookupClass;
1045                 } else {
1046                     throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
1047                 }
1048             }
1049             return callerClass;
1050         }
1051 
1052         private boolean isFullPowerLookup() {
1053             return (allowedModes & PRIVATE) != 0;
1054         }
1055 
1056         /**
1057          * Determine whether a security manager has an overridden
1058          * SecurityManager.checkMemberAccess method.
1059          */
1060         private boolean isCheckMemberAccessOverridden(SecurityManager sm) {
1061             final Class<? extends SecurityManager> cls = sm.getClass();
1062             if (cls == SecurityManager.class) return false;
1063 
1064             try {
1065                 return cls.getMethod("checkMemberAccess", Class.class, int.class).
1066                     getDeclaringClass() != SecurityManager.class;
1067             } catch (NoSuchMethodException e) {
1068                 throw new InternalError("should not reach here");
1069             }
1070         }
1071 
1072         /**
1073          * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
1074          * Determines a trustable caller class to compare with refc, the symbolic reference class.
1075          * If this lookup object has private access, then the caller class is the lookupClass.
1076          */
1077         void checkSecurityManager(Class<?> refc, MemberName m) {
1078             SecurityManager smgr = System.getSecurityManager();
1079             if (smgr == null)  return;
1080             if (allowedModes == TRUSTED)  return;
1081 
1082             final boolean overridden = isCheckMemberAccessOverridden(smgr);
1083             // Step 1:
1084             {
1085                 // Default policy is to allow Member.PUBLIC; no need to check
1086                 // permission if SecurityManager is the default implementation
1087                 final int which = Member.PUBLIC;
1088                 final Class<?> clazz = refc;
1089                 if (overridden) {
1090                     // Don't refactor; otherwise break the stack depth for
1091                     // checkMemberAccess of subclasses of SecurityManager as specified.
1092                     smgr.checkMemberAccess(clazz, which);
1093                 }
1094             }
1095 
1096             // Step 2:
1097             if (!isFullPowerLookup() ||
1098                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
1099                 ReflectUtil.checkPackageAccess(refc);
1100             }
1101 
1102             // Step 3:
1103             if (m.isPublic()) return;
1104             Class<?> defc = m.getDeclaringClass();
1105             {
1106                 // Inline SecurityManager.checkMemberAccess
1107                 final int which = Member.DECLARED;
1108                 final Class<?> clazz = defc;
1109                 if (!overridden) {
1110                     if (!isFullPowerLookup()) {
1111                         smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
1112                     }
1113                 } else {
1114                     // Don't refactor; otherwise break the stack depth for
1115                     // checkMemberAccess of subclasses of SecurityManager as specified.
1116                     smgr.checkMemberAccess(clazz, which);
1117                 }
1118             }
1119 
1120             // Step 4:
1121             if (defc != refc) {
1122                 ReflectUtil.checkPackageAccess(defc);
1123             }
1124         }
1125 
1126         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1127             boolean wantStatic = (refKind == REF_invokeStatic);
1128             String message;
1129             if (m.isConstructor())
1130                 message = "expected a method, not a constructor";
1131             else if (!m.isMethod())
1132                 message = "expected a method";
1133             else if (wantStatic != m.isStatic())
1134                 message = wantStatic ? "expected a static method" : "expected a non-static method";
1135             else
1136                 { checkAccess(refKind, refc, m); return; }
1137             throw m.makeAccessException(message, this);
1138         }
1139 
1140         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1141             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
1142             String message;
1143             if (wantStatic != m.isStatic())
1144                 message = wantStatic ? "expected a static field" : "expected a non-static field";
1145             else
1146                 { checkAccess(refKind, refc, m); return; }
1147             throw m.makeAccessException(message, this);
1148         }
1149 
1150         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1151             assert(m.referenceKindIsConsistentWith(refKind) &&
1152                    MethodHandleNatives.refKindIsValid(refKind) &&
1153                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
1154             int allowedModes = this.allowedModes;
1155             if (allowedModes == TRUSTED)  return;
1156             int mods = m.getModifiers();
1157             if (Modifier.isFinal(mods) &&
1158                     MethodHandleNatives.refKindIsSetter(refKind))
1159                 throw m.makeAccessException("unexpected set of a final field", this);
1160             if (Modifier.isPublic(mods) && Modifier.isPublic(refc.getModifiers()) && allowedModes != 0)
1161                 return;  // common case
1162             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
1163             if ((requestedModes & allowedModes) != 0) {
1164                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
1165                                                     mods, lookupClass(), allowedModes))
1166                     return;
1167             } else {
1168                 // Protected members can also be checked as if they were package-private.
1169                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
1170                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
1171                     return;
1172             }
1173             throw m.makeAccessException(accessFailedMessage(refc, m), this);
1174         }
1175 
1176         String accessFailedMessage(Class<?> refc, MemberName m) {
1177             Class<?> defc = m.getDeclaringClass();
1178             int mods = m.getModifiers();
1179             // check the class first:
1180             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
1181                                (defc == refc ||
1182                                 Modifier.isPublic(refc.getModifiers())));
1183             if (!classOK && (allowedModes & PACKAGE) != 0) {
1184                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
1185                            (defc == refc ||
1186                             VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
1187             }
1188             if (!classOK)
1189                 return "class is not public";
1190             if (Modifier.isPublic(mods))
1191                 return "access to public member failed";  // (how?)
1192             if (Modifier.isPrivate(mods))
1193                 return "member is private";
1194             if (Modifier.isProtected(mods))
1195                 return "member is protected";
1196             return "member is private to package";
1197         }
1198 
1199         private static final boolean ALLOW_NESTMATE_ACCESS = false;
1200 
1201         private void checkSpecialCaller(Class<?> specialCaller) throws IllegalAccessException {
1202             int allowedModes = this.allowedModes;
1203             if (allowedModes == TRUSTED)  return;
1204             if ((allowedModes & PRIVATE) == 0
1205                 || (specialCaller != lookupClass()
1206                     && !(ALLOW_NESTMATE_ACCESS &&
1207                          VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
1208                 throw new MemberName(specialCaller).
1209                     makeAccessException("no private access for invokespecial", this);
1210         }
1211 
1212         private boolean restrictProtectedReceiver(MemberName method) {
1213             // The accessing class only has the right to use a protected member
1214             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
1215             if (!method.isProtected() || method.isStatic()
1216                 || allowedModes == TRUSTED
1217                 || method.getDeclaringClass() == lookupClass()
1218                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
1219                 || (ALLOW_NESTMATE_ACCESS &&
1220                     VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass())))
1221                 return false;
1222             return true;
1223         }
1224         private MethodHandle restrictReceiver(MemberName method, MethodHandle mh, Class<?> caller) throws IllegalAccessException {
1225             assert(!method.isStatic());
1226             // receiver type of mh is too wide; narrow to caller
1227             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
1228                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
1229             }
1230             MethodType rawType = mh.type();
1231             if (rawType.parameterType(0) == caller)  return mh;
1232             MethodType narrowType = rawType.changeParameterType(0, caller);
1233             return mh.viewAsType(narrowType);
1234         }
1235 
1236         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1237             return getDirectMethodCommon(refKind, refc, method,
1238                     (refKind == REF_invokeSpecial ||
1239                         (MethodHandleNatives.refKindHasReceiver(refKind) &&
1240                             restrictProtectedReceiver(method))), callerClass);
1241         }
1242         private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1243             return getDirectMethodCommon(refKind, refc, method, false, callerClass);
1244         }
1245         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
1246                                                    boolean doRestrict, Class<?> callerClass) throws IllegalAccessException {
1247             checkMethod(refKind, refc, method);
1248             if (method.isMethodHandleInvoke())
1249                 return fakeMethodHandleInvoke(method);
1250 
1251             Class<?> refcAsSuper;
1252             if (refKind == REF_invokeSpecial &&
1253                 refc != lookupClass() &&
1254                 refc != (refcAsSuper = lookupClass().getSuperclass()) &&
1255                 refc.isAssignableFrom(lookupClass())) {
1256                 assert(!method.getName().equals("<init>"));  // not this code path
1257                 // Per JVMS 6.5, desc. of invokespecial instruction:
1258                 // If the method is in a superclass of the LC,
1259                 // and if our original search was above LC.super,
1260                 // repeat the search (symbolic lookup) from LC.super.
1261                 // FIXME: MemberName.resolve should handle this instead.
1262                 MemberName m2 = new MemberName(refcAsSuper,
1263                                                method.getName(),
1264                                                method.getMethodType(),
1265                                                REF_invokeSpecial);
1266                 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
1267                 if (m2 == null)  throw new InternalError(method.toString());
1268                 method = m2;
1269                 refc = refcAsSuper;
1270                 // redo basic checks
1271                 checkMethod(refKind, refc, method);
1272             }
1273 
1274             MethodHandle mh = DirectMethodHandle.make(refKind, refc, method);
1275             mh = maybeBindCaller(method, mh, callerClass);
1276             mh = mh.setVarargs(method);
1277             if (doRestrict)
1278                 mh = restrictReceiver(method, mh, lookupClass());
1279             return mh;
1280         }
1281         private MethodHandle fakeMethodHandleInvoke(MemberName method) {
1282             return throwException(method.getReturnType(), UnsupportedOperationException.class);
1283         }
1284         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
1285                                              Class<?> callerClass)
1286                                              throws IllegalAccessException {
1287             if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
1288                 return mh;
1289             Class<?> hostClass = lookupClass;
1290             if ((allowedModes & PRIVATE) == 0)  // caller must use full-power lookup
1291                 hostClass = callerClass;  // callerClass came from a security manager style stack walk
1292             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
1293             // Note: caller will apply varargs after this step happens.
1294             return cbmh;
1295         }
1296         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
1297             checkField(refKind, refc, field);
1298             MethodHandle mh = DirectMethodHandle.make(refc, field);
1299             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
1300                                     restrictProtectedReceiver(field));
1301             if (doRestrict)
1302                 mh = restrictReceiver(field, mh, lookupClass());
1303             return mh;
1304         }
1305         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
1306             assert(ctor.isConstructor());
1307             checkAccess(REF_newInvokeSpecial, refc, ctor);
1308             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
1309             return DirectMethodHandle.make(ctor).setVarargs(ctor);
1310         }
1311 
1312         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
1313          */
1314         /*non-public*/
1315         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException {
1316             MemberName resolved = null;
1317             if (type instanceof MemberName) {
1318                 resolved = (MemberName) type;
1319                 if (!resolved.isResolved())  throw new InternalError("unresolved MemberName");
1320                 assert(name == null || name.equals(resolved.getName()));
1321             }
1322             if (MethodHandleNatives.refKindIsField(refKind)) {
1323                 MemberName field = (resolved != null) ? resolved
1324                         : resolveOrFail(refKind, defc, name, (Class<?>) type);
1325                 return getDirectField(refKind, defc, field);
1326             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
1327                 MemberName method = (resolved != null) ? resolved
1328                         : resolveOrFail(refKind, defc, name, (MethodType) type);
1329                 return getDirectMethod(refKind, defc, method, lookupClass);
1330             } else if (refKind == REF_newInvokeSpecial) {
1331                 assert(name == null || name.equals("<init>"));
1332                 MemberName ctor = (resolved != null) ? resolved
1333                         : resolveOrFail(REF_newInvokeSpecial, defc, name, (MethodType) type);
1334                 return getDirectConstructor(defc, ctor);
1335             }
1336             // oops
1337             throw new ReflectiveOperationException("bad MethodHandle constant #"+refKind+" "+name+" : "+type);
1338         }
1339     }
1340 
1341     /**
1342      * Produces a method handle giving read access to elements of an array.
1343      * The type of the method handle will have a return type of the array's
1344      * element type.  Its first argument will be the array type,
1345      * and the second will be {@code int}.
1346      * @param arrayClass an array type
1347      * @return a method handle which can load values from the given array type
1348      * @throws NullPointerException if the argument is null
1349      * @throws  IllegalArgumentException if arrayClass is not an array type
1350      */
1351     public static
1352     MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
1353         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false);
1354     }
1355 
1356     /**
1357      * Produces a method handle giving write access to elements of an array.
1358      * The type of the method handle will have a void return type.
1359      * Its last argument will be the array's element type.
1360      * The first and second arguments will be the array type and int.
1361      * @param arrayClass the class of an array
1362      * @return a method handle which can store values into the array type
1363      * @throws NullPointerException if the argument is null
1364      * @throws IllegalArgumentException if arrayClass is not an array type
1365      */
1366     public static
1367     MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
1368         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true);
1369     }
1370 
1371     /// method handle invocation (reflective style)
1372 
1373     /**
1374      * Produces a method handle which will invoke any method handle of the
1375      * given {@code type}, with a given number of trailing arguments replaced by
1376      * a single trailing {@code Object[]} array.
1377      * The resulting invoker will be a method handle with the following
1378      * arguments:
1379      * <ul>
1380      * <li>a single {@code MethodHandle} target
1381      * <li>zero or more leading values (counted by {@code leadingArgCount})
1382      * <li>an {@code Object[]} array containing trailing arguments
1383      * </ul>
1384      * <p>
1385      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
1386      * the indicated {@code type}.
1387      * That is, if the target is exactly of the given {@code type}, it will behave
1388      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
1389      * is used to convert the target to the required {@code type}.
1390      * <p>
1391      * The type of the returned invoker will not be the given {@code type}, but rather
1392      * will have all parameters except the first {@code leadingArgCount}
1393      * replaced by a single array of type {@code Object[]}, which will be
1394      * the final parameter.
1395      * <p>
1396      * Before invoking its target, the invoker will spread the final array, apply
1397      * reference casts as necessary, and unbox and widen primitive arguments.
1398      * <p>
1399      * This method is equivalent to the following code (though it may be more efficient):
1400      * <p><blockquote><pre>
1401 MethodHandle invoker = MethodHandles.invoker(type);
1402 int spreadArgCount = type.parameterCount() - leadingArgCount;
1403 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
1404 return invoker;
1405      * </pre></blockquote>
1406      * <p>
1407      * This method throws no reflective or security exceptions.
1408      * @param type the desired target type
1409      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
1410      * @return a method handle suitable for invoking any method handle of the given type
1411      * @throws NullPointerException if {@code type} is null
1412      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
1413      *                  the range from 0 to {@code type.parameterCount()} inclusive
1414      */
1415     static public
1416     MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
1417         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
1418             throw new IllegalArgumentException("bad argument count "+leadingArgCount);
1419         return type.invokers().spreadInvoker(leadingArgCount);
1420     }
1421 
1422     /**
1423      * Produces a special <em>invoker method handle</em> which can be used to
1424      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
1425      * The resulting invoker will have a type which is
1426      * exactly equal to the desired type, except that it will accept
1427      * an additional leading argument of type {@code MethodHandle}.
1428      * <p>
1429      * This method is equivalent to the following code (though it may be more efficient):
1430      * <p><blockquote><pre>
1431 publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)
1432      * </pre></blockquote>
1433      *
1434      * <p style="font-size:smaller;">
1435      * <em>Discussion:</em>
1436      * Invoker method handles can be useful when working with variable method handles
1437      * of unknown types.
1438      * For example, to emulate an {@code invokeExact} call to a variable method
1439      * handle {@code M}, extract its type {@code T},
1440      * look up the invoker method {@code X} for {@code T},
1441      * and call the invoker method, as {@code X.invoke(T, A...)}.
1442      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
1443      * is unknown.)
1444      * If spreading, collecting, or other argument transformations are required,
1445      * they can be applied once to the invoker {@code X} and reused on many {@code M}
1446      * method handle values, as long as they are compatible with the type of {@code X}.
1447      * <p>
1448      * <em>(Note:  The invoker method is not available via the Core Reflection API.
1449      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
1450      * on the declared {@code invokeExact} or {@code invoke} method will raise an
1451      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
1452      * <p>
1453      * This method throws no reflective or security exceptions.
1454      * @param type the desired target type
1455      * @return a method handle suitable for invoking any method handle of the given type
1456      */
1457     static public
1458     MethodHandle exactInvoker(MethodType type) {
1459         return type.invokers().exactInvoker();
1460     }
1461 
1462     /**
1463      * Produces a special <em>invoker method handle</em> which can be used to
1464      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
1465      * The resulting invoker will have a type which is
1466      * exactly equal to the desired type, except that it will accept
1467      * an additional leading argument of type {@code MethodHandle}.
1468      * <p>
1469      * Before invoking its target, if the target differs from the expected type,
1470      * the invoker will apply reference casts as
1471      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
1472      * Similarly, the return value will be converted as necessary.
1473      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
1474      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
1475      * <p>
1476      * A {@linkplain MethodType#genericMethodType general method type},
1477      * mentions only {@code Object} arguments and return values.
1478      * An invoker for such a type is capable of calling any method handle
1479      * of the same arity as the general type.
1480      * <p>
1481      * This method is equivalent to the following code (though it may be more efficient):
1482      * <p><blockquote><pre>
1483 publicLookup().findVirtual(MethodHandle.class, "invoke", type)
1484      * </pre></blockquote>
1485      * <p>
1486      * This method throws no reflective or security exceptions.
1487      * @param type the desired target type
1488      * @return a method handle suitable for invoking any method handle convertible to the given type
1489      */
1490     static public
1491     MethodHandle invoker(MethodType type) {
1492         return type.invokers().generalInvoker();
1493     }
1494 
1495     static /*non-public*/
1496     MethodHandle basicInvoker(MethodType type) {
1497         return type.form().basicInvoker();
1498     }
1499 
1500      /// method handle modification (creation from other method handles)
1501 
1502     /**
1503      * Produces a method handle which adapts the type of the
1504      * given method handle to a new type by pairwise argument and return type conversion.
1505      * The original type and new type must have the same number of arguments.
1506      * The resulting method handle is guaranteed to report a type
1507      * which is equal to the desired new type.
1508      * <p>
1509      * If the original type and new type are equal, returns target.
1510      * <p>
1511      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
1512      * and some additional conversions are also applied if those conversions fail.
1513      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
1514      * if possible, before or instead of any conversions done by {@code asType}:
1515      * <ul>
1516      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
1517      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
1518      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
1519      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
1520      *     the boolean is converted to a byte value, 1 for true, 0 for false.
1521      *     (This treatment follows the usage of the bytecode verifier.)
1522      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
1523      *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
1524      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
1525      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
1526      *     then a Java casting conversion (JLS 5.5) is applied.
1527      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
1528      *     widening and/or narrowing.)
1529      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
1530      *     conversion will be applied at runtime, possibly followed
1531      *     by a Java casting conversion (JLS 5.5) on the primitive value,
1532      *     possibly followed by a conversion from byte to boolean by testing
1533      *     the low-order bit.
1534      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
1535      *     and if the reference is null at runtime, a zero value is introduced.
1536      * </ul>
1537      * @param target the method handle to invoke after arguments are retyped
1538      * @param newType the expected type of the new method handle
1539      * @return a method handle which delegates to the target after performing
1540      *           any necessary argument conversions, and arranges for any
1541      *           necessary return value conversions
1542      * @throws NullPointerException if either argument is null
1543      * @throws WrongMethodTypeException if the conversion cannot be made
1544      * @see MethodHandle#asType
1545      */
1546     public static
1547     MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
1548         if (!target.type().isCastableTo(newType)) {
1549             throw new WrongMethodTypeException("cannot explicitly cast "+target+" to "+newType);
1550         }
1551         return MethodHandleImpl.makePairwiseConvert(target, newType, 2);
1552     }
1553 
1554     /**
1555      * Produces a method handle which adapts the calling sequence of the
1556      * given method handle to a new type, by reordering the arguments.
1557      * The resulting method handle is guaranteed to report a type
1558      * which is equal to the desired new type.
1559      * <p>
1560      * The given array controls the reordering.
1561      * Call {@code #I} the number of incoming parameters (the value
1562      * {@code newType.parameterCount()}, and call {@code #O} the number
1563      * of outgoing parameters (the value {@code target.type().parameterCount()}).
1564      * Then the length of the reordering array must be {@code #O},
1565      * and each element must be a non-negative number less than {@code #I}.
1566      * For every {@code N} less than {@code #O}, the {@code N}-th
1567      * outgoing argument will be taken from the {@code I}-th incoming
1568      * argument, where {@code I} is {@code reorder[N]}.
1569      * <p>
1570      * No argument or return value conversions are applied.
1571      * The type of each incoming argument, as determined by {@code newType},
1572      * must be identical to the type of the corresponding outgoing parameter
1573      * or parameters in the target method handle.
1574      * The return type of {@code newType} must be identical to the return
1575      * type of the original target.
1576      * <p>
1577      * The reordering array need not specify an actual permutation.
1578      * An incoming argument will be duplicated if its index appears
1579      * more than once in the array, and an incoming argument will be dropped
1580      * if its index does not appear in the array.
1581      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
1582      * incoming arguments which are not mentioned in the reordering array
1583      * are may be any type, as determined only by {@code newType}.
1584      * <blockquote><pre>{@code
1585 import static java.lang.invoke.MethodHandles.*;
1586 import static java.lang.invoke.MethodType.*;
1587 ...
1588 MethodType intfn1 = methodType(int.class, int.class);
1589 MethodType intfn2 = methodType(int.class, int.class, int.class);
1590 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
1591 assert(sub.type().equals(intfn2));
1592 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
1593 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
1594 assert((int)rsub.invokeExact(1, 100) == 99);
1595 MethodHandle add = ... (int x, int y) -> (x+y) ...;
1596 assert(add.type().equals(intfn2));
1597 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
1598 assert(twice.type().equals(intfn1));
1599 assert((int)twice.invokeExact(21) == 42);
1600      * }</pre></blockquote>
1601      * @param target the method handle to invoke after arguments are reordered
1602      * @param newType the expected type of the new method handle
1603      * @param reorder an index array which controls the reordering
1604      * @return a method handle which delegates to the target after it
1605      *           drops unused arguments and moves and/or duplicates the other arguments
1606      * @throws NullPointerException if any argument is null
1607      * @throws IllegalArgumentException if the index array length is not equal to
1608      *                  the arity of the target, or if any index array element
1609      *                  not a valid index for a parameter of {@code newType},
1610      *                  or if two corresponding parameter types in
1611      *                  {@code target.type()} and {@code newType} are not identical,
1612      */
1613     public static
1614     MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
1615         checkReorder(reorder, newType, target.type());
1616         return target.permuteArguments(newType, reorder);
1617     }
1618 
1619     private static void checkReorder(int[] reorder, MethodType newType, MethodType oldType) {
1620         if (newType.returnType() != oldType.returnType())
1621             throw newIllegalArgumentException("return types do not match",
1622                     oldType, newType);
1623         if (reorder.length == oldType.parameterCount()) {
1624             int limit = newType.parameterCount();
1625             boolean bad = false;
1626             for (int j = 0; j < reorder.length; j++) {
1627                 int i = reorder[j];
1628                 if (i < 0 || i >= limit) {
1629                     bad = true; break;
1630                 }
1631                 Class<?> src = newType.parameterType(i);
1632                 Class<?> dst = oldType.parameterType(j);
1633                 if (src != dst)
1634                     throw newIllegalArgumentException("parameter types do not match after reorder",
1635                             oldType, newType);
1636             }
1637             if (!bad)  return;
1638         }
1639         throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
1640     }
1641 
1642     /**
1643      * Produces a method handle of the requested return type which returns the given
1644      * constant value every time it is invoked.
1645      * <p>
1646      * Before the method handle is returned, the passed-in value is converted to the requested type.
1647      * If the requested type is primitive, widening primitive conversions are attempted,
1648      * else reference conversions are attempted.
1649      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
1650      * @param type the return type of the desired method handle
1651      * @param value the value to return
1652      * @return a method handle of the given return type and no arguments, which always returns the given value
1653      * @throws NullPointerException if the {@code type} argument is null
1654      * @throws ClassCastException if the value cannot be converted to the required return type
1655      * @throws IllegalArgumentException if the given type is {@code void.class}
1656      */
1657     public static
1658     MethodHandle constant(Class<?> type, Object value) {
1659         if (type.isPrimitive()) {
1660             if (type == void.class)
1661                 throw newIllegalArgumentException("void type");
1662             Wrapper w = Wrapper.forPrimitiveType(type);
1663             return insertArguments(identity(type), 0, w.convert(value, type));
1664         } else {
1665             return identity(type).bindTo(type.cast(value));
1666         }
1667     }
1668 
1669     /**
1670      * Produces a method handle which returns its sole argument when invoked.
1671      * @param type the type of the sole parameter and return value of the desired method handle
1672      * @return a unary method handle which accepts and returns the given type
1673      * @throws NullPointerException if the argument is null
1674      * @throws IllegalArgumentException if the given type is {@code void.class}
1675      */
1676     public static
1677     MethodHandle identity(Class<?> type) {
1678         if (type == void.class)
1679             throw newIllegalArgumentException("void type");
1680         else if (type == Object.class)
1681             return ValueConversions.identity();
1682         else if (type.isPrimitive())
1683             return ValueConversions.identity(Wrapper.forPrimitiveType(type));
1684         else
1685             return MethodHandleImpl.makeReferenceIdentity(type);
1686     }
1687 
1688     /**
1689      * Provides a target method handle with one or more <em>bound arguments</em>
1690      * in advance of the method handle's invocation.
1691      * The formal parameters to the target corresponding to the bound
1692      * arguments are called <em>bound parameters</em>.
1693      * Returns a new method handle which saves away the bound arguments.
1694      * When it is invoked, it receives arguments for any non-bound parameters,
1695      * binds the saved arguments to their corresponding parameters,
1696      * and calls the original target.
1697      * <p>
1698      * The type of the new method handle will drop the types for the bound
1699      * parameters from the original target type, since the new method handle
1700      * will no longer require those arguments to be supplied by its callers.
1701      * <p>
1702      * Each given argument object must match the corresponding bound parameter type.
1703      * If a bound parameter type is a primitive, the argument object
1704      * must be a wrapper, and will be unboxed to produce the primitive value.
1705      * <p>
1706      * The {@code pos} argument selects which parameters are to be bound.
1707      * It may range between zero and <i>N-L</i> (inclusively),
1708      * where <i>N</i> is the arity of the target method handle
1709      * and <i>L</i> is the length of the values array.
1710      * @param target the method handle to invoke after the argument is inserted
1711      * @param pos where to insert the argument (zero for the first)
1712      * @param values the series of arguments to insert
1713      * @return a method handle which inserts an additional argument,
1714      *         before calling the original method handle
1715      * @throws NullPointerException if the target or the {@code values} array is null
1716      * @see MethodHandle#bindTo
1717      */
1718     public static
1719     MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
1720         int insCount = values.length;
1721         MethodType oldType = target.type();
1722         int outargs = oldType.parameterCount();
1723         int inargs  = outargs - insCount;
1724         if (inargs < 0)
1725             throw newIllegalArgumentException("too many values to insert");
1726         if (pos < 0 || pos > inargs)
1727             throw newIllegalArgumentException("no argument type to append");
1728         MethodHandle result = target;
1729         for (int i = 0; i < insCount; i++) {
1730             Object value = values[i];
1731             Class<?> ptype = oldType.parameterType(pos+i);
1732             if (ptype.isPrimitive()) {
1733                 char btype = 'I';
1734                 Wrapper w = Wrapper.forPrimitiveType(ptype);
1735                 switch (w) {
1736                 case LONG:    btype = 'J'; break;
1737                 case FLOAT:   btype = 'F'; break;
1738                 case DOUBLE:  btype = 'D'; break;
1739                 }
1740                 // perform unboxing and/or primitive conversion
1741                 value = w.convert(value, ptype);
1742                 result = result.bindArgument(pos, btype, value);
1743                 continue;
1744             }
1745             value = ptype.cast(value);  // throw CCE if needed
1746             if (pos == 0) {
1747                 result = result.bindReceiver(value);
1748             } else {
1749                 result = result.bindArgument(pos, 'L', value);
1750             }
1751         }
1752         return result;
1753     }
1754 
1755     /**
1756      * Produces a method handle which will discard some dummy arguments
1757      * before calling some other specified <i>target</i> method handle.
1758      * The type of the new method handle will be the same as the target's type,
1759      * except it will also include the dummy argument types,
1760      * at some given position.
1761      * <p>
1762      * The {@code pos} argument may range between zero and <i>N</i>,
1763      * where <i>N</i> is the arity of the target.
1764      * If {@code pos} is zero, the dummy arguments will precede
1765      * the target's real arguments; if {@code pos} is <i>N</i>
1766      * they will come after.
1767      * <p>
1768      * <b>Example:</b>
1769      * <p><blockquote><pre>
1770 import static java.lang.invoke.MethodHandles.*;
1771 import static java.lang.invoke.MethodType.*;
1772 ...
1773 MethodHandle cat = lookup().findVirtual(String.class,
1774   "concat", methodType(String.class, String.class));
1775 assertEquals("xy", (String) cat.invokeExact("x", "y"));
1776 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
1777 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
1778 assertEquals(bigType, d0.type());
1779 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
1780      * </pre></blockquote>
1781      * <p>
1782      * This method is also equivalent to the following code:
1783      * <p><blockquote><pre>
1784      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}(target, pos, valueTypes.toArray(new Class[0]))
1785      * </pre></blockquote>
1786      * @param target the method handle to invoke after the arguments are dropped
1787      * @param valueTypes the type(s) of the argument(s) to drop
1788      * @param pos position of first argument to drop (zero for the leftmost)
1789      * @return a method handle which drops arguments of the given types,
1790      *         before calling the original method handle
1791      * @throws NullPointerException if the target is null,
1792      *                              or if the {@code valueTypes} list or any of its elements is null
1793      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
1794      *                  or if {@code pos} is negative or greater than the arity of the target,
1795      *                  or if the new method handle's type would have too many parameters
1796      */
1797     public static
1798     MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
1799         MethodType oldType = target.type();  // get NPE
1800         int dropped = valueTypes.size();
1801         MethodType.checkSlotCount(dropped);
1802         if (dropped == 0)  return target;
1803         int outargs = oldType.parameterCount();
1804         int inargs  = outargs + dropped;
1805         if (pos < 0 || pos >= inargs)
1806             throw newIllegalArgumentException("no argument type to remove");
1807         ArrayList<Class<?>> ptypes = new ArrayList<>(oldType.parameterList());
1808         ptypes.addAll(pos, valueTypes);
1809         MethodType newType = MethodType.methodType(oldType.returnType(), ptypes);
1810         return target.dropArguments(newType, pos, dropped);
1811     }
1812 
1813     /**
1814      * Produces a method handle which will discard some dummy arguments
1815      * before calling some other specified <i>target</i> method handle.
1816      * The type of the new method handle will be the same as the target's type,
1817      * except it will also include the dummy argument types,
1818      * at some given position.
1819      * <p>
1820      * The {@code pos} argument may range between zero and <i>N</i>,
1821      * where <i>N</i> is the arity of the target.
1822      * If {@code pos} is zero, the dummy arguments will precede
1823      * the target's real arguments; if {@code pos} is <i>N</i>
1824      * they will come after.
1825      * <p>
1826      * <b>Example:</b>
1827      * <p><blockquote><pre>
1828 import static java.lang.invoke.MethodHandles.*;
1829 import static java.lang.invoke.MethodType.*;
1830 ...
1831 MethodHandle cat = lookup().findVirtual(String.class,
1832   "concat", methodType(String.class, String.class));
1833 assertEquals("xy", (String) cat.invokeExact("x", "y"));
1834 MethodHandle d0 = dropArguments(cat, 0, String.class);
1835 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
1836 MethodHandle d1 = dropArguments(cat, 1, String.class);
1837 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
1838 MethodHandle d2 = dropArguments(cat, 2, String.class);
1839 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
1840 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
1841 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
1842      * </pre></blockquote>
1843      * <p>
1844      * This method is also equivalent to the following code:
1845      * <p><blockquote><pre>
1846      * {@link #dropArguments(MethodHandle,int,List) dropArguments}(target, pos, Arrays.asList(valueTypes))
1847      * </pre></blockquote>
1848      * @param target the method handle to invoke after the arguments are dropped
1849      * @param valueTypes the type(s) of the argument(s) to drop
1850      * @param pos position of first argument to drop (zero for the leftmost)
1851      * @return a method handle which drops arguments of the given types,
1852      *         before calling the original method handle
1853      * @throws NullPointerException if the target is null,
1854      *                              or if the {@code valueTypes} array or any of its elements is null
1855      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
1856      *                  or if {@code pos} is negative or greater than the arity of the target,
1857      *                  or if the new method handle's type would have too many parameters
1858      */
1859     public static
1860     MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
1861         return dropArguments(target, pos, Arrays.asList(valueTypes));
1862     }
1863 
1864     /**
1865      * Adapts a target method handle by pre-processing
1866      * one or more of its arguments, each with its own unary filter function,
1867      * and then calling the target with each pre-processed argument
1868      * replaced by the result of its corresponding filter function.
1869      * <p>
1870      * The pre-processing is performed by one or more method handles,
1871      * specified in the elements of the {@code filters} array.
1872      * The first element of the filter array corresponds to the {@code pos}
1873      * argument of the target, and so on in sequence.
1874      * <p>
1875      * Null arguments in the array are treated as identity functions,
1876      * and the corresponding arguments left unchanged.
1877      * (If there are no non-null elements in the array, the original target is returned.)
1878      * Each filter is applied to the corresponding argument of the adapter.
1879      * <p>
1880      * If a filter {@code F} applies to the {@code N}th argument of
1881      * the target, then {@code F} must be a method handle which
1882      * takes exactly one argument.  The type of {@code F}'s sole argument
1883      * replaces the corresponding argument type of the target
1884      * in the resulting adapted method handle.
1885      * The return type of {@code F} must be identical to the corresponding
1886      * parameter type of the target.
1887      * <p>
1888      * It is an error if there are elements of {@code filters}
1889      * (null or not)
1890      * which do not correspond to argument positions in the target.
1891      * <b>Example:</b>
1892      * <p><blockquote><pre>
1893 import static java.lang.invoke.MethodHandles.*;
1894 import static java.lang.invoke.MethodType.*;
1895 ...
1896 MethodHandle cat = lookup().findVirtual(String.class,
1897   "concat", methodType(String.class, String.class));
1898 MethodHandle upcase = lookup().findVirtual(String.class,
1899   "toUpperCase", methodType(String.class));
1900 assertEquals("xy", (String) cat.invokeExact("x", "y"));
1901 MethodHandle f0 = filterArguments(cat, 0, upcase);
1902 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
1903 MethodHandle f1 = filterArguments(cat, 1, upcase);
1904 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
1905 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
1906 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
1907      * </pre></blockquote>
1908      * <p> Here is pseudocode for the resulting adapter:
1909      * <blockquote><pre>
1910      * V target(P... p, A[i]... a[i], B... b);
1911      * A[i] filter[i](V[i]);
1912      * T adapter(P... p, V[i]... v[i], B... b) {
1913      *   return target(p..., f[i](v[i])..., b...);
1914      * }
1915      * </pre></blockquote>
1916      *
1917      * @param target the method handle to invoke after arguments are filtered
1918      * @param pos the position of the first argument to filter
1919      * @param filters method handles to call initially on filtered arguments
1920      * @return method handle which incorporates the specified argument filtering logic
1921      * @throws NullPointerException if the target is null
1922      *                              or if the {@code filters} array is null
1923      * @throws IllegalArgumentException if a non-null element of {@code filters}
1924      *          does not match a corresponding argument type of target as described above,
1925      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}
1926      */
1927     public static
1928     MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
1929         MethodType targetType = target.type();
1930         MethodHandle adapter = target;
1931         MethodType adapterType = null;
1932         assert((adapterType = targetType) != null);
1933         int maxPos = targetType.parameterCount();
1934         if (pos + filters.length > maxPos)
1935             throw newIllegalArgumentException("too many filters");
1936         int curPos = pos-1;  // pre-incremented
1937         for (MethodHandle filter : filters) {
1938             curPos += 1;
1939             if (filter == null)  continue;  // ignore null elements of filters
1940             adapter = filterArgument(adapter, curPos, filter);
1941             assert((adapterType = adapterType.changeParameterType(curPos, filter.type().parameterType(0))) != null);
1942         }
1943         assert(adapterType.equals(adapter.type()));
1944         return adapter;
1945     }
1946 
1947     /*non-public*/ static
1948     MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
1949         MethodType targetType = target.type();
1950         MethodType filterType = filter.type();
1951         if (filterType.parameterCount() != 1
1952             || filterType.returnType() != targetType.parameterType(pos))
1953             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
1954         return MethodHandleImpl.makeCollectArguments(target, filter, pos, false);
1955     }
1956 
1957     // FIXME: Make this public in M1.
1958     /*non-public*/ static
1959     MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle collector) {
1960         MethodType targetType = target.type();
1961         MethodType filterType = collector.type();
1962         if (filterType.returnType() != void.class &&
1963             filterType.returnType() != targetType.parameterType(pos))
1964             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
1965         return MethodHandleImpl.makeCollectArguments(target, collector, pos, false);
1966     }
1967 
1968     /**
1969      * Adapts a target method handle by post-processing
1970      * its return value (if any) with a filter (another method handle).
1971      * The result of the filter is returned from the adapter.
1972      * <p>
1973      * If the target returns a value, the filter must accept that value as
1974      * its only argument.
1975      * If the target returns void, the filter must accept no arguments.
1976      * <p>
1977      * The return type of the filter
1978      * replaces the return type of the target
1979      * in the resulting adapted method handle.
1980      * The argument type of the filter (if any) must be identical to the
1981      * return type of the target.
1982      * <b>Example:</b>
1983      * <p><blockquote><pre>
1984 import static java.lang.invoke.MethodHandles.*;
1985 import static java.lang.invoke.MethodType.*;
1986 ...
1987 MethodHandle cat = lookup().findVirtual(String.class,
1988   "concat", methodType(String.class, String.class));
1989 MethodHandle length = lookup().findVirtual(String.class,
1990   "length", methodType(int.class));
1991 System.out.println((String) cat.invokeExact("x", "y")); // xy
1992 MethodHandle f0 = filterReturnValue(cat, length);
1993 System.out.println((int) f0.invokeExact("x", "y")); // 2
1994      * </pre></blockquote>
1995      * <p> Here is pseudocode for the resulting adapter:
1996      * <blockquote><pre>
1997      * V target(A...);
1998      * T filter(V);
1999      * T adapter(A... a) {
2000      *   V v = target(a...);
2001      *   return filter(v);
2002      * }
2003      * // and if the target has a void return:
2004      * void target2(A...);
2005      * T filter2();
2006      * T adapter2(A... a) {
2007      *   target2(a...);
2008      *   return filter2();
2009      * }
2010      * // and if the filter has a void return:
2011      * V target3(A...);
2012      * void filter3(V);
2013      * void adapter3(A... a) {
2014      *   V v = target3(a...);
2015      *   filter3(v);
2016      * }
2017      * </pre></blockquote>
2018      * @param target the method handle to invoke before filtering the return value
2019      * @param filter method handle to call on the return value
2020      * @return method handle which incorporates the specified return value filtering logic
2021      * @throws NullPointerException if either argument is null
2022      * @throws IllegalArgumentException if the argument list of {@code filter}
2023      *          does not match the return type of target as described above
2024      */
2025     public static
2026     MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
2027         MethodType targetType = target.type();
2028         MethodType filterType = filter.type();
2029         Class<?> rtype = targetType.returnType();
2030         int filterValues = filterType.parameterCount();
2031         if (filterValues == 0
2032                 ? (rtype != void.class)
2033                 : (rtype != filterType.parameterType(0)))
2034             throw newIllegalArgumentException("target and filter types do not match", target, filter);
2035         // result = fold( lambda(retval, arg...) { filter(retval) },
2036         //                lambda(        arg...) { target(arg...) } )
2037         return MethodHandleImpl.makeCollectArguments(filter, target, 0, false);
2038     }
2039 
2040     /**
2041      * Adapts a target method handle by pre-processing
2042      * some of its arguments, and then calling the target with
2043      * the result of the pre-processing, inserted into the original
2044      * sequence of arguments.
2045      * <p>
2046      * The pre-processing is performed by {@code combiner}, a second method handle.
2047      * Of the arguments passed to the adapter, the first {@code N} arguments
2048      * are copied to the combiner, which is then called.
2049      * (Here, {@code N} is defined as the parameter count of the combiner.)
2050      * After this, control passes to the target, with any result
2051      * from the combiner inserted before the original {@code N} incoming
2052      * arguments.
2053      * <p>
2054      * If the combiner returns a value, the first parameter type of the target
2055      * must be identical with the return type of the combiner, and the next
2056      * {@code N} parameter types of the target must exactly match the parameters
2057      * of the combiner.
2058      * <p>
2059      * If the combiner has a void return, no result will be inserted,
2060      * and the first {@code N} parameter types of the target
2061      * must exactly match the parameters of the combiner.
2062      * <p>
2063      * The resulting adapter is the same type as the target, except that the
2064      * first parameter type is dropped,
2065      * if it corresponds to the result of the combiner.
2066      * <p>
2067      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
2068      * that either the combiner or the target does not wish to receive.
2069      * If some of the incoming arguments are destined only for the combiner,
2070      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
2071      * arguments will not need to be live on the stack on entry to the
2072      * target.)
2073      * <b>Example:</b>
2074      * <p><blockquote><pre>
2075 import static java.lang.invoke.MethodHandles.*;
2076 import static java.lang.invoke.MethodType.*;
2077 ...
2078 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
2079   "println", methodType(void.class, String.class))
2080     .bindTo(System.out);
2081 MethodHandle cat = lookup().findVirtual(String.class,
2082   "concat", methodType(String.class, String.class));
2083 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
2084 MethodHandle catTrace = foldArguments(cat, trace);
2085 // also prints "boo":
2086 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
2087      * </pre></blockquote>
2088      * <p> Here is pseudocode for the resulting adapter:
2089      * <blockquote><pre>
2090      * // there are N arguments in A...
2091      * T target(V, A[N]..., B...);
2092      * V combiner(A...);
2093      * T adapter(A... a, B... b) {
2094      *   V v = combiner(a...);
2095      *   return target(v, a..., b...);
2096      * }
2097      * // and if the combiner has a void return:
2098      * T target2(A[N]..., B...);
2099      * void combiner2(A...);
2100      * T adapter2(A... a, B... b) {
2101      *   combiner2(a...);
2102      *   return target2(a..., b...);
2103      * }
2104      * </pre></blockquote>
2105      * @param target the method handle to invoke after arguments are combined
2106      * @param combiner method handle to call initially on the incoming arguments
2107      * @return method handle which incorporates the specified argument folding logic
2108      * @throws NullPointerException if either argument is null
2109      * @throws IllegalArgumentException if {@code combiner}'s return type
2110      *          is non-void and not the same as the first argument type of
2111      *          the target, or if the initial {@code N} argument types
2112      *          of the target
2113      *          (skipping one matching the {@code combiner}'s return type)
2114      *          are not identical with the argument types of {@code combiner}
2115      */
2116     public static
2117     MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
2118         int pos = 0;
2119         MethodType targetType = target.type();
2120         MethodType combinerType = combiner.type();
2121         int foldPos = pos;
2122         int foldArgs = combinerType.parameterCount();
2123         int foldVals = combinerType.returnType() == void.class ? 0 : 1;
2124         int afterInsertPos = foldPos + foldVals;
2125         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
2126         if (ok && !(combinerType.parameterList()
2127                     .equals(targetType.parameterList().subList(afterInsertPos,
2128                                                                afterInsertPos + foldArgs))))
2129             ok = false;
2130         if (ok && foldVals != 0 && !combinerType.returnType().equals(targetType.parameterType(0)))
2131             ok = false;
2132         if (!ok)
2133             throw misMatchedTypes("target and combiner types", targetType, combinerType);
2134         MethodType newType = targetType.dropParameterTypes(foldPos, afterInsertPos);
2135         return MethodHandleImpl.makeCollectArguments(target, combiner, foldPos, true);
2136     }
2137 
2138     /**
2139      * Makes a method handle which adapts a target method handle,
2140      * by guarding it with a test, a boolean-valued method handle.
2141      * If the guard fails, a fallback handle is called instead.
2142      * All three method handles must have the same corresponding
2143      * argument and return types, except that the return type
2144      * of the test must be boolean, and the test is allowed
2145      * to have fewer arguments than the other two method handles.
2146      * <p> Here is pseudocode for the resulting adapter:
2147      * <blockquote><pre>
2148      * boolean test(A...);
2149      * T target(A...,B...);
2150      * T fallback(A...,B...);
2151      * T adapter(A... a,B... b) {
2152      *   if (test(a...))
2153      *     return target(a..., b...);
2154      *   else
2155      *     return fallback(a..., b...);
2156      * }
2157      * </pre></blockquote>
2158      * Note that the test arguments ({@code a...} in the pseudocode) cannot
2159      * be modified by execution of the test, and so are passed unchanged
2160      * from the caller to the target or fallback as appropriate.
2161      * @param test method handle used for test, must return boolean
2162      * @param target method handle to call if test passes
2163      * @param fallback method handle to call if test fails
2164      * @return method handle which incorporates the specified if/then/else logic
2165      * @throws NullPointerException if any argument is null
2166      * @throws IllegalArgumentException if {@code test} does not return boolean,
2167      *          or if all three method types do not match (with the return
2168      *          type of {@code test} changed to match that of the target).
2169      */
2170     public static
2171     MethodHandle guardWithTest(MethodHandle test,
2172                                MethodHandle target,
2173                                MethodHandle fallback) {
2174         MethodType gtype = test.type();
2175         MethodType ttype = target.type();
2176         MethodType ftype = fallback.type();
2177         if (!ttype.equals(ftype))
2178             throw misMatchedTypes("target and fallback types", ttype, ftype);
2179         if (gtype.returnType() != boolean.class)
2180             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
2181         List<Class<?>> targs = ttype.parameterList();
2182         List<Class<?>> gargs = gtype.parameterList();
2183         if (!targs.equals(gargs)) {
2184             int gpc = gargs.size(), tpc = targs.size();
2185             if (gpc >= tpc || !targs.subList(0, gpc).equals(gargs))
2186                 throw misMatchedTypes("target and test types", ttype, gtype);
2187             test = dropArguments(test, gpc, targs.subList(gpc, tpc));
2188             gtype = test.type();
2189         }
2190         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
2191     }
2192 
2193     static RuntimeException misMatchedTypes(String what, MethodType t1, MethodType t2) {
2194         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
2195     }
2196 
2197     /**
2198      * Makes a method handle which adapts a target method handle,
2199      * by running it inside an exception handler.
2200      * If the target returns normally, the adapter returns that value.
2201      * If an exception matching the specified type is thrown, the fallback
2202      * handle is called instead on the exception, plus the original arguments.
2203      * <p>
2204      * The target and handler must have the same corresponding
2205      * argument and return types, except that handler may omit trailing arguments
2206      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
2207      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
2208      * <p> Here is pseudocode for the resulting adapter:
2209      * <blockquote><pre>
2210      * T target(A..., B...);
2211      * T handler(ExType, A...);
2212      * T adapter(A... a, B... b) {
2213      *   try {
2214      *     return target(a..., b...);
2215      *   } catch (ExType ex) {
2216      *     return handler(ex, a...);
2217      *   }
2218      * }
2219      * </pre></blockquote>
2220      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
2221      * be modified by execution of the target, and so are passed unchanged
2222      * from the caller to the handler, if the handler is invoked.
2223      * <p>
2224      * The target and handler must return the same type, even if the handler
2225      * always throws.  (This might happen, for instance, because the handler
2226      * is simulating a {@code finally} clause).
2227      * To create such a throwing handler, compose the handler creation logic
2228      * with {@link #throwException throwException},
2229      * in order to create a method handle of the correct return type.
2230      * @param target method handle to call
2231      * @param exType the type of exception which the handler will catch
2232      * @param handler method handle to call if a matching exception is thrown
2233      * @return method handle which incorporates the specified try/catch logic
2234      * @throws NullPointerException if any argument is null
2235      * @throws IllegalArgumentException if {@code handler} does not accept
2236      *          the given exception type, or if the method handle types do
2237      *          not match in their return types and their
2238      *          corresponding parameters
2239      */
2240     public static
2241     MethodHandle catchException(MethodHandle target,
2242                                 Class<? extends Throwable> exType,
2243                                 MethodHandle handler) {
2244         MethodType ttype = target.type();
2245         MethodType htype = handler.type();
2246         if (htype.parameterCount() < 1 ||
2247             !htype.parameterType(0).isAssignableFrom(exType))
2248             throw newIllegalArgumentException("handler does not accept exception type "+exType);
2249         if (htype.returnType() != ttype.returnType())
2250             throw misMatchedTypes("target and handler return types", ttype, htype);
2251         List<Class<?>> targs = ttype.parameterList();
2252         List<Class<?>> hargs = htype.parameterList();
2253         hargs = hargs.subList(1, hargs.size());  // omit leading parameter from handler
2254         if (!targs.equals(hargs)) {
2255             int hpc = hargs.size(), tpc = targs.size();
2256             if (hpc >= tpc || !targs.subList(0, hpc).equals(hargs))
2257                 throw misMatchedTypes("target and handler types", ttype, htype);
2258             handler = dropArguments(handler, 1+hpc, targs.subList(hpc, tpc));
2259             htype = handler.type();
2260         }
2261         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
2262     }
2263 
2264     /**
2265      * Produces a method handle which will throw exceptions of the given {@code exType}.
2266      * The method handle will accept a single argument of {@code exType},
2267      * and immediately throw it as an exception.
2268      * The method type will nominally specify a return of {@code returnType}.
2269      * The return type may be anything convenient:  It doesn't matter to the
2270      * method handle's behavior, since it will never return normally.
2271      * @param returnType the return type of the desired method handle
2272      * @param exType the parameter type of the desired method handle
2273      * @return method handle which can throw the given exceptions
2274      * @throws NullPointerException if either argument is null
2275      */
2276     public static
2277     MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
2278         if (!Throwable.class.isAssignableFrom(exType))
2279             throw new ClassCastException(exType.getName());
2280         return MethodHandleImpl.throwException(MethodType.methodType(returnType, exType));
2281     }
2282 }