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