1 /*
   2  * Copyright (c) 2008, 2016, 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 jdk.internal.org.objectweb.asm.ClassWriter;
  29 import jdk.internal.org.objectweb.asm.Opcodes;
  30 import jdk.internal.reflect.CallerSensitive;
  31 import jdk.internal.reflect.Reflection;
  32 import sun.invoke.util.ValueConversions;
  33 import sun.invoke.util.VerifyAccess;
  34 import sun.invoke.util.Wrapper;
  35 import sun.reflect.misc.ReflectUtil;
  36 import sun.security.util.SecurityConstants;
  37 
  38 import java.lang.invoke.LambdaForm.BasicType;
  39 import java.lang.reflect.Constructor;
  40 import java.lang.reflect.Field;
  41 import java.lang.reflect.Member;
  42 import java.lang.reflect.Method;
  43 import java.lang.reflect.Modifier;
  44 import java.lang.reflect.ReflectPermission;
  45 import java.nio.ByteOrder;
  46 import java.security.AccessController;
  47 import java.security.PrivilegedAction;
  48 import java.util.ArrayList;
  49 import java.util.Arrays;
  50 import java.util.BitSet;
  51 import java.util.Iterator;
  52 import java.util.List;
  53 import java.util.Objects;
  54 import java.util.concurrent.ConcurrentHashMap;
  55 import java.util.stream.Collectors;
  56 import java.util.stream.Stream;
  57 
  58 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  59 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  60 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  61 import static java.lang.invoke.MethodType.methodType;
  62 
  63 /**
  64  * This class consists exclusively of static methods that operate on or return
  65  * method handles. They fall into several categories:
  66  * <ul>
  67  * <li>Lookup methods which help create method handles for methods and fields.
  68  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  69  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  70  * </ul>
  71  *
  72  * @author John Rose, JSR 292 EG
  73  * @since 1.7
  74  */
  75 public class MethodHandles {
  76 
  77     private MethodHandles() { }  // do not instantiate
  78 
  79     private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  80 
  81     // See IMPL_LOOKUP below.
  82 
  83     //// Method handle creation from ordinary methods.
  84 
  85     /**
  86      * Returns a {@link Lookup lookup object} with
  87      * full capabilities to emulate all supported bytecode behaviors of the caller.
  88      * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller.
  89      * Factory methods on the lookup object can create
  90      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
  91      * for any member that the caller has access to via bytecodes,
  92      * including protected and private fields and methods.
  93      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
  94      * Do not store it in place where untrusted code can access it.
  95      * <p>
  96      * This method is caller sensitive, which means that it may return different
  97      * values to different callers.
  98      * <p>
  99      * For any given caller class {@code C}, the lookup object returned by this call
 100      * has equivalent capabilities to any lookup object
 101      * supplied by the JVM to the bootstrap method of an
 102      * <a href="package-summary.html#indyinsn">invokedynamic instruction</a>
 103      * executing in the same caller class {@code C}.
 104      * @return a lookup object for the caller of this method, with private access
 105      */
 106     @CallerSensitive
 107     public static Lookup lookup() {
 108         return new Lookup(Reflection.getCallerClass());
 109     }
 110 
 111     /**
 112      * Returns a {@link Lookup lookup object} which is trusted minimally.
 113      * It can only be used to create method handles to public members in
 114      * public classes in packages that are exported unconditionally.
 115      * <p>
 116      * For now, the {@linkplain Lookup#lookupClass lookup class} of this lookup
 117      * object is in an unnamed module.
 118      * Consequently, the lookup context of this lookup object will be the bootstrap
 119      * class loader, which means it cannot find user classes.
 120      *
 121      * <p style="font-size:smaller;">
 122      * <em>Discussion:</em>
 123      * The lookup class can be changed to any other class {@code C} using an expression of the form
 124      * {@link Lookup#in publicLookup().in(C.class)}.
 125      * but may change the lookup context by virtue of changing the class loader.
 126      * A public lookup object is always subject to
 127      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 128      * Also, it cannot access
 129      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 130      * @return a lookup object which is trusted minimally
 131      */
 132     public static Lookup publicLookup() {
 133         // During VM startup then only classes in the java.base module can be
 134         // loaded and linked. This is because java.base exports aren't setup until
 135         // the module system is initialized, hence types in the unnamed module
 136         // (or any named module) can't link to java/lang/Object.
 137         if (!jdk.internal.misc.VM.isModuleSystemInited()) {
 138             return new Lookup(Object.class, Lookup.PUBLIC);
 139         } else {
 140             return LookupHelper.PUBLIC_LOOKUP;
 141         }
 142     }
 143 
 144     /**
 145      * Performs an unchecked "crack" of a
 146      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 147      * The result is as if the user had obtained a lookup object capable enough
 148      * to crack the target method handle, called
 149      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 150      * on the target to obtain its symbolic reference, and then called
 151      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 152      * to resolve the symbolic reference to a member.
 153      * <p>
 154      * If there is a security manager, its {@code checkPermission} method
 155      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 156      * @param <T> the desired type of the result, either {@link Member} or a subtype
 157      * @param target a direct method handle to crack into symbolic reference components
 158      * @param expected a class object representing the desired result type {@code T}
 159      * @return a reference to the method, constructor, or field object
 160      * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
 161      * @exception NullPointerException if either argument is {@code null}
 162      * @exception IllegalArgumentException if the target is not a direct method handle
 163      * @exception ClassCastException if the member is not of the expected type
 164      * @since 1.8
 165      */
 166     public static <T extends Member> T
 167     reflectAs(Class<T> expected, MethodHandle target) {
 168         SecurityManager smgr = System.getSecurityManager();
 169         if (smgr != null)  smgr.checkPermission(ACCESS_PERMISSION);
 170         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 171         return lookup.revealDirect(target).reflectAs(expected, lookup);
 172     }
 173     // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
 174     private static final java.security.Permission ACCESS_PERMISSION =
 175         new ReflectPermission("suppressAccessChecks");
 176 
 177     /**
 178      * A <em>lookup object</em> is a factory for creating method handles,
 179      * when the creation requires access checking.
 180      * Method handles do not perform
 181      * access checks when they are called, but rather when they are created.
 182      * Therefore, method handle access
 183      * restrictions must be enforced when a method handle is created.
 184      * The caller class against which those restrictions are enforced
 185      * is known as the {@linkplain #lookupClass lookup class}.
 186      * <p>
 187      * A lookup class which needs to create method handles will call
 188      * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself.
 189      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 190      * determined, and securely stored in the {@code Lookup} object.
 191      * The lookup class (or its delegates) may then use factory methods
 192      * on the {@code Lookup} object to create method handles for access-checked members.
 193      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 194      * even private ones.
 195      *
 196      * <h1><a name="lookups"></a>Lookup Factory Methods</h1>
 197      * The factory methods on a {@code Lookup} object correspond to all major
 198      * use cases for methods, constructors, and fields.
 199      * Each method handle created by a factory method is the functional
 200      * equivalent of a particular <em>bytecode behavior</em>.
 201      * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
 202      * Here is a summary of the correspondence between these factory methods and
 203      * the behavior of the resulting method handles:
 204      * <table border=1 cellpadding=5 summary="lookup method behaviors">
 205      * <tr>
 206      *     <th><a name="equiv"></a>lookup expression</th>
 207      *     <th>member</th>
 208      *     <th>bytecode behavior</th>
 209      * </tr>
 210      * <tr>
 211      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td>
 212      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 213      * </tr>
 214      * <tr>
 215      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td>
 216      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
 217      * </tr>
 218      * <tr>
 219      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td>
 220      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 221      * </tr>
 222      * <tr>
 223      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td>
 224      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 225      * </tr>
 226      * <tr>
 227      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td>
 228      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 229      * </tr>
 230      * <tr>
 231      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td>
 232      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 233      * </tr>
 234      * <tr>
 235      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td>
 236      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 237      * </tr>
 238      * <tr>
 239      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td>
 240      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 241      * </tr>
 242      * <tr>
 243      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td>
 244      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 245      * </tr>
 246      * <tr>
 247      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td>
 248      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 249      * </tr>
 250      * <tr>
 251      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
 252      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 253      * </tr>
 254      * <tr>
 255      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td>
 256      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 257      * </tr>
 258      * <tr>
 259      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
 260      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 261      * </tr>
 262      * <tr>
 263      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</td>
 264      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 265      * </tr>
 266      * </table>
 267      *
 268      * Here, the type {@code C} is the class or interface being searched for a member,
 269      * documented as a parameter named {@code refc} in the lookup methods.
 270      * The method type {@code MT} is composed from the return type {@code T}
 271      * and the sequence of argument types {@code A*}.
 272      * The constructor also has a sequence of argument types {@code A*} and
 273      * is deemed to return the newly-created object of type {@code C}.
 274      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 275      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 276      * if it is present, it is always the leading argument to the method handle invocation.
 277      * (In the case of some {@code protected} members, {@code this} may be
 278      * restricted in type to the lookup class; see below.)
 279      * The name {@code arg} stands for all the other method handle arguments.
 280      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 281      * stands for a null reference if the accessed method or field is static,
 282      * and {@code this} otherwise.
 283      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 284      * for reflective objects corresponding to the given members.
 285      * <p>
 286      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 287      * as if by {@code ldc CONSTANT_Class}.
 288      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 289      * <p>
 290      * In cases where the given member is of variable arity (i.e., a method or constructor)
 291      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 292      * In all other cases, the returned method handle will be of fixed arity.
 293      * <p style="font-size:smaller;">
 294      * <em>Discussion:</em>
 295      * The equivalence between looked-up method handles and underlying
 296      * class members and bytecode behaviors
 297      * can break down in a few ways:
 298      * <ul style="font-size:smaller;">
 299      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 300      * the lookup can still succeed, even when there is no equivalent
 301      * Java expression or bytecoded constant.
 302      * <li>Likewise, if {@code T} or {@code MT}
 303      * is not symbolically accessible from the lookup class's loader,
 304      * the lookup can still succeed.
 305      * For example, lookups for {@code MethodHandle.invokeExact} and
 306      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 307      * <li>If there is a security manager installed, it can forbid the lookup
 308      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 309      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 310      * constant is not subject to security manager checks.
 311      * <li>If the looked-up method has a
 312      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 313      * the method handle creation may fail, due to the method handle
 314      * type having too many parameters.
 315      * </ul>
 316      *
 317      * <h1><a name="access"></a>Access checking</h1>
 318      * Access checks are applied in the factory methods of {@code Lookup},
 319      * when a method handle is created.
 320      * This is a key difference from the Core Reflection API, since
 321      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 322      * performs access checking against every caller, on every call.
 323      * <p>
 324      * All access checks start from a {@code Lookup} object, which
 325      * compares its recorded lookup class against all requests to
 326      * create method handles.
 327      * A single {@code Lookup} object can be used to create any number
 328      * of access-checked method handles, all checked against a single
 329      * lookup class.
 330      * <p>
 331      * A {@code Lookup} object can be shared with other trusted code,
 332      * such as a metaobject protocol.
 333      * A shared {@code Lookup} object delegates the capability
 334      * to create method handles on private members of the lookup class.
 335      * Even if privileged code uses the {@code Lookup} object,
 336      * the access checking is confined to the privileges of the
 337      * original lookup class.
 338      * <p>
 339      * A lookup can fail, because
 340      * the containing class is not accessible to the lookup class, or
 341      * because the desired class member is missing, or because the
 342      * desired class member is not accessible to the lookup class, or
 343      * because the lookup object is not trusted enough to access the member.
 344      * In any of these cases, a {@code ReflectiveOperationException} will be
 345      * thrown from the attempted lookup.  The exact class will be one of
 346      * the following:
 347      * <ul>
 348      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 349      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 350      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 351      * </ul>
 352      * <p>
 353      * In general, the conditions under which a method handle may be
 354      * looked up for a method {@code M} are no more restrictive than the conditions
 355      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 356      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 357      * a method handle lookup will generally raise a corresponding
 358      * checked exception, such as {@code NoSuchMethodException}.
 359      * And the effect of invoking the method handle resulting from the lookup
 360      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 361      * to executing the compiled, verified, and resolved call to {@code M}.
 362      * The same point is true of fields and constructors.
 363      * <p style="font-size:smaller;">
 364      * <em>Discussion:</em>
 365      * Access checks only apply to named and reflected methods,
 366      * constructors, and fields.
 367      * Other method handle creation methods, such as
 368      * {@link MethodHandle#asType MethodHandle.asType},
 369      * do not require any access checks, and are used
 370      * independently of any {@code Lookup} object.
 371      * <p>
 372      * If the desired member is {@code protected}, the usual JVM rules apply,
 373      * including the requirement that the lookup class must be either be in the
 374      * same package as the desired member, or must inherit that member.
 375      * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.)
 376      * In addition, if the desired member is a non-static field or method
 377      * in a different package, the resulting method handle may only be applied
 378      * to objects of the lookup class or one of its subclasses.
 379      * This requirement is enforced by narrowing the type of the leading
 380      * {@code this} parameter from {@code C}
 381      * (which will necessarily be a superclass of the lookup class)
 382      * to the lookup class itself.
 383      * <p>
 384      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 385      * that the receiver argument must match both the resolved method <em>and</em>
 386      * the current class.  Again, this requirement is enforced by narrowing the
 387      * type of the leading parameter to the resulting method handle.
 388      * (See the Java Virtual Machine Specification, section 4.10.1.9.)
 389      * <p>
 390      * The JVM represents constructors and static initializer blocks as internal methods
 391      * with special names ({@code "<init>"} and {@code "<clinit>"}).
 392      * The internal syntax of invocation instructions allows them to refer to such internal
 393      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 394      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 395      * <p>
 396      * In some cases, access between nested classes is obtained by the Java compiler by creating
 397      * an wrapper method to access a private method of another class
 398      * in the same top-level declaration.
 399      * For example, a nested class {@code C.D}
 400      * can access private members within other related classes such as
 401      * {@code C}, {@code C.D.E}, or {@code C.B},
 402      * but the Java compiler may need to generate wrapper methods in
 403      * those related classes.  In such cases, a {@code Lookup} object on
 404      * {@code C.E} would be unable to those private members.
 405      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 406      * which can transform a lookup on {@code C.E} into one on any of those other
 407      * classes, without special elevation of privilege.
 408      * <p>
 409      * The accesses permitted to a given lookup object may be limited,
 410      * according to its set of {@link #lookupModes lookupModes},
 411      * to a subset of members normally accessible to the lookup class.
 412      * For example, the {@link MethodHandles#publicLookup publicLookup}
 413      * method produces a lookup object which is only allowed to access
 414      * public members in public classes of exported packages.
 415      * The caller sensitive method {@link MethodHandles#lookup lookup}
 416      * produces a lookup object with full capabilities relative to
 417      * its caller class, to emulate all supported bytecode behaviors.
 418      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 419      * with fewer access modes than the original lookup object.
 420      *
 421      * <p style="font-size:smaller;">
 422      * <a name="privacc"></a>
 423      * <em>Discussion of private access:</em>
 424      * We say that a lookup has <em>private access</em>
 425      * if its {@linkplain #lookupModes lookup modes}
 426      * include the possibility of accessing {@code private} members.
 427      * As documented in the relevant methods elsewhere,
 428      * only lookups with private access possess the following capabilities:
 429      * <ul style="font-size:smaller;">
 430      * <li>access private fields, methods, and constructors of the lookup class
 431      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 432      *     such as {@code Class.forName}
 433      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 434      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 435      *     for classes accessible to the lookup class
 436      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 437      *     within the same package member
 438      * </ul>
 439      * <p style="font-size:smaller;">
 440      * Each of these permissions is a consequence of the fact that a lookup object
 441      * with private access can be securely traced back to an originating class,
 442      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 443      * can be reliably determined and emulated by method handles.
 444      *
 445      * <h1><a name="secmgr"></a>Security manager interactions</h1>
 446      * Although bytecode instructions can only refer to classes in
 447      * a related class loader, this API can search for methods in any
 448      * class, as long as a reference to its {@code Class} object is
 449      * available.  Such cross-loader references are also possible with the
 450      * Core Reflection API, and are impossible to bytecode instructions
 451      * such as {@code invokestatic} or {@code getfield}.
 452      * There is a {@linkplain java.lang.SecurityManager security manager API}
 453      * to allow applications to check such cross-loader references.
 454      * These checks apply to both the {@code MethodHandles.Lookup} API
 455      * and the Core Reflection API
 456      * (as found on {@link java.lang.Class Class}).
 457      * <p>
 458      * If a security manager is present, member and class lookups are subject to
 459      * additional checks.
 460      * From one to three calls are made to the security manager.
 461      * Any of these calls can refuse access by throwing a
 462      * {@link java.lang.SecurityException SecurityException}.
 463      * Define {@code smgr} as the security manager,
 464      * {@code lookc} as the lookup class of the current lookup object,
 465      * {@code refc} as the containing class in which the member
 466      * is being sought, and {@code defc} as the class in which the
 467      * member is actually defined.
 468      * (If a class or other type is being accessed,
 469      * the {@code refc} and {@code defc} values are the class itself.)
 470      * The value {@code lookc} is defined as <em>not present</em>
 471      * if the current lookup object does not have
 472      * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 473      * The calls are made according to the following rules:
 474      * <ul>
 475      * <li><b>Step 1:</b>
 476      *     If {@code lookc} is not present, or if its class loader is not
 477      *     the same as or an ancestor of the class loader of {@code refc},
 478      *     then {@link SecurityManager#checkPackageAccess
 479      *     smgr.checkPackageAccess(refcPkg)} is called,
 480      *     where {@code refcPkg} is the package of {@code refc}.
 481      * <li><b>Step 2a:</b>
 482      *     If the retrieved member is not public and
 483      *     {@code lookc} is not present, then
 484      *     {@link SecurityManager#checkPermission smgr.checkPermission}
 485      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
 486      * <li><b>Step 2b:</b>
 487      *     If the retrieved class has a {@code null} class loader,
 488      *     and {@code lookc} is not present, then
 489      *     {@link SecurityManager#checkPermission smgr.checkPermission}
 490      *     with {@code RuntimePermission("getClassLoader")} is called.
 491      * <li><b>Step 3:</b>
 492      *     If the retrieved member is not public,
 493      *     and if {@code lookc} is not present,
 494      *     and if {@code defc} and {@code refc} are different,
 495      *     then {@link SecurityManager#checkPackageAccess
 496      *     smgr.checkPackageAccess(defcPkg)} is called,
 497      *     where {@code defcPkg} is the package of {@code defc}.
 498      * </ul>
 499      * Security checks are performed after other access checks have passed.
 500      * Therefore, the above rules presuppose a member or class that is public,
 501      * or else that is being accessed from a lookup class that has
 502      * rights to access the member or class.
 503      *
 504      * <h1><a name="callsens"></a>Caller sensitive methods</h1>
 505      * A small number of Java methods have a special property called caller sensitivity.
 506      * A <em>caller-sensitive</em> method can behave differently depending on the
 507      * identity of its immediate caller.
 508      * <p>
 509      * If a method handle for a caller-sensitive method is requested,
 510      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
 511      * but they take account of the lookup class in a special way.
 512      * The resulting method handle behaves as if it were called
 513      * from an instruction contained in the lookup class,
 514      * so that the caller-sensitive method detects the lookup class.
 515      * (By contrast, the invoker of the method handle is disregarded.)
 516      * Thus, in the case of caller-sensitive methods,
 517      * different lookup classes may give rise to
 518      * differently behaving method handles.
 519      * <p>
 520      * In cases where the lookup object is
 521      * {@link MethodHandles#publicLookup() publicLookup()},
 522      * or some other lookup object without
 523      * <a href="MethodHandles.Lookup.html#privacc">private access</a>,
 524      * the lookup class is disregarded.
 525      * In such cases, no caller-sensitive method handle can be created,
 526      * access is forbidden, and the lookup fails with an
 527      * {@code IllegalAccessException}.
 528      * <p style="font-size:smaller;">
 529      * <em>Discussion:</em>
 530      * For example, the caller-sensitive method
 531      * {@link java.lang.Class#forName(String) Class.forName(x)}
 532      * can return varying classes or throw varying exceptions,
 533      * depending on the class loader of the class that calls it.
 534      * A public lookup of {@code Class.forName} will fail, because
 535      * there is no reasonable way to determine its bytecode behavior.
 536      * <p style="font-size:smaller;">
 537      * If an application caches method handles for broad sharing,
 538      * it should use {@code publicLookup()} to create them.
 539      * If there is a lookup of {@code Class.forName}, it will fail,
 540      * and the application must take appropriate action in that case.
 541      * It may be that a later lookup, perhaps during the invocation of a
 542      * bootstrap method, can incorporate the specific identity
 543      * of the caller, making the method accessible.
 544      * <p style="font-size:smaller;">
 545      * The function {@code MethodHandles.lookup} is caller sensitive
 546      * so that there can be a secure foundation for lookups.
 547      * Nearly all other methods in the JSR 292 API rely on lookup
 548      * objects to check access requests.
 549      */
 550     public static final
 551     class Lookup {
 552         /** The class on behalf of whom the lookup is being performed. */
 553         private final Class<?> lookupClass;
 554 
 555         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
 556         private final int allowedModes;
 557 
 558         /** A single-bit mask representing {@code public} access,
 559          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 560          *  The value, {@code 0x01}, happens to be the same as the value of the
 561          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
 562          */
 563         public static final int PUBLIC = Modifier.PUBLIC;
 564 
 565         /** A single-bit mask representing {@code private} access,
 566          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 567          *  The value, {@code 0x02}, happens to be the same as the value of the
 568          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
 569          */
 570         public static final int PRIVATE = Modifier.PRIVATE;
 571 
 572         /** A single-bit mask representing {@code protected} access,
 573          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 574          *  The value, {@code 0x04}, happens to be the same as the value of the
 575          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
 576          */
 577         public static final int PROTECTED = Modifier.PROTECTED;
 578 
 579         /** A single-bit mask representing {@code package} access (default access),
 580          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 581          *  The value is {@code 0x08}, which does not correspond meaningfully to
 582          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
 583          */
 584         public static final int PACKAGE = Modifier.STATIC;
 585 
 586         /** A single-bit mask representing {@code module} access (default access),
 587          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 588          *  The value is {@code 0x10}, which does not correspond meaningfully to
 589          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
 590          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
 591          *  with this lookup mode can access all public types in the module of the
 592          *  lookup class and public types in packages exported by other modules
 593          *  to the module of the lookup class.
 594          *  @since 9
 595          */
 596         public static final int MODULE = PACKAGE << 1;
 597 
 598         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE);
 599         private static final int TRUSTED   = -1;
 600 
 601         private static int fixmods(int mods) {
 602             mods &= (ALL_MODES - PACKAGE - MODULE);
 603             return (mods != 0) ? mods : (PACKAGE | MODULE);
 604         }
 605 
 606         /** Tells which class is performing the lookup.  It is this class against
 607          *  which checks are performed for visibility and access permissions.
 608          *  <p>
 609          *  The class implies a maximum level of access permission,
 610          *  but the permissions may be additionally limited by the bitmask
 611          *  {@link #lookupModes lookupModes}, which controls whether non-public members
 612          *  can be accessed.
 613          *  @return the lookup class, on behalf of which this lookup object finds members
 614          */
 615         public Class<?> lookupClass() {
 616             return lookupClass;
 617         }
 618 
 619         // This is just for calling out to MethodHandleImpl.
 620         private Class<?> lookupClassOrNull() {
 621             return (allowedModes == TRUSTED) ? null : lookupClass;
 622         }
 623 
 624         /** Tells which access-protection classes of members this lookup object can produce.
 625          *  The result is a bit-mask of the bits
 626          *  {@linkplain #PUBLIC PUBLIC (0x01)},
 627          *  {@linkplain #PRIVATE PRIVATE (0x02)},
 628          *  {@linkplain #PROTECTED PROTECTED (0x04)},
 629          *  {@linkplain #PACKAGE PACKAGE (0x08)},
 630          *  and {@linkplain #MODULE MODULE (0x10)}.
 631          *  <p>
 632          *  A freshly-created lookup object
 633          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
 634          *  has all possible bits set, since the caller class can access all its own members,
 635          *  all public types in the caller's module, and all public types in packages exported
 636          *  by other modules to the caller's module.
 637          *  A lookup object on a new lookup class
 638          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
 639          *  may have some mode bits set to zero.
 640          *  The purpose of this is to restrict access via the new lookup object,
 641          *  so that it can access only names which can be reached by the original
 642          *  lookup object, and also by the new lookup class.
 643          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
 644          */
 645         public int lookupModes() {
 646             return allowedModes & ALL_MODES;
 647         }
 648 
 649         /** Embody the current class (the lookupClass) as a lookup class
 650          * for method handle creation.
 651          * Must be called by from a method in this package,
 652          * which in turn is called by a method not in this package.
 653          */
 654         Lookup(Class<?> lookupClass) {
 655             this(lookupClass, ALL_MODES);
 656             // make sure we haven't accidentally picked up a privileged class:
 657             checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
 658         }
 659 
 660         private Lookup(Class<?> lookupClass, int allowedModes) {
 661             this.lookupClass = lookupClass;
 662             this.allowedModes = allowedModes;
 663         }
 664 
 665         /**
 666          * Creates a lookup on the specified new lookup class.
 667          * The resulting object will report the specified
 668          * class as its own {@link #lookupClass lookupClass}.
 669          * <p>
 670          * However, the resulting {@code Lookup} object is guaranteed
 671          * to have no more access capabilities than the original.
 672          * In particular, access capabilities can be lost as follows:<ul>
 673          * <li>If the lookup class for this {@code Lookup} is not in a named module,
 674          * and the new lookup class is in a named module {@code M}, then no members in
 675          * {@code M}'s non-exported packages will be accessible.
 676          * <li>If the lookup for this {@code Lookup} is in a named module, and the
 677          * new lookup class is in a different module {@code M}, then no members, not even
 678          * public members in {@code M}'s exported packages, will be accessible.
 679          * <li>If the new lookup class differs from the old one,
 680          * protected members will not be accessible by virtue of inheritance.
 681          * (Protected members may continue to be accessible because of package sharing.)
 682          * <li>If the new lookup class is in a different package
 683          * than the old one, protected and default (package) members will not be accessible.
 684          * <li>If the new lookup class is not within the same package member
 685          * as the old one, private members will not be accessible.
 686          * <li>If the new lookup class is not accessible to the old lookup class,
 687          * then no members, not even public members, will be accessible.
 688          * (In all other cases, public members will continue to be accessible.)
 689          * </ul>
 690          * <p>
 691          * The resulting lookup's capabilities for loading classes
 692          * (used during {@link #findClass} invocations)
 693          * are determined by the lookup class' loader,
 694          * which may change due to this operation.
 695          *
 696          * @param requestedLookupClass the desired lookup class for the new lookup object
 697          * @return a lookup object which reports the desired lookup class
 698          * @throws NullPointerException if the argument is null
 699          */
 700         public Lookup in(Class<?> requestedLookupClass) {
 701             Objects.requireNonNull(requestedLookupClass);
 702             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
 703                 return new Lookup(requestedLookupClass, ALL_MODES);
 704             if (requestedLookupClass == this.lookupClass)
 705                 return this;  // keep same capabilities
 706 
 707             int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
 708             if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) {
 709                 // Allowed to teleport from an unnamed to a named module but resulting
 710                 // Lookup has no access to module private members
 711                 if (this.lookupClass.getModule().isNamed()) {
 712                     newModes = 0;
 713                 } else {
 714                     newModes &= ~MODULE;
 715                 }
 716             }
 717             if ((newModes & PACKAGE) != 0
 718                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
 719                 newModes &= ~(PACKAGE|PRIVATE);
 720             }
 721             // Allow nestmate lookups to be created without special privilege:
 722             if ((newModes & PRIVATE) != 0
 723                 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
 724                 newModes &= ~PRIVATE;
 725             }
 726             if ((newModes & PUBLIC) != 0
 727                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
 728                 // The requested class it not accessible from the lookup class.
 729                 // No permissions.
 730                 newModes = 0;
 731             }
 732 
 733             checkUnprivilegedlookupClass(requestedLookupClass, newModes);
 734             return new Lookup(requestedLookupClass, newModes);
 735         }
 736 
 737         // Make sure outer class is initialized first.
 738         static { IMPL_NAMES.getClass(); }
 739 
 740         /** Package-private version of lookup which is trusted. */
 741         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
 742 
 743         private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) {
 744             String name = lookupClass.getName();
 745             if (name.startsWith("java.lang.invoke."))
 746                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
 747 
 748             // For caller-sensitive MethodHandles.lookup() disallow lookup from
 749             // restricted packages.  This a fragile and blunt approach.
 750             // TODO replace with a more formal and less fragile mechanism
 751             // that does not bluntly restrict classes under packages within
 752             // java.base from looking up MethodHandles or VarHandles.
 753             if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) {
 754                 if ((name.startsWith("java.") && !name.startsWith("java.util.concurrent.")) ||
 755                         (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) {
 756                     throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
 757                 }
 758             }
 759         }
 760 
 761         /**
 762          * Displays the name of the class from which lookups are to be made.
 763          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
 764          * If there are restrictions on the access permitted to this lookup,
 765          * this is indicated by adding a suffix to the class name, consisting
 766          * of a slash and a keyword.  The keyword represents the strongest
 767          * allowed access, and is chosen as follows:
 768          * <ul>
 769          * <li>If no access is allowed, the suffix is "/noaccess".
 770          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
 771          * <li>If only public and module access are allowed, the suffix is "/module".
 772          * <li>If only public, module and package access are allowed, the suffix is "/package".
 773          * <li>If only public, module, package, and private access are allowed, the suffix is "/private".
 774          * </ul>
 775          * If none of the above cases apply, it is the case that full
 776          * access (public, module, package, private, and protected) is allowed.
 777          * In this case, no suffix is added.
 778          * This is true only of an object obtained originally from
 779          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
 780          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
 781          * always have restricted access, and will display a suffix.
 782          * <p>
 783          * (It may seem strange that protected access should be
 784          * stronger than private access.  Viewed independently from
 785          * package access, protected access is the first to be lost,
 786          * because it requires a direct subclass relationship between
 787          * caller and callee.)
 788          * @see #in
 789          */
 790         @Override
 791         public String toString() {
 792             String cname = lookupClass.getName();
 793             switch (allowedModes) {
 794             case 0:  // no privileges
 795                 return cname + "/noaccess";
 796             case PUBLIC:
 797                 return cname + "/public";
 798             case PUBLIC|MODULE:
 799                 return cname + "/module";
 800             case PUBLIC|MODULE|PACKAGE:
 801                 return cname + "/package";
 802             case ALL_MODES & ~PROTECTED:
 803                 return cname + "/private";
 804             case ALL_MODES:
 805                 return cname;
 806             case TRUSTED:
 807                 return "/trusted";  // internal only; not exported
 808             default:  // Should not happen, but it's a bitfield...
 809                 cname = cname + "/" + Integer.toHexString(allowedModes);
 810                 assert(false) : cname;
 811                 return cname;
 812             }
 813         }
 814 
 815         /**
 816          * Produces a method handle for a static method.
 817          * The type of the method handle will be that of the method.
 818          * (Since static methods do not take receivers, there is no
 819          * additional receiver argument inserted into the method handle type,
 820          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
 821          * The method and all its argument types must be accessible to the lookup object.
 822          * <p>
 823          * The returned method handle will have
 824          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 825          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 826          * <p>
 827          * If the returned method handle is invoked, the method's class will
 828          * be initialized, if it has not already been initialized.
 829          * <p><b>Example:</b>
 830          * <blockquote><pre>{@code
 831 import static java.lang.invoke.MethodHandles.*;
 832 import static java.lang.invoke.MethodType.*;
 833 ...
 834 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
 835   "asList", methodType(List.class, Object[].class));
 836 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
 837          * }</pre></blockquote>
 838          * @param refc the class from which the method is accessed
 839          * @param name the name of the method
 840          * @param type the type of the method
 841          * @return the desired method handle
 842          * @throws NoSuchMethodException if the method does not exist
 843          * @throws IllegalAccessException if access checking fails,
 844          *                                or if the method is not {@code static},
 845          *                                or if the method's variable arity modifier bit
 846          *                                is set and {@code asVarargsCollector} fails
 847          * @exception SecurityException if a security manager is present and it
 848          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 849          * @throws NullPointerException if any argument is null
 850          */
 851         public
 852         MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 853             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
 854             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method));
 855         }
 856 
 857         /**
 858          * Produces a method handle for a virtual method.
 859          * The type of the method handle will be that of the method,
 860          * with the receiver type (usually {@code refc}) prepended.
 861          * The method and all its argument types must be accessible to the lookup object.
 862          * <p>
 863          * When called, the handle will treat the first argument as a receiver
 864          * and dispatch on the receiver's type to determine which method
 865          * implementation to enter.
 866          * (The dispatching action is identical with that performed by an
 867          * {@code invokevirtual} or {@code invokeinterface} instruction.)
 868          * <p>
 869          * The first argument will be of type {@code refc} if the lookup
 870          * class has full privileges to access the member.  Otherwise
 871          * the member must be {@code protected} and the first argument
 872          * will be restricted in type to the lookup class.
 873          * <p>
 874          * The returned method handle will have
 875          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 876          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 877          * <p>
 878          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
 879          * instructions and method handles produced by {@code findVirtual},
 880          * if the class is {@code MethodHandle} and the name string is
 881          * {@code invokeExact} or {@code invoke}, the resulting
 882          * method handle is equivalent to one produced by
 883          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
 884          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
 885          * with the same {@code type} argument.
 886          * <p>
 887          * If the class is {@code VarHandle} and the name string corresponds to
 888          * the name of a signature-polymorphic access mode method, the resulting
 889          * method handle is equivalent to one produced by
 890          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
 891          * the access mode corresponding to the name string and with the same
 892          * {@code type} arguments.
 893          * <p>
 894          * <b>Example:</b>
 895          * <blockquote><pre>{@code
 896 import static java.lang.invoke.MethodHandles.*;
 897 import static java.lang.invoke.MethodType.*;
 898 ...
 899 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
 900   "concat", methodType(String.class, String.class));
 901 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
 902   "hashCode", methodType(int.class));
 903 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
 904   "hashCode", methodType(int.class));
 905 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
 906 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
 907 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
 908 // interface method:
 909 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
 910   "subSequence", methodType(CharSequence.class, int.class, int.class));
 911 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
 912 // constructor "internal method" must be accessed differently:
 913 MethodType MT_newString = methodType(void.class); //()V for new String()
 914 try { assertEquals("impossible", lookup()
 915         .findVirtual(String.class, "<init>", MT_newString));
 916  } catch (NoSuchMethodException ex) { } // OK
 917 MethodHandle MH_newString = publicLookup()
 918   .findConstructor(String.class, MT_newString);
 919 assertEquals("", (String) MH_newString.invokeExact());
 920          * }</pre></blockquote>
 921          *
 922          * @param refc the class or interface from which the method is accessed
 923          * @param name the name of the method
 924          * @param type the type of the method, with the receiver argument omitted
 925          * @return the desired method handle
 926          * @throws NoSuchMethodException if the method does not exist
 927          * @throws IllegalAccessException if access checking fails,
 928          *                                or if the method is {@code static},
 929          *                                or if the method is {@code private} method of interface,
 930          *                                or if the method's variable arity modifier bit
 931          *                                is set and {@code asVarargsCollector} fails
 932          * @exception SecurityException if a security manager is present and it
 933          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 934          * @throws NullPointerException if any argument is null
 935          */
 936         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 937             if (refc == MethodHandle.class) {
 938                 MethodHandle mh = findVirtualForMH(name, type);
 939                 if (mh != null)  return mh;
 940             } else if (refc == VarHandle.class) {
 941                 MethodHandle mh = findVirtualForVH(name, type);
 942                 if (mh != null)  return mh;
 943             }
 944             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
 945             MemberName method = resolveOrFail(refKind, refc, name, type);
 946             return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
 947         }
 948         private MethodHandle findVirtualForMH(String name, MethodType type) {
 949             // these names require special lookups because of the implicit MethodType argument
 950             if ("invoke".equals(name))
 951                 return invoker(type);
 952             if ("invokeExact".equals(name))
 953                 return exactInvoker(type);
 954             if ("invokeBasic".equals(name))
 955                 return basicInvoker(type);
 956             assert(!MemberName.isMethodHandleInvokeName(name));
 957             return null;
 958         }
 959         private MethodHandle findVirtualForVH(String name, MethodType type) {
 960             try {
 961                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
 962             } catch (IllegalArgumentException e) {
 963                 return null;
 964             }
 965         }
 966 
 967         /**
 968          * Produces a method handle which creates an object and initializes it, using
 969          * the constructor of the specified type.
 970          * The parameter types of the method handle will be those of the constructor,
 971          * while the return type will be a reference to the constructor's class.
 972          * The constructor and all its argument types must be accessible to the lookup object.
 973          * <p>
 974          * The requested type must have a return type of {@code void}.
 975          * (This is consistent with the JVM's treatment of constructor type descriptors.)
 976          * <p>
 977          * The returned method handle will have
 978          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 979          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
 980          * <p>
 981          * If the returned method handle is invoked, the constructor's class will
 982          * be initialized, if it has not already been initialized.
 983          * <p><b>Example:</b>
 984          * <blockquote><pre>{@code
 985 import static java.lang.invoke.MethodHandles.*;
 986 import static java.lang.invoke.MethodType.*;
 987 ...
 988 MethodHandle MH_newArrayList = publicLookup().findConstructor(
 989   ArrayList.class, methodType(void.class, Collection.class));
 990 Collection orig = Arrays.asList("x", "y");
 991 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
 992 assert(orig != copy);
 993 assertEquals(orig, copy);
 994 // a variable-arity constructor:
 995 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
 996   ProcessBuilder.class, methodType(void.class, String[].class));
 997 ProcessBuilder pb = (ProcessBuilder)
 998   MH_newProcessBuilder.invoke("x", "y", "z");
 999 assertEquals("[x, y, z]", pb.command().toString());
1000          * }</pre></blockquote>
1001          * @param refc the class or interface from which the method is accessed
1002          * @param type the type of the method, with the receiver argument omitted, and a void return type
1003          * @return the desired method handle
1004          * @throws NoSuchMethodException if the constructor does not exist
1005          * @throws IllegalAccessException if access checking fails
1006          *                                or if the method's variable arity modifier bit
1007          *                                is set and {@code asVarargsCollector} fails
1008          * @exception SecurityException if a security manager is present and it
1009          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1010          * @throws NullPointerException if any argument is null
1011          */
1012         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1013             if (refc.isArray()) {
1014                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
1015             }
1016             String name = "<init>";
1017             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
1018             return getDirectConstructor(refc, ctor);
1019         }
1020 
1021         /**
1022          * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static
1023          * initializer of the class is not run.
1024          * <p>
1025          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, its class
1026          * loader, and the {@linkplain #lookupModes() lookup modes}. In particular, the method first attempts to
1027          * load the requested class, and then determines whether the class is accessible to this lookup object.
1028          *
1029          * @param targetName the fully qualified name of the class to be looked up.
1030          * @return the requested class.
1031          * @exception SecurityException if a security manager is present and it
1032          *            <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1033          * @throws LinkageError if the linkage fails
1034          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
1035          * @throws IllegalAccessException if the class is not accessible, using the allowed access
1036          * modes.
1037          * @exception SecurityException if a security manager is present and it
1038          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1039          * @since 9
1040          */
1041         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
1042             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
1043             return accessClass(targetClass);
1044         }
1045 
1046         /**
1047          * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The
1048          * static initializer of the class is not run.
1049          * <p>
1050          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class} and the
1051          * {@linkplain #lookupModes() lookup modes}.
1052          *
1053          * @param targetClass the class to be access-checked
1054          *
1055          * @return the class that has been access-checked
1056          *
1057          * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access
1058          * modes.
1059          * @exception SecurityException if a security manager is present and it
1060          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1061          * @since 9
1062          */
1063         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
1064             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) {
1065                 throw new MemberName(targetClass).makeAccessException("access violation", this);
1066             }
1067             checkSecurityManager(targetClass, null);
1068             return targetClass;
1069         }
1070 
1071         /**
1072          * Produces an early-bound method handle for a virtual method.
1073          * It will bypass checks for overriding methods on the receiver,
1074          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1075          * instruction from within the explicitly specified {@code specialCaller}.
1076          * The type of the method handle will be that of the method,
1077          * with a suitably restricted receiver type prepended.
1078          * (The receiver type will be {@code specialCaller} or a subtype.)
1079          * The method and all its argument types must be accessible
1080          * to the lookup object.
1081          * <p>
1082          * Before method resolution,
1083          * if the explicitly specified caller class is not identical with the
1084          * lookup class, or if this lookup object does not have
1085          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1086          * privileges, the access fails.
1087          * <p>
1088          * The returned method handle will have
1089          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1090          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1091          * <p style="font-size:smaller;">
1092          * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
1093          * even though the {@code invokespecial} instruction can refer to them
1094          * in special circumstances.  Use {@link #findConstructor findConstructor}
1095          * to access instance initialization methods in a safe manner.)</em>
1096          * <p><b>Example:</b>
1097          * <blockquote><pre>{@code
1098 import static java.lang.invoke.MethodHandles.*;
1099 import static java.lang.invoke.MethodType.*;
1100 ...
1101 static class Listie extends ArrayList {
1102   public String toString() { return "[wee Listie]"; }
1103   static Lookup lookup() { return MethodHandles.lookup(); }
1104 }
1105 ...
1106 // no access to constructor via invokeSpecial:
1107 MethodHandle MH_newListie = Listie.lookup()
1108   .findConstructor(Listie.class, methodType(void.class));
1109 Listie l = (Listie) MH_newListie.invokeExact();
1110 try { assertEquals("impossible", Listie.lookup().findSpecial(
1111         Listie.class, "<init>", methodType(void.class), Listie.class));
1112  } catch (NoSuchMethodException ex) { } // OK
1113 // access to super and self methods via invokeSpecial:
1114 MethodHandle MH_super = Listie.lookup().findSpecial(
1115   ArrayList.class, "toString" , methodType(String.class), Listie.class);
1116 MethodHandle MH_this = Listie.lookup().findSpecial(
1117   Listie.class, "toString" , methodType(String.class), Listie.class);
1118 MethodHandle MH_duper = Listie.lookup().findSpecial(
1119   Object.class, "toString" , methodType(String.class), Listie.class);
1120 assertEquals("[]", (String) MH_super.invokeExact(l));
1121 assertEquals(""+l, (String) MH_this.invokeExact(l));
1122 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
1123 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
1124         String.class, "toString", methodType(String.class), Listie.class));
1125  } catch (IllegalAccessException ex) { } // OK
1126 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
1127 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
1128          * }</pre></blockquote>
1129          *
1130          * @param refc the class or interface from which the method is accessed
1131          * @param name the name of the method (which must not be "&lt;init&gt;")
1132          * @param type the type of the method, with the receiver argument omitted
1133          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
1134          * @return the desired method handle
1135          * @throws NoSuchMethodException if the method does not exist
1136          * @throws IllegalAccessException if access checking fails,
1137          *                                or if the method is {@code static},
1138          *                                or if the method's variable arity modifier bit
1139          *                                is set and {@code asVarargsCollector} fails
1140          * @exception SecurityException if a security manager is present and it
1141          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1142          * @throws NullPointerException if any argument is null
1143          */
1144         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
1145                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
1146             checkSpecialCaller(specialCaller, refc);
1147             Lookup specialLookup = this.in(specialCaller);
1148             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
1149             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1150         }
1151 
1152         /**
1153          * Produces a method handle giving read access to a non-static field.
1154          * The type of the method handle will have a return type of the field's
1155          * value type.
1156          * The method handle's single argument will be the instance containing
1157          * the field.
1158          * Access checking is performed immediately on behalf of the lookup class.
1159          * @param refc the class or interface from which the method is accessed
1160          * @param name the field's name
1161          * @param type the field's type
1162          * @return a method handle which can load values from the field
1163          * @throws NoSuchFieldException if the field does not exist
1164          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1165          * @exception SecurityException if a security manager is present and it
1166          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1167          * @throws NullPointerException if any argument is null
1168          * @see #findVarHandle(Class, String, Class)
1169          */
1170         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1171             MemberName field = resolveOrFail(REF_getField, refc, name, type);
1172             return getDirectField(REF_getField, refc, field);
1173         }
1174 
1175         /**
1176          * Produces a method handle giving write access to a non-static field.
1177          * The type of the method handle will have a void return type.
1178          * The method handle will take two arguments, the instance containing
1179          * the field, and the value to be stored.
1180          * The second argument will be of the field's value type.
1181          * Access checking is performed immediately on behalf of the lookup class.
1182          * @param refc the class or interface from which the method is accessed
1183          * @param name the field's name
1184          * @param type the field's type
1185          * @return a method handle which can store values into the field
1186          * @throws NoSuchFieldException if the field does not exist
1187          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1188          * @exception SecurityException if a security manager is present and it
1189          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1190          * @throws NullPointerException if any argument is null
1191          * @see #findVarHandle(Class, String, Class)
1192          */
1193         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1194             MemberName field = resolveOrFail(REF_putField, refc, name, type);
1195             return getDirectField(REF_putField, refc, field);
1196         }
1197 
1198         /**
1199          * Produces a VarHandle giving access to non-static fields of type
1200          * {@code T} declared by a receiver class of type {@code R}, supporting
1201          * shape {@code (R : T)}.
1202          * <p>
1203          * Access checking is performed immediately on behalf of the lookup
1204          * class.
1205          * <p>
1206          * Certain access modes of the returned VarHandle are unsupported under
1207          * the following conditions:
1208          * <ul>
1209          * <li>if the field is declared {@code final}, then the write, atomic
1210          *     update, and numeric atomic update access modes are unsupported.
1211          * <li>if the field type is anything other than {@code boolean},
1212          *     {@code byte}, {@code short}, {@code char}, {@code int} or
1213          *     a reference type, then atomic update access modes
1214          *     are unsupported.  (Future major platform releases of the JDK may
1215          *     support additional types for certain currently unsupported access
1216          *     modes.)
1217          * <li>if the field type is anything other than {@code byte},
1218          *     {@code short}, {@code char}, {@code int} or {@code long}, then
1219          *     numeric atomic update access modes are unsupported.
1220          * </ul>
1221          * <p>
1222          * If the field is declared {@code volatile} then the returned VarHandle
1223          * will override access to the field (effectively ignore the
1224          * {@code volatile} declaration) in accordance to it's specified
1225          * access modes.
1226          * @param recv the receiver class, of type {@code R}, that declares the
1227          * non-static field
1228          * @param name the field's name
1229          * @param type the field's type, of type {@code T}
1230          * @return a VarHandle giving access to non-static fields.
1231          * @throws NoSuchFieldException if the field does not exist
1232          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1233          * @exception SecurityException if a security manager is present and it
1234          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1235          * @throws NullPointerException if any argument is null
1236          * @since 9
1237          */
1238         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1239             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
1240             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
1241             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
1242         }
1243 
1244         /**
1245          * Produces a method handle giving read access to a static field.
1246          * The type of the method handle will have a return type of the field's
1247          * value type.
1248          * The method handle will take no arguments.
1249          * Access checking is performed immediately on behalf of the lookup class.
1250          * <p>
1251          * If the returned method handle is invoked, the field's class will
1252          * be initialized, if it has not already been initialized.
1253          * @param refc the class or interface from which the method is accessed
1254          * @param name the field's name
1255          * @param type the field's type
1256          * @return a method handle which can load values from the field
1257          * @throws NoSuchFieldException if the field does not exist
1258          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1259          * @exception SecurityException if a security manager is present and it
1260          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1261          * @throws NullPointerException if any argument is null
1262          */
1263         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1264             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
1265             return getDirectField(REF_getStatic, refc, field);
1266         }
1267 
1268         /**
1269          * Produces a method handle giving write access to a static field.
1270          * The type of the method handle will have a void return type.
1271          * The method handle will take a single
1272          * argument, of the field's value type, the value to be stored.
1273          * Access checking is performed immediately on behalf of the lookup class.
1274          * <p>
1275          * If the returned method handle is invoked, the field's class will
1276          * be initialized, if it has not already been initialized.
1277          * @param refc the class or interface from which the method is accessed
1278          * @param name the field's name
1279          * @param type the field's type
1280          * @return a method handle which can store values into the field
1281          * @throws NoSuchFieldException if the field does not exist
1282          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1283          * @exception SecurityException if a security manager is present and it
1284          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1285          * @throws NullPointerException if any argument is null
1286          */
1287         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1288             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
1289             return getDirectField(REF_putStatic, refc, field);
1290         }
1291 
1292         /**
1293          * Produces a VarHandle giving access to a static field of type
1294          * {@code T} declared by a given declaring class, supporting shape
1295          * {@code ((empty) : T)}.
1296          * <p>
1297          * Access checking is performed immediately on behalf of the lookup
1298          * class.
1299          * <p>
1300          * If the returned VarHandle is operated on, the declaring class will be
1301          * initialized, if it has not already been initialized.
1302          * <p>
1303          * Certain access modes of the returned VarHandle are unsupported under
1304          * the following conditions:
1305          * <ul>
1306          * <li>if the field is declared {@code final}, then the write, atomic
1307          *     update, and numeric atomic update access modes are unsupported.
1308          * <li>if the field type is anything other than {@code boolean},
1309          *     {@code byte}, {@code short}, {@code char}, {@code int},
1310          *     {@code long} or a reference type, then atomic update access modes
1311          *     are unsupported.  (Future major platform releases of the JDK may
1312          *     support additional types for certain currently unsupported access
1313          *     modes.)
1314          * <li>if the field type is anything other than {@code byte},
1315          *     {@code short}, {@code char}, {@code int} or {@code long}, then
1316          *     numeric atomic update access modes are unsupported.
1317          * </ul>
1318          * <p>
1319          * If the field is declared {@code volatile} then the returned VarHandle
1320          * will override access to the field (effectively ignore the
1321          * {@code volatile} declaration) in accordance to it's specified
1322          * access modes.
1323          * @param decl the class that declares the static field
1324          * @param name the field's name
1325          * @param type the field's type, of type {@code T}
1326          * @return a VarHandle giving access to a static field
1327          * @throws NoSuchFieldException if the field does not exist
1328          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1329          * @exception SecurityException if a security manager is present and it
1330          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1331          * @throws NullPointerException if any argument is null
1332          * @since 9
1333          */
1334         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1335             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
1336             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
1337             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
1338         }
1339 
1340         /**
1341          * Produces an early-bound method handle for a non-static method.
1342          * The receiver must have a supertype {@code defc} in which a method
1343          * of the given name and type is accessible to the lookup class.
1344          * The method and all its argument types must be accessible to the lookup object.
1345          * The type of the method handle will be that of the method,
1346          * without any insertion of an additional receiver parameter.
1347          * The given receiver will be bound into the method handle,
1348          * so that every call to the method handle will invoke the
1349          * requested method on the given receiver.
1350          * <p>
1351          * The returned method handle will have
1352          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1353          * the method's variable arity modifier bit ({@code 0x0080}) is set
1354          * <em>and</em> the trailing array argument is not the only argument.
1355          * (If the trailing array argument is the only argument,
1356          * the given receiver value will be bound to it.)
1357          * <p>
1358          * This is equivalent to the following code:
1359          * <blockquote><pre>{@code
1360 import static java.lang.invoke.MethodHandles.*;
1361 import static java.lang.invoke.MethodType.*;
1362 ...
1363 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
1364 MethodHandle mh1 = mh0.bindTo(receiver);
1365 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
1366 return mh1;
1367          * }</pre></blockquote>
1368          * where {@code defc} is either {@code receiver.getClass()} or a super
1369          * type of that class, in which the requested method is accessible
1370          * to the lookup class.
1371          * (Note that {@code bindTo} does not preserve variable arity.)
1372          * @param receiver the object from which the method is accessed
1373          * @param name the name of the method
1374          * @param type the type of the method, with the receiver argument omitted
1375          * @return the desired method handle
1376          * @throws NoSuchMethodException if the method does not exist
1377          * @throws IllegalAccessException if access checking fails
1378          *                                or if the method's variable arity modifier bit
1379          *                                is set and {@code asVarargsCollector} fails
1380          * @exception SecurityException if a security manager is present and it
1381          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1382          * @throws NullPointerException if any argument is null
1383          * @see MethodHandle#bindTo
1384          * @see #findVirtual
1385          */
1386         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1387             Class<? extends Object> refc = receiver.getClass(); // may get NPE
1388             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
1389             MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1390             return mh.bindArgumentL(0, receiver).setVarargs(method);
1391         }
1392 
1393         /**
1394          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1395          * to <i>m</i>, if the lookup class has permission.
1396          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
1397          * If <i>m</i> is virtual, overriding is respected on every call.
1398          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
1399          * The type of the method handle will be that of the method,
1400          * with the receiver type prepended (but only if it is non-static).
1401          * If the method's {@code accessible} flag is not set,
1402          * access checking is performed immediately on behalf of the lookup class.
1403          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
1404          * <p>
1405          * The returned method handle will have
1406          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1407          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1408          * <p>
1409          * If <i>m</i> is static, and
1410          * if the returned method handle is invoked, the method's class will
1411          * be initialized, if it has not already been initialized.
1412          * @param m the reflected method
1413          * @return a method handle which can invoke the reflected method
1414          * @throws IllegalAccessException if access checking fails
1415          *                                or if the method's variable arity modifier bit
1416          *                                is set and {@code asVarargsCollector} fails
1417          * @throws NullPointerException if the argument is null
1418          */
1419         public MethodHandle unreflect(Method m) throws IllegalAccessException {
1420             if (m.getDeclaringClass() == MethodHandle.class) {
1421                 MethodHandle mh = unreflectForMH(m);
1422                 if (mh != null)  return mh;
1423             }
1424             if (m.getDeclaringClass() == VarHandle.class) {
1425                 MethodHandle mh = unreflectForVH(m);
1426                 if (mh != null)  return mh;
1427             }
1428             MemberName method = new MemberName(m);
1429             byte refKind = method.getReferenceKind();
1430             if (refKind == REF_invokeSpecial)
1431                 refKind = REF_invokeVirtual;
1432             assert(method.isMethod());
1433             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
1434             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
1435         }
1436         private MethodHandle unreflectForMH(Method m) {
1437             // these names require special lookups because they throw UnsupportedOperationException
1438             if (MemberName.isMethodHandleInvokeName(m.getName()))
1439                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
1440             return null;
1441         }
1442         private MethodHandle unreflectForVH(Method m) {
1443             // these names require special lookups because they throw UnsupportedOperationException
1444             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
1445                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
1446             return null;
1447         }
1448 
1449         /**
1450          * Produces a method handle for a reflected method.
1451          * It will bypass checks for overriding methods on the receiver,
1452          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1453          * instruction from within the explicitly specified {@code specialCaller}.
1454          * The type of the method handle will be that of the method,
1455          * with a suitably restricted receiver type prepended.
1456          * (The receiver type will be {@code specialCaller} or a subtype.)
1457          * If the method's {@code accessible} flag is not set,
1458          * access checking is performed immediately on behalf of the lookup class,
1459          * as if {@code invokespecial} instruction were being linked.
1460          * <p>
1461          * Before method resolution,
1462          * if the explicitly specified caller class is not identical with the
1463          * lookup class, or if this lookup object does not have
1464          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1465          * privileges, the access fails.
1466          * <p>
1467          * The returned method handle will have
1468          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1469          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1470          * @param m the reflected method
1471          * @param specialCaller the class nominally calling the method
1472          * @return a method handle which can invoke the reflected method
1473          * @throws IllegalAccessException if access checking fails,
1474          *                                or if the method is {@code static},
1475          *                                or if the method's variable arity modifier bit
1476          *                                is set and {@code asVarargsCollector} fails
1477          * @throws NullPointerException if any argument is null
1478          */
1479         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
1480             checkSpecialCaller(specialCaller, null);
1481             Lookup specialLookup = this.in(specialCaller);
1482             MemberName method = new MemberName(m, true);
1483             assert(method.isMethod());
1484             // ignore m.isAccessible:  this is a new kind of access
1485             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
1486         }
1487 
1488         /**
1489          * Produces a method handle for a reflected constructor.
1490          * The type of the method handle will be that of the constructor,
1491          * with the return type changed to the declaring class.
1492          * The method handle will perform a {@code newInstance} operation,
1493          * creating a new instance of the constructor's class on the
1494          * arguments passed to the method handle.
1495          * <p>
1496          * If the constructor's {@code accessible} flag is not set,
1497          * access checking is performed immediately on behalf of the lookup class.
1498          * <p>
1499          * The returned method handle will have
1500          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1501          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
1502          * <p>
1503          * If the returned method handle is invoked, the constructor's class will
1504          * be initialized, if it has not already been initialized.
1505          * @param c the reflected constructor
1506          * @return a method handle which can invoke the reflected constructor
1507          * @throws IllegalAccessException if access checking fails
1508          *                                or if the method's variable arity modifier bit
1509          *                                is set and {@code asVarargsCollector} fails
1510          * @throws NullPointerException if the argument is null
1511          */
1512         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
1513             MemberName ctor = new MemberName(c);
1514             assert(ctor.isConstructor());
1515             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
1516             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
1517         }
1518 
1519         /**
1520          * Produces a method handle giving read access to a reflected field.
1521          * The type of the method handle will have a return type of the field's
1522          * value type.
1523          * If the field is static, the method handle will take no arguments.
1524          * Otherwise, its single argument will be the instance containing
1525          * the field.
1526          * If the field's {@code accessible} flag is not set,
1527          * access checking is performed immediately on behalf of the lookup class.
1528          * <p>
1529          * If the field is static, and
1530          * if the returned method handle is invoked, the field's class will
1531          * be initialized, if it has not already been initialized.
1532          * @param f the reflected field
1533          * @return a method handle which can load values from the reflected field
1534          * @throws IllegalAccessException if access checking fails
1535          * @throws NullPointerException if the argument is null
1536          */
1537         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
1538             return unreflectField(f, false);
1539         }
1540         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
1541             MemberName field = new MemberName(f, isSetter);
1542             assert(isSetter
1543                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
1544                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
1545             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
1546             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
1547         }
1548 
1549         /**
1550          * Produces a method handle giving write access to a reflected field.
1551          * The type of the method handle will have a void return type.
1552          * If the field is static, the method handle will take a single
1553          * argument, of the field's value type, the value to be stored.
1554          * Otherwise, the two arguments will be the instance containing
1555          * the field, and the value to be stored.
1556          * If the field's {@code accessible} flag is not set,
1557          * access checking is performed immediately on behalf of the lookup class.
1558          * <p>
1559          * If the field is static, and
1560          * if the returned method handle is invoked, the field's class will
1561          * be initialized, if it has not already been initialized.
1562          * @param f the reflected field
1563          * @return a method handle which can store values into the reflected field
1564          * @throws IllegalAccessException if access checking fails
1565          * @throws NullPointerException if the argument is null
1566          */
1567         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
1568             return unreflectField(f, true);
1569         }
1570 
1571         /**
1572          * Produces a VarHandle that accesses fields of type {@code T} declared
1573          * by a class of type {@code R}, as described by the given reflected
1574          * field.
1575          * If the field is non-static the VarHandle supports a shape of
1576          * {@code (R : T)}, otherwise supports a shape of {@code ((empty) : T)}.
1577          * <p>
1578          * Access checking is performed immediately on behalf of the lookup
1579          * class, regardless of the value of the field's {@code accessible}
1580          * flag.
1581          * <p>
1582          * If the field is static, and if the returned VarHandle is operated
1583          * on, the field's declaring class will be initialized, if it has not
1584          * already been initialized.
1585          * <p>
1586          * Certain access modes of the returned VarHandle are unsupported under
1587          * the following conditions:
1588          * <ul>
1589          * <li>if the field is declared {@code final}, then the write, atomic
1590          *     update, and numeric atomic update access modes are unsupported.
1591          * <li>if the field type is anything other than {@code boolean},
1592          *     {@code byte}, {@code short}, {@code char}, {@code int}, or
1593          *     a reference type, then atomic update access modes
1594          *     are unsupported.  (Future major platform releases of the JDK may
1595          *     support additional types for certain currently unsupported access
1596          *     modes.)
1597          * <li>if the field type is anything other than {@code byte},
1598          *     {@code short}, {@code char}, {@code int} or {@code long}, then
1599          *     numeric atomic update access modes are unsupported.
1600          * </ul>
1601          * <p>
1602          * If the field is declared {@code volatile} then the returned VarHandle
1603          * will override access to the field (effectively ignore the
1604          * {@code volatile} declaration) in accordance to it's specified
1605          * access modes.
1606          * @param f the reflected field, with a field of type {@code T}, and
1607          * a declaring class of type {@code R}
1608          * @return a VarHandle giving access to non-static fields or a static
1609          * field
1610          * @throws IllegalAccessException if access checking fails
1611          * @throws NullPointerException if the argument is null
1612          * @since 9
1613          */
1614         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
1615             MemberName getField = new MemberName(f, false);
1616             MemberName putField = new MemberName(f, true);
1617             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
1618                                                       f.getDeclaringClass(), getField, putField);
1619         }
1620 
1621         /**
1622          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1623          * created by this lookup object or a similar one.
1624          * Security and access checks are performed to ensure that this lookup object
1625          * is capable of reproducing the target method handle.
1626          * This means that the cracking may fail if target is a direct method handle
1627          * but was created by an unrelated lookup object.
1628          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
1629          * and was created by a lookup object for a different class.
1630          * @param target a direct method handle to crack into symbolic reference components
1631          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
1632          * @exception SecurityException if a security manager is present and it
1633          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1634          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
1635          * @exception NullPointerException if the target is {@code null}
1636          * @see MethodHandleInfo
1637          * @since 1.8
1638          */
1639         public MethodHandleInfo revealDirect(MethodHandle target) {
1640             MemberName member = target.internalMemberName();
1641             if (member == null || (!member.isResolved() &&
1642                                    !member.isMethodHandleInvoke() &&
1643                                    !member.isVarHandleMethodInvoke()))
1644                 throw newIllegalArgumentException("not a direct method handle");
1645             Class<?> defc = member.getDeclaringClass();
1646             byte refKind = member.getReferenceKind();
1647             assert(MethodHandleNatives.refKindIsValid(refKind));
1648             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
1649                 // Devirtualized method invocation is usually formally virtual.
1650                 // To avoid creating extra MemberName objects for this common case,
1651                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
1652                 refKind = REF_invokeVirtual;
1653             if (refKind == REF_invokeVirtual && defc.isInterface())
1654                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
1655                 refKind = REF_invokeInterface;
1656             // Check SM permissions and member access before cracking.
1657             try {
1658                 checkAccess(refKind, defc, member);
1659                 checkSecurityManager(defc, member);
1660             } catch (IllegalAccessException ex) {
1661                 throw new IllegalArgumentException(ex);
1662             }
1663             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
1664                 Class<?> callerClass = target.internalCallerClass();
1665                 if (!hasPrivateAccess() || callerClass != lookupClass())
1666                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
1667             }
1668             // Produce the handle to the results.
1669             return new InfoFromMemberName(this, member, refKind);
1670         }
1671 
1672         /// Helper methods, all package-private.
1673 
1674         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1675             checkSymbolicClass(refc);  // do this before attempting to resolve
1676             Objects.requireNonNull(name);
1677             Objects.requireNonNull(type);
1678             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1679                                             NoSuchFieldException.class);
1680         }
1681 
1682         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1683             checkSymbolicClass(refc);  // do this before attempting to resolve
1684             Objects.requireNonNull(name);
1685             Objects.requireNonNull(type);
1686             checkMethodName(refKind, name);  // NPE check on name
1687             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1688                                             NoSuchMethodException.class);
1689         }
1690 
1691         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
1692             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
1693             Objects.requireNonNull(member.getName());
1694             Objects.requireNonNull(member.getType());
1695             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
1696                                             ReflectiveOperationException.class);
1697         }
1698 
1699         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
1700             Objects.requireNonNull(refc);
1701             Class<?> caller = lookupClassOrNull();
1702             if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes))
1703                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
1704         }
1705 
1706         /** Check name for an illegal leading "&lt;" character. */
1707         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
1708             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
1709                 throw new NoSuchMethodException("illegal method name: "+name);
1710         }
1711 
1712 
1713         /**
1714          * Find my trustable caller class if m is a caller sensitive method.
1715          * If this lookup object has private access, then the caller class is the lookupClass.
1716          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
1717          */
1718         Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
1719             Class<?> callerClass = null;
1720             if (MethodHandleNatives.isCallerSensitive(m)) {
1721                 // Only lookups with private access are allowed to resolve caller-sensitive methods
1722                 if (hasPrivateAccess()) {
1723                     callerClass = lookupClass;
1724                 } else {
1725                     throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
1726                 }
1727             }
1728             return callerClass;
1729         }
1730 
1731         private boolean hasPrivateAccess() {
1732             return (allowedModes & PRIVATE) != 0;
1733         }
1734 
1735         /**
1736          * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
1737          * Determines a trustable caller class to compare with refc, the symbolic reference class.
1738          * If this lookup object has private access, then the caller class is the lookupClass.
1739          */
1740         void checkSecurityManager(Class<?> refc, MemberName m) {
1741             SecurityManager smgr = System.getSecurityManager();
1742             if (smgr == null)  return;
1743             if (allowedModes == TRUSTED)  return;
1744 
1745             // Step 1:
1746             boolean fullPowerLookup = hasPrivateAccess();
1747             if (!fullPowerLookup ||
1748                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
1749                 ReflectUtil.checkPackageAccess(refc);
1750             }
1751 
1752             if (m == null) {  // findClass or accessClass
1753                 // Step 2b:
1754                 if (!fullPowerLookup) {
1755                     smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
1756                 }
1757                 return;
1758             }
1759 
1760             // Step 2a:
1761             if (m.isPublic()) return;
1762             if (!fullPowerLookup) {
1763                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
1764             }
1765 
1766             // Step 3:
1767             Class<?> defc = m.getDeclaringClass();
1768             if (!fullPowerLookup && defc != refc) {
1769                 ReflectUtil.checkPackageAccess(defc);
1770             }
1771         }
1772 
1773         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1774             boolean wantStatic = (refKind == REF_invokeStatic);
1775             String message;
1776             if (m.isConstructor())
1777                 message = "expected a method, not a constructor";
1778             else if (!m.isMethod())
1779                 message = "expected a method";
1780             else if (wantStatic != m.isStatic())
1781                 message = wantStatic ? "expected a static method" : "expected a non-static method";
1782             else
1783                 { checkAccess(refKind, refc, m); return; }
1784             throw m.makeAccessException(message, this);
1785         }
1786 
1787         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1788             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
1789             String message;
1790             if (wantStatic != m.isStatic())
1791                 message = wantStatic ? "expected a static field" : "expected a non-static field";
1792             else
1793                 { checkAccess(refKind, refc, m); return; }
1794             throw m.makeAccessException(message, this);
1795         }
1796 
1797         /** Check public/protected/private bits on the symbolic reference class and its member. */
1798         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1799             assert(m.referenceKindIsConsistentWith(refKind) &&
1800                    MethodHandleNatives.refKindIsValid(refKind) &&
1801                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
1802             int allowedModes = this.allowedModes;
1803             if (allowedModes == TRUSTED)  return;
1804             int mods = m.getModifiers();
1805             if (Modifier.isProtected(mods) &&
1806                     refKind == REF_invokeVirtual &&
1807                     m.getDeclaringClass() == Object.class &&
1808                     m.getName().equals("clone") &&
1809                     refc.isArray()) {
1810                 // The JVM does this hack also.
1811                 // (See ClassVerifier::verify_invoke_instructions
1812                 // and LinkResolver::check_method_accessability.)
1813                 // Because the JVM does not allow separate methods on array types,
1814                 // there is no separate method for int[].clone.
1815                 // All arrays simply inherit Object.clone.
1816                 // But for access checking logic, we make Object.clone
1817                 // (normally protected) appear to be public.
1818                 // Later on, when the DirectMethodHandle is created,
1819                 // its leading argument will be restricted to the
1820                 // requested array type.
1821                 // N.B. The return type is not adjusted, because
1822                 // that is *not* the bytecode behavior.
1823                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
1824             }
1825             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
1826                 // cannot "new" a protected ctor in a different package
1827                 mods ^= Modifier.PROTECTED;
1828             }
1829             if (Modifier.isFinal(mods) &&
1830                     MethodHandleNatives.refKindIsSetter(refKind))
1831                 throw m.makeAccessException("unexpected set of a final field", this);
1832             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
1833             if ((requestedModes & allowedModes) != 0) {
1834                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
1835                                                     mods, lookupClass(), allowedModes))
1836                     return;
1837             } else {
1838                 // Protected members can also be checked as if they were package-private.
1839                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
1840                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
1841                     return;
1842             }
1843             throw m.makeAccessException(accessFailedMessage(refc, m), this);
1844         }
1845 
1846         String accessFailedMessage(Class<?> refc, MemberName m) {
1847             Class<?> defc = m.getDeclaringClass();
1848             int mods = m.getModifiers();
1849             // check the class first:
1850             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
1851                                (defc == refc ||
1852                                 Modifier.isPublic(refc.getModifiers())));
1853             if (!classOK && (allowedModes & PACKAGE) != 0) {
1854                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
1855                            (defc == refc ||
1856                             VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
1857             }
1858             if (!classOK)
1859                 return "class is not public";
1860             if (Modifier.isPublic(mods))
1861                 return "access to public member failed";  // (how?, module not readable?)
1862             if (Modifier.isPrivate(mods))
1863                 return "member is private";
1864             if (Modifier.isProtected(mods))
1865                 return "member is protected";
1866             return "member is private to package";
1867         }
1868 
1869         private static final boolean ALLOW_NESTMATE_ACCESS = false;
1870 
1871         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
1872             int allowedModes = this.allowedModes;
1873             if (allowedModes == TRUSTED)  return;
1874             if (!hasPrivateAccess()
1875                 || (specialCaller != lookupClass()
1876                        // ensure non-abstract methods in superinterfaces can be special-invoked
1877                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))
1878                     && !(ALLOW_NESTMATE_ACCESS &&
1879                          VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
1880                 throw new MemberName(specialCaller).
1881                     makeAccessException("no private access for invokespecial", this);
1882         }
1883 
1884         private boolean restrictProtectedReceiver(MemberName method) {
1885             // The accessing class only has the right to use a protected member
1886             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
1887             if (!method.isProtected() || method.isStatic()
1888                 || allowedModes == TRUSTED
1889                 || method.getDeclaringClass() == lookupClass()
1890                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
1891                 || (ALLOW_NESTMATE_ACCESS &&
1892                     VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass())))
1893                 return false;
1894             return true;
1895         }
1896         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
1897             assert(!method.isStatic());
1898             // receiver type of mh is too wide; narrow to caller
1899             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
1900                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
1901             }
1902             MethodType rawType = mh.type();
1903             if (rawType.parameterType(0) == caller)  return mh;
1904             MethodType narrowType = rawType.changeParameterType(0, caller);
1905             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
1906             assert(mh.viewAsTypeChecks(narrowType, true));
1907             return mh.copyWith(narrowType, mh.form);
1908         }
1909 
1910         /** Check access and get the requested method. */
1911         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1912             final boolean doRestrict    = true;
1913             final boolean checkSecurity = true;
1914             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1915         }
1916         /** Check access and get the requested method, eliding receiver narrowing rules. */
1917         private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1918             final boolean doRestrict    = false;
1919             final boolean checkSecurity = true;
1920             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1921         }
1922         /** Check access and get the requested method, eliding security manager checks. */
1923         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1924             final boolean doRestrict    = true;
1925             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
1926             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1927         }
1928         /** Common code for all methods; do not call directly except from immediately above. */
1929         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
1930                                                    boolean checkSecurity,
1931                                                    boolean doRestrict, Class<?> callerClass) throws IllegalAccessException {
1932             checkMethod(refKind, refc, method);
1933             // Optionally check with the security manager; this isn't needed for unreflect* calls.
1934             if (checkSecurity)
1935                 checkSecurityManager(refc, method);
1936             assert(!method.isMethodHandleInvoke());
1937 
1938             if (refKind == REF_invokeSpecial &&
1939                 refc != lookupClass() &&
1940                 !refc.isInterface() &&
1941                 refc != lookupClass().getSuperclass() &&
1942                 refc.isAssignableFrom(lookupClass())) {
1943                 assert(!method.getName().equals("<init>"));  // not this code path
1944                 // Per JVMS 6.5, desc. of invokespecial instruction:
1945                 // If the method is in a superclass of the LC,
1946                 // and if our original search was above LC.super,
1947                 // repeat the search (symbolic lookup) from LC.super
1948                 // and continue with the direct superclass of that class,
1949                 // and so forth, until a match is found or no further superclasses exist.
1950                 // FIXME: MemberName.resolve should handle this instead.
1951                 Class<?> refcAsSuper = lookupClass();
1952                 MemberName m2;
1953                 do {
1954                     refcAsSuper = refcAsSuper.getSuperclass();
1955                     m2 = new MemberName(refcAsSuper,
1956                                         method.getName(),
1957                                         method.getMethodType(),
1958                                         REF_invokeSpecial);
1959                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
1960                 } while (m2 == null &&         // no method is found yet
1961                          refc != refcAsSuper); // search up to refc
1962                 if (m2 == null)  throw new InternalError(method.toString());
1963                 method = m2;
1964                 refc = refcAsSuper;
1965                 // redo basic checks
1966                 checkMethod(refKind, refc, method);
1967             }
1968 
1969             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method);
1970             MethodHandle mh = dmh;
1971             // Optionally narrow the receiver argument to refc using restrictReceiver.
1972             if (doRestrict &&
1973                    (refKind == REF_invokeSpecial ||
1974                        (MethodHandleNatives.refKindHasReceiver(refKind) &&
1975                            restrictProtectedReceiver(method)))) {
1976                 mh = restrictReceiver(method, dmh, lookupClass());
1977             }
1978             mh = maybeBindCaller(method, mh, callerClass);
1979             mh = mh.setVarargs(method);
1980             return mh;
1981         }
1982         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
1983                                              Class<?> callerClass)
1984                                              throws IllegalAccessException {
1985             if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
1986                 return mh;
1987             Class<?> hostClass = lookupClass;
1988             if (!hasPrivateAccess())  // caller must have private access
1989                 hostClass = callerClass;  // callerClass came from a security manager style stack walk
1990             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
1991             // Note: caller will apply varargs after this step happens.
1992             return cbmh;
1993         }
1994         /** Check access and get the requested field. */
1995         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
1996             final boolean checkSecurity = true;
1997             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
1998         }
1999         /** Check access and get the requested field, eliding security manager checks. */
2000         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
2001             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
2002             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
2003         }
2004         /** Common code for all fields; do not call directly except from immediately above. */
2005         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
2006                                                   boolean checkSecurity) throws IllegalAccessException {
2007             checkField(refKind, refc, field);
2008             // Optionally check with the security manager; this isn't needed for unreflect* calls.
2009             if (checkSecurity)
2010                 checkSecurityManager(refc, field);
2011             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
2012             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
2013                                     restrictProtectedReceiver(field));
2014             if (doRestrict)
2015                 return restrictReceiver(field, dmh, lookupClass());
2016             return dmh;
2017         }
2018         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
2019                                             Class<?> refc, MemberName getField, MemberName putField)
2020                 throws IllegalAccessException {
2021             final boolean checkSecurity = true;
2022             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
2023         }
2024         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
2025                                                              Class<?> refc, MemberName getField, MemberName putField)
2026                 throws IllegalAccessException {
2027             final boolean checkSecurity = false;
2028             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
2029         }
2030         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
2031                                                   Class<?> refc, MemberName getField, MemberName putField,
2032                                                   boolean checkSecurity) throws IllegalAccessException {
2033             assert getField.isStatic() == putField.isStatic();
2034             assert getField.isGetter() && putField.isSetter();
2035             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
2036             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
2037 
2038             checkField(getRefKind, refc, getField);
2039             if (checkSecurity)
2040                 checkSecurityManager(refc, getField);
2041 
2042             if (!putField.isFinal()) {
2043                 // A VarHandle does not support updates to final fields, any
2044                 // such VarHandle to a final field will be read-only and
2045                 // therefore the following write-based accessibility checks are
2046                 // only required for non-final fields
2047                 checkField(putRefKind, refc, putField);
2048                 if (checkSecurity)
2049                     checkSecurityManager(refc, putField);
2050             }
2051 
2052             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
2053                                   restrictProtectedReceiver(getField));
2054             if (doRestrict) {
2055                 assert !getField.isStatic();
2056                 // receiver type of VarHandle is too wide; narrow to caller
2057                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
2058                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
2059                 }
2060                 refc = lookupClass();
2061             }
2062             return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED);
2063         }
2064         /** Check access and get the requested constructor. */
2065         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
2066             final boolean checkSecurity = true;
2067             return getDirectConstructorCommon(refc, ctor, checkSecurity);
2068         }
2069         /** Check access and get the requested constructor, eliding security manager checks. */
2070         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
2071             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
2072             return getDirectConstructorCommon(refc, ctor, checkSecurity);
2073         }
2074         /** Common code for all constructors; do not call directly except from immediately above. */
2075         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
2076                                                   boolean checkSecurity) throws IllegalAccessException {
2077             assert(ctor.isConstructor());
2078             checkAccess(REF_newInvokeSpecial, refc, ctor);
2079             // Optionally check with the security manager; this isn't needed for unreflect* calls.
2080             if (checkSecurity)
2081                 checkSecurityManager(refc, ctor);
2082             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
2083             return DirectMethodHandle.make(ctor).setVarargs(ctor);
2084         }
2085 
2086         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
2087          */
2088         /*non-public*/
2089         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException {
2090             if (!(type instanceof Class || type instanceof MethodType))
2091                 throw new InternalError("unresolved MemberName");
2092             MemberName member = new MemberName(refKind, defc, name, type);
2093             MethodHandle mh = LOOKASIDE_TABLE.get(member);
2094             if (mh != null) {
2095                 checkSymbolicClass(defc);
2096                 return mh;
2097             }
2098             // Treat MethodHandle.invoke and invokeExact specially.
2099             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
2100                 mh = findVirtualForMH(member.getName(), member.getMethodType());
2101                 if (mh != null) {
2102                     return mh;
2103                 }
2104             }
2105             MemberName resolved = resolveOrFail(refKind, member);
2106             mh = getDirectMethodForConstant(refKind, defc, resolved);
2107             if (mh instanceof DirectMethodHandle
2108                     && canBeCached(refKind, defc, resolved)) {
2109                 MemberName key = mh.internalMemberName();
2110                 if (key != null) {
2111                     key = key.asNormalOriginal();
2112                 }
2113                 if (member.equals(key)) {  // better safe than sorry
2114                     LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
2115                 }
2116             }
2117             return mh;
2118         }
2119         private
2120         boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
2121             if (refKind == REF_invokeSpecial) {
2122                 return false;
2123             }
2124             if (!Modifier.isPublic(defc.getModifiers()) ||
2125                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
2126                     !member.isPublic() ||
2127                     member.isCallerSensitive()) {
2128                 return false;
2129             }
2130             ClassLoader loader = defc.getClassLoader();
2131             if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) {
2132                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
2133                 boolean found = false;
2134                 while (sysl != null) {
2135                     if (loader == sysl) { found = true; break; }
2136                     sysl = sysl.getParent();
2137                 }
2138                 if (!found) {
2139                     return false;
2140                 }
2141             }
2142             try {
2143                 MemberName resolved2 = publicLookup().resolveOrFail(refKind,
2144                     new MemberName(refKind, defc, member.getName(), member.getType()));
2145                 checkSecurityManager(defc, resolved2);
2146             } catch (ReflectiveOperationException | SecurityException ex) {
2147                 return false;
2148             }
2149             return true;
2150         }
2151         private
2152         MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
2153                 throws ReflectiveOperationException {
2154             if (MethodHandleNatives.refKindIsField(refKind)) {
2155                 return getDirectFieldNoSecurityManager(refKind, defc, member);
2156             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
2157                 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
2158             } else if (refKind == REF_newInvokeSpecial) {
2159                 return getDirectConstructorNoSecurityManager(defc, member);
2160             }
2161             // oops
2162             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
2163         }
2164 
2165         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
2166     }
2167 
2168     /**
2169      * Helper class used to lazily create PUBLIC_LOOKUP with a lookup class
2170      * in an <em>unnamed module</em>.
2171      *
2172      * @see Lookup#publicLookup
2173      */
2174     private static class LookupHelper {
2175         private static final String UNNAMED = "Unnamed";
2176         private static final String OBJECT  = "java/lang/Object";
2177 
2178         private static Class<?> createClass() {
2179             try {
2180                 ClassWriter cw = new ClassWriter(0);
2181                 cw.visit(Opcodes.V1_8,
2182                          Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
2183                          UNNAMED,
2184                          null,
2185                          OBJECT,
2186                          null);
2187                 cw.visitSource(UNNAMED, null);
2188                 cw.visitEnd();
2189                 byte[] bytes = cw.toByteArray();
2190                 ClassLoader loader = new ClassLoader(null) {
2191                     @Override
2192                     protected Class<?> findClass(String cn) throws ClassNotFoundException {
2193                         if (cn.equals(UNNAMED))
2194                             return super.defineClass(UNNAMED, bytes, 0, bytes.length);
2195                         throw new ClassNotFoundException(cn);
2196                     }
2197                 };
2198                 return loader.loadClass(UNNAMED);
2199             } catch (Exception e) {
2200                 throw new InternalError(e);
2201             }
2202         }
2203 
2204         private static final Class<?> PUBLIC_LOOKUP_CLASS;
2205         static {
2206             PrivilegedAction<Class<?>> pa = new PrivilegedAction<Class<?>>() {
2207                 public Class<?> run() {
2208                     return createClass();
2209                 }
2210             };
2211             PUBLIC_LOOKUP_CLASS = AccessController.doPrivileged(pa);
2212         }
2213 
2214         /**
2215          * Lookup that is trusted minimally. It can only be used to create
2216          * method handles to publicly accessible members in exported packages.
2217          *
2218          * @see MethodHandles#publicLookup
2219          */
2220         static final Lookup PUBLIC_LOOKUP = new Lookup(PUBLIC_LOOKUP_CLASS, Lookup.PUBLIC);
2221     }
2222 
2223     /**
2224      * Produces a method handle constructing arrays of a desired type.
2225      * The return type of the method handle will be the array type.
2226      * The type of its sole argument will be {@code int}, which specifies the size of the array.
2227      * @param arrayClass an array type
2228      * @return a method handle which can create arrays of the given type
2229      * @throws NullPointerException if the argument is {@code null}
2230      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
2231      * @see java.lang.reflect.Array#newInstance(Class, int)
2232      * @since 9
2233      */
2234     public static
2235     MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
2236         if (!arrayClass.isArray()) {
2237             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
2238         }
2239         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
2240                 bindTo(arrayClass.getComponentType());
2241         return ani.asType(ani.type().changeReturnType(arrayClass));
2242     }
2243 
2244     /**
2245      * Produces a method handle giving read access to elements of an array.
2246      * The type of the method handle will have a return type of the array's
2247      * element type.  Its first argument will be the array type,
2248      * and the second will be {@code int}.
2249      * @param arrayClass an array type
2250      * @return a method handle which can load values from the given array type
2251      * @throws NullPointerException if the argument is null
2252      * @throws  IllegalArgumentException if arrayClass is not an array type
2253      */
2254     public static
2255     MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
2256         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false);
2257     }
2258 
2259     /**
2260      * Produces a method handle giving write access to elements of an array.
2261      * The type of the method handle will have a void return type.
2262      * Its last argument will be the array's element type.
2263      * The first and second arguments will be the array type and int.
2264      * @param arrayClass the class of an array
2265      * @return a method handle which can store values into the array type
2266      * @throws NullPointerException if the argument is null
2267      * @throws IllegalArgumentException if arrayClass is not an array type
2268      */
2269     public static
2270     MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
2271         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true);
2272     }
2273 
2274     /**
2275      *
2276      * Produces a VarHandle giving access to elements of an array type
2277      * {@code T[]}, supporting shape {@code (T[], int : T)}.
2278      * <p>
2279      * Certain access modes of the returned VarHandle are unsupported under
2280      * the following conditions:
2281      * <ul>
2282       * <li>if the field type is anything other than {@code boolean},
2283      *     {@code byte}, {@code short}, {@code char}, {@code int} or
2284      *     a reference type, then atomic update access modes
2285      *     are unsupported.  (Future major platform releases of the JDK may
2286      *     support additional types for certain currently unsupported access
2287      *     modes.)
2288      * <li>if the component type is anything other than {@code byte},
2289      *     {@code short}, {@code char}, {@code int} or {@code long}, then
2290      *     numeric atomic update access modes are unsupported.
2291      * </ul>
2292      * @param arrayClass the class of an array, of type {@code T[]}
2293      * @return a VarHandle giving access to elements of an array
2294      * @throws NullPointerException if the arrayClass is null
2295      * @throws IllegalArgumentException if arrayClass is not an array type
2296      * @since 9
2297      */
2298     public static
2299     VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
2300         return VarHandles.makeArrayElementHandle(arrayClass);
2301     }
2302 
2303     /**
2304      * Produces a VarHandle giving access to elements of a {@code byte[]} array
2305      * viewed as if it were a different primitive array type, such as
2306      * {@code int[]} or {@code long[]}.  The shape of the resulting VarHandle is
2307      * {@code (byte[], int : T)}, where the {@code int} coordinate type
2308      * corresponds to an argument that is an index in a {@code byte[]} array,
2309      * and {@code T} is the component type of the given view array class.  The
2310      * returned VarHandle accesses bytes at an index in a {@code byte[]} array,
2311      * composing bytes to or from a value of {@code T} according to the given
2312      * endianness.
2313      * <p>
2314      * The supported component types (variables types) are {@code short},
2315      * {@code char}, {@code int}, {@code long}, {@code float} and
2316      * {@code double}.
2317      * <p>
2318      * Access of bytes at a given index will result in an
2319      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
2320      * or greater than the {@code byte[]} array length minus the size (in bytes)
2321      * of {@code T}.
2322      * <p>
2323      * Access of bytes at an index may be aligned or misaligned for {@code T},
2324      * with respect to the underlying memory address, {@code A} say, associated
2325      * with the array and index.
2326      * If access is misaligned then access for anything other than the
2327      * {@code get} and {@code set} access modes will result in an
2328      * {@code IllegalStateException}.  In such cases atomic access is only
2329      * guaranteed with respect to the largest power of two that divides the GCD
2330      * of {@code A} and the size (in bytes) of {@code T}.
2331      * If access is aligned then following access modes are supported and are
2332      * guaranteed to support atomic access:
2333      * <ul>
2334      * <li>read write access modes for all {@code T};
2335      * <li>atomic update access modes for {@code int}, {@code long},
2336      *     {@code float} or {@code double}.
2337      *     (Future major platform releases of the JDK may support additional
2338      *     types for certain currently unsupported access modes.)
2339      * <li>numeric atomic update access modes for {@code int} and {@code long}.
2340      *     (Future major platform releases of the JDK may support additional
2341      *     numeric types for certain currently unsupported access modes.)
2342      * </ul>
2343      * <p>
2344      * Misaligned access, and therefore atomicity guarantees, may be determined
2345      * for {@code byte[]} arrays without operating on a specific array.  Given
2346      * an {@code index}, {@code T} and it's corresponding boxed type,
2347      * {@code T_BOX}, misalignment may be determined as follows:
2348      * <pre>{@code
2349      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
2350      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
2351      *     alignmentOffset(0, sizeOfT);
2352      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
2353      * boolean isMisaligned = misalignedAtIndex != 0;
2354      * }</pre>
2355      *
2356      * @implNote
2357      * The variable types {@code float} and {@code double} are supported as if
2358      * by transformation to and access with the variable types {@code int} and
2359      * {@code long} respectively.  For example, the transformation of a
2360      * {@code double} value to a long value is performed as if using
2361      * {@link Double#doubleToRawLongBits(double)}, and the reverse
2362      * transformation is performed as if using
2363      * {@link Double#longBitsToDouble(long)}.
2364      *
2365      * @param viewArrayClass the view array class, with a component type of
2366      * type {@code T}
2367      * @param byteOrder the endianness of the view array elements, as
2368      * stored in the underlying {@code byte} array
2369      * @return a VarHandle giving access to elements of a {@code byte[]} array
2370      * viewed as if elements corresponding to the components type of the view
2371      * array class
2372      * @throws NullPointerException if viewArrayClass or byteOrder is null
2373      * @throws IllegalArgumentException if viewArrayClass is not an array type
2374      * @throws UnsupportedOperationException if the component type of
2375      * viewArrayClass is not supported as a variable type
2376      * @since 9
2377      */
2378     public static
2379     VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
2380                                      ByteOrder byteOrder) throws IllegalArgumentException {
2381         Objects.requireNonNull(byteOrder);
2382         return VarHandles.byteArrayViewHandle(viewArrayClass,
2383                                               byteOrder == ByteOrder.BIG_ENDIAN);
2384     }
2385 
2386     /**
2387      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
2388      * viewed as if it were an array of elements of a different primitive
2389      * component type to that of {@code byte}, such as {@code int[]} or
2390      * {@code long[]}.  The shape of the resulting VarHandle is
2391      * {@code (ByteBuffer, int : T)}, where the {@code int} coordinate type
2392      * corresponds to an argument that is an index in a {@code ByteBuffer}, and
2393      * {@code T} is the component type of the given view array class.  The
2394      * returned VarHandle accesses bytes at an index in a {@code ByteBuffer},
2395      * composing bytes to or from a value of {@code T} according to the given
2396      * endianness.
2397      * <p>
2398      * The supported component types (variables types) are {@code short},
2399      * {@code char}, {@code int}, {@code long}, {@code float} and
2400      * {@code double}.
2401      * <p>
2402      * Access will result in a {@code ReadOnlyBufferException} for anything
2403      * other than the read access modes if the {@code ByteBuffer} is read-only.
2404      * <p>
2405      * Access of bytes at a given index will result in an
2406      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
2407      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
2408      * {@code T}.
2409      * <p>
2410      * Access of bytes at an index may be aligned or misaligned for {@code T},
2411      * with respect to the underlying memory address, {@code A} say, associated
2412      * with the {@code ByteBuffer} and index.
2413      * If access is misaligned then access for anything other than the
2414      * {@code get} and {@code set} access modes will result in an
2415      * {@code IllegalStateException}.  In such cases atomic access is only
2416      * guaranteed with respect to the largest power of two that divides the GCD
2417      * of {@code A} and the size (in bytes) of {@code T}.
2418      * If access is aligned then following access modes are supported and are
2419      * guaranteed to support atomic access:
2420      * <ul>
2421      * <li>read write access modes for all {@code T};
2422      * <li>atomic update access modes for {@code int}, {@code long},
2423      *     {@code float} or {@code double}.
2424      *     (Future major platform releases of the JDK may support additional
2425      *     types for certain currently unsupported access modes.)
2426      * <li>numeric atomic update access modes for {@code int} and {@code long}.
2427      *     (Future major platform releases of the JDK may support additional
2428      *     numeric types for certain currently unsupported access modes.)
2429      * </ul>
2430      * <p>
2431      * Misaligned access, and therefore atomicity guarantees, may be determined
2432      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
2433      * {@code index}, {@code T} and it's corresponding boxed type,
2434      * {@code T_BOX}, as follows:
2435      * <pre>{@code
2436      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
2437      * ByteBuffer bb = ...
2438      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
2439      * boolean isMisaligned = misalignedAtIndex != 0;
2440      * }</pre>
2441      *
2442      * @implNote
2443      * The variable types {@code float} and {@code double} are supported as if
2444      * by transformation to and access with the variable types {@code int} and
2445      * {@code long} respectively.  For example, the transformation of a
2446      * {@code double} value to a long value is performed as if using
2447      * {@link Double#doubleToRawLongBits(double)}, and the reverse
2448      * transformation is performed as if using
2449      * {@link Double#longBitsToDouble(long)}.
2450      *
2451      * @param viewArrayClass the view array class, with a component type of
2452      * type {@code T}
2453      * @param byteOrder the endianness of the view array elements, as
2454      * stored in the underlying {@code ByteBuffer} (Note this overrides the
2455      * endianness of a {@code ByteBuffer})
2456      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
2457      * viewed as if elements corresponding to the components type of the view
2458      * array class
2459      * @throws NullPointerException if viewArrayClass or byteOrder is null
2460      * @throws IllegalArgumentException if viewArrayClass is not an array type
2461      * @throws UnsupportedOperationException if the component type of
2462      * viewArrayClass is not supported as a variable type
2463      * @since 9
2464      */
2465     public static
2466     VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
2467                                       ByteOrder byteOrder) throws IllegalArgumentException {
2468         Objects.requireNonNull(byteOrder);
2469         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
2470                                                    byteOrder == ByteOrder.BIG_ENDIAN);
2471     }
2472 
2473 
2474     /// method handle invocation (reflective style)
2475 
2476     /**
2477      * Produces a method handle which will invoke any method handle of the
2478      * given {@code type}, with a given number of trailing arguments replaced by
2479      * a single trailing {@code Object[]} array.
2480      * The resulting invoker will be a method handle with the following
2481      * arguments:
2482      * <ul>
2483      * <li>a single {@code MethodHandle} target
2484      * <li>zero or more leading values (counted by {@code leadingArgCount})
2485      * <li>an {@code Object[]} array containing trailing arguments
2486      * </ul>
2487      * <p>
2488      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
2489      * the indicated {@code type}.
2490      * That is, if the target is exactly of the given {@code type}, it will behave
2491      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
2492      * is used to convert the target to the required {@code type}.
2493      * <p>
2494      * The type of the returned invoker will not be the given {@code type}, but rather
2495      * will have all parameters except the first {@code leadingArgCount}
2496      * replaced by a single array of type {@code Object[]}, which will be
2497      * the final parameter.
2498      * <p>
2499      * Before invoking its target, the invoker will spread the final array, apply
2500      * reference casts as necessary, and unbox and widen primitive arguments.
2501      * If, when the invoker is called, the supplied array argument does
2502      * not have the correct number of elements, the invoker will throw
2503      * an {@link IllegalArgumentException} instead of invoking the target.
2504      * <p>
2505      * This method is equivalent to the following code (though it may be more efficient):
2506      * <blockquote><pre>{@code
2507 MethodHandle invoker = MethodHandles.invoker(type);
2508 int spreadArgCount = type.parameterCount() - leadingArgCount;
2509 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
2510 return invoker;
2511      * }</pre></blockquote>
2512      * This method throws no reflective or security exceptions.
2513      * @param type the desired target type
2514      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
2515      * @return a method handle suitable for invoking any method handle of the given type
2516      * @throws NullPointerException if {@code type} is null
2517      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
2518      *                  the range from 0 to {@code type.parameterCount()} inclusive,
2519      *                  or if the resulting method handle's type would have
2520      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2521      */
2522     public static
2523     MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
2524         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
2525             throw newIllegalArgumentException("bad argument count", leadingArgCount);
2526         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
2527         return type.invokers().spreadInvoker(leadingArgCount);
2528     }
2529 
2530     /**
2531      * Produces a special <em>invoker method handle</em> which can be used to
2532      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
2533      * The resulting invoker will have a type which is
2534      * exactly equal to the desired type, except that it will accept
2535      * an additional leading argument of type {@code MethodHandle}.
2536      * <p>
2537      * This method is equivalent to the following code (though it may be more efficient):
2538      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
2539      *
2540      * <p style="font-size:smaller;">
2541      * <em>Discussion:</em>
2542      * Invoker method handles can be useful when working with variable method handles
2543      * of unknown types.
2544      * For example, to emulate an {@code invokeExact} call to a variable method
2545      * handle {@code M}, extract its type {@code T},
2546      * look up the invoker method {@code X} for {@code T},
2547      * and call the invoker method, as {@code X.invoke(T, A...)}.
2548      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
2549      * is unknown.)
2550      * If spreading, collecting, or other argument transformations are required,
2551      * they can be applied once to the invoker {@code X} and reused on many {@code M}
2552      * method handle values, as long as they are compatible with the type of {@code X}.
2553      * <p style="font-size:smaller;">
2554      * <em>(Note:  The invoker method is not available via the Core Reflection API.
2555      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
2556      * on the declared {@code invokeExact} or {@code invoke} method will raise an
2557      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
2558      * <p>
2559      * This method throws no reflective or security exceptions.
2560      * @param type the desired target type
2561      * @return a method handle suitable for invoking any method handle of the given type
2562      * @throws IllegalArgumentException if the resulting method handle's type would have
2563      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2564      */
2565     public static
2566     MethodHandle exactInvoker(MethodType type) {
2567         return type.invokers().exactInvoker();
2568     }
2569 
2570     /**
2571      * Produces a special <em>invoker method handle</em> which can be used to
2572      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
2573      * The resulting invoker will have a type which is
2574      * exactly equal to the desired type, except that it will accept
2575      * an additional leading argument of type {@code MethodHandle}.
2576      * <p>
2577      * Before invoking its target, if the target differs from the expected type,
2578      * the invoker will apply reference casts as
2579      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
2580      * Similarly, the return value will be converted as necessary.
2581      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
2582      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
2583      * <p>
2584      * This method is equivalent to the following code (though it may be more efficient):
2585      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
2586      * <p style="font-size:smaller;">
2587      * <em>Discussion:</em>
2588      * A {@linkplain MethodType#genericMethodType general method type} is one which
2589      * mentions only {@code Object} arguments and return values.
2590      * An invoker for such a type is capable of calling any method handle
2591      * of the same arity as the general type.
2592      * <p style="font-size:smaller;">
2593      * <em>(Note:  The invoker method is not available via the Core Reflection API.
2594      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
2595      * on the declared {@code invokeExact} or {@code invoke} method will raise an
2596      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
2597      * <p>
2598      * This method throws no reflective or security exceptions.
2599      * @param type the desired target type
2600      * @return a method handle suitable for invoking any method handle convertible to the given type
2601      * @throws IllegalArgumentException if the resulting method handle's type would have
2602      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2603      */
2604     public static
2605     MethodHandle invoker(MethodType type) {
2606         return type.invokers().genericInvoker();
2607     }
2608 
2609     /**
2610      * Produces a special <em>invoker method handle</em> which can be used to
2611      * invoke a signature-polymorphic access mode method on any VarHandle whose
2612      * associated access mode type is compatible with the given type.
2613      * The resulting invoker will have a type which is exactly equal to the
2614      * desired given type, except that it will accept an additional leading
2615      * argument of type {@code VarHandle}.
2616      *
2617      * @param accessMode the VarHandle access mode
2618      * @param type the desired target type
2619      * @return a method handle suitable for invoking an access mode method of
2620      *         any VarHandle whose access mode type is of the given type.
2621      * @since 9
2622      */
2623     static public
2624     MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
2625         return type.invokers().varHandleMethodExactInvoker(accessMode);
2626     }
2627 
2628     /**
2629      * Produces a special <em>invoker method handle</em> which can be used to
2630      * invoke a signature-polymorphic access mode method on any VarHandle whose
2631      * associated access mode type is compatible with the given type.
2632      * The resulting invoker will have a type which is exactly equal to the
2633      * desired given type, except that it will accept an additional leading
2634      * argument of type {@code VarHandle}.
2635      * <p>
2636      * Before invoking its target, if the access mode type differs from the
2637      * desired given type, the invoker will apply reference casts as necessary
2638      * and box, unbox, or widen primitive values, as if by
2639      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
2640      * converted as necessary.
2641      * <p>
2642      * This method is equivalent to the following code (though it may be more
2643      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
2644      *
2645      * @param accessMode the VarHandle access mode
2646      * @param type the desired target type
2647      * @return a method handle suitable for invoking an access mode method of
2648      *         any VarHandle whose access mode type is convertible to the given
2649      *         type.
2650      * @since 9
2651      */
2652     static public
2653     MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
2654         return type.invokers().varHandleMethodInvoker(accessMode);
2655     }
2656 
2657     static /*non-public*/
2658     MethodHandle basicInvoker(MethodType type) {
2659         return type.invokers().basicInvoker();
2660     }
2661 
2662      /// method handle modification (creation from other method handles)
2663 
2664     /**
2665      * Produces a method handle which adapts the type of the
2666      * given method handle to a new type by pairwise argument and return type conversion.
2667      * The original type and new type must have the same number of arguments.
2668      * The resulting method handle is guaranteed to report a type
2669      * which is equal to the desired new type.
2670      * <p>
2671      * If the original type and new type are equal, returns target.
2672      * <p>
2673      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
2674      * and some additional conversions are also applied if those conversions fail.
2675      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
2676      * if possible, before or instead of any conversions done by {@code asType}:
2677      * <ul>
2678      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
2679      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
2680      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
2681      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
2682      *     the boolean is converted to a byte value, 1 for true, 0 for false.
2683      *     (This treatment follows the usage of the bytecode verifier.)
2684      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
2685      *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
2686      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
2687      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
2688      *     then a Java casting conversion (JLS 5.5) is applied.
2689      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
2690      *     widening and/or narrowing.)
2691      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
2692      *     conversion will be applied at runtime, possibly followed
2693      *     by a Java casting conversion (JLS 5.5) on the primitive value,
2694      *     possibly followed by a conversion from byte to boolean by testing
2695      *     the low-order bit.
2696      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
2697      *     and if the reference is null at runtime, a zero value is introduced.
2698      * </ul>
2699      * @param target the method handle to invoke after arguments are retyped
2700      * @param newType the expected type of the new method handle
2701      * @return a method handle which delegates to the target after performing
2702      *           any necessary argument conversions, and arranges for any
2703      *           necessary return value conversions
2704      * @throws NullPointerException if either argument is null
2705      * @throws WrongMethodTypeException if the conversion cannot be made
2706      * @see MethodHandle#asType
2707      */
2708     public static
2709     MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
2710         explicitCastArgumentsChecks(target, newType);
2711         // use the asTypeCache when possible:
2712         MethodType oldType = target.type();
2713         if (oldType == newType)  return target;
2714         if (oldType.explicitCastEquivalentToAsType(newType)) {
2715             return target.asFixedArity().asType(newType);
2716         }
2717         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
2718     }
2719 
2720     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
2721         if (target.type().parameterCount() != newType.parameterCount()) {
2722             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
2723         }
2724     }
2725 
2726     /**
2727      * Produces a method handle which adapts the calling sequence of the
2728      * given method handle to a new type, by reordering the arguments.
2729      * The resulting method handle is guaranteed to report a type
2730      * which is equal to the desired new type.
2731      * <p>
2732      * The given array controls the reordering.
2733      * Call {@code #I} the number of incoming parameters (the value
2734      * {@code newType.parameterCount()}, and call {@code #O} the number
2735      * of outgoing parameters (the value {@code target.type().parameterCount()}).
2736      * Then the length of the reordering array must be {@code #O},
2737      * and each element must be a non-negative number less than {@code #I}.
2738      * For every {@code N} less than {@code #O}, the {@code N}-th
2739      * outgoing argument will be taken from the {@code I}-th incoming
2740      * argument, where {@code I} is {@code reorder[N]}.
2741      * <p>
2742      * No argument or return value conversions are applied.
2743      * The type of each incoming argument, as determined by {@code newType},
2744      * must be identical to the type of the corresponding outgoing parameter
2745      * or parameters in the target method handle.
2746      * The return type of {@code newType} must be identical to the return
2747      * type of the original target.
2748      * <p>
2749      * The reordering array need not specify an actual permutation.
2750      * An incoming argument will be duplicated if its index appears
2751      * more than once in the array, and an incoming argument will be dropped
2752      * if its index does not appear in the array.
2753      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
2754      * incoming arguments which are not mentioned in the reordering array
2755      * may be of any type, as determined only by {@code newType}.
2756      * <blockquote><pre>{@code
2757 import static java.lang.invoke.MethodHandles.*;
2758 import static java.lang.invoke.MethodType.*;
2759 ...
2760 MethodType intfn1 = methodType(int.class, int.class);
2761 MethodType intfn2 = methodType(int.class, int.class, int.class);
2762 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
2763 assert(sub.type().equals(intfn2));
2764 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
2765 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
2766 assert((int)rsub.invokeExact(1, 100) == 99);
2767 MethodHandle add = ... (int x, int y) -> (x+y) ...;
2768 assert(add.type().equals(intfn2));
2769 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
2770 assert(twice.type().equals(intfn1));
2771 assert((int)twice.invokeExact(21) == 42);
2772      * }</pre></blockquote>
2773      * <p>
2774      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
2775      * variable-arity method handle}, even if the original target method handle was.
2776      * @param target the method handle to invoke after arguments are reordered
2777      * @param newType the expected type of the new method handle
2778      * @param reorder an index array which controls the reordering
2779      * @return a method handle which delegates to the target after it
2780      *           drops unused arguments and moves and/or duplicates the other arguments
2781      * @throws NullPointerException if any argument is null
2782      * @throws IllegalArgumentException if the index array length is not equal to
2783      *                  the arity of the target, or if any index array element
2784      *                  not a valid index for a parameter of {@code newType},
2785      *                  or if two corresponding parameter types in
2786      *                  {@code target.type()} and {@code newType} are not identical,
2787      */
2788     public static
2789     MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
2790         reorder = reorder.clone();  // get a private copy
2791         MethodType oldType = target.type();
2792         permuteArgumentChecks(reorder, newType, oldType);
2793         // first detect dropped arguments and handle them separately
2794         int[] originalReorder = reorder;
2795         BoundMethodHandle result = target.rebind();
2796         LambdaForm form = result.form;
2797         int newArity = newType.parameterCount();
2798         // Normalize the reordering into a real permutation,
2799         // by removing duplicates and adding dropped elements.
2800         // This somewhat improves lambda form caching, as well
2801         // as simplifying the transform by breaking it up into steps.
2802         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
2803             if (ddIdx > 0) {
2804                 // We found a duplicated entry at reorder[ddIdx].
2805                 // Example:  (x,y,z)->asList(x,y,z)
2806                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
2807                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
2808                 // The starred element corresponds to the argument
2809                 // deleted by the dupArgumentForm transform.
2810                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
2811                 boolean killFirst = false;
2812                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
2813                     // Set killFirst if the dup is larger than an intervening position.
2814                     // This will remove at least one inversion from the permutation.
2815                     if (dupVal > val) killFirst = true;
2816                 }
2817                 if (!killFirst) {
2818                     srcPos = dstPos;
2819                     dstPos = ddIdx;
2820                 }
2821                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
2822                 assert (reorder[srcPos] == reorder[dstPos]);
2823                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
2824                 // contract the reordering by removing the element at dstPos
2825                 int tailPos = dstPos + 1;
2826                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
2827                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
2828             } else {
2829                 int dropVal = ~ddIdx, insPos = 0;
2830                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
2831                     // Find first element of reorder larger than dropVal.
2832                     // This is where we will insert the dropVal.
2833                     insPos += 1;
2834                 }
2835                 Class<?> ptype = newType.parameterType(dropVal);
2836                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
2837                 oldType = oldType.insertParameterTypes(insPos, ptype);
2838                 // expand the reordering by inserting an element at insPos
2839                 int tailPos = insPos + 1;
2840                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
2841                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
2842                 reorder[insPos] = dropVal;
2843             }
2844             assert (permuteArgumentChecks(reorder, newType, oldType));
2845         }
2846         assert (reorder.length == newArity);  // a perfect permutation
2847         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
2848         form = form.editor().permuteArgumentsForm(1, reorder);
2849         if (newType == result.type() && form == result.internalForm())
2850             return result;
2851         return result.copyWith(newType, form);
2852     }
2853 
2854     /**
2855      * Return an indication of any duplicate or omission in reorder.
2856      * If the reorder contains a duplicate entry, return the index of the second occurrence.
2857      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
2858      * Otherwise, return zero.
2859      * If an element not in [0..newArity-1] is encountered, return reorder.length.
2860      */
2861     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
2862         final int BIT_LIMIT = 63;  // max number of bits in bit mask
2863         if (newArity < BIT_LIMIT) {
2864             long mask = 0;
2865             for (int i = 0; i < reorder.length; i++) {
2866                 int arg = reorder[i];
2867                 if (arg >= newArity) {
2868                     return reorder.length;
2869                 }
2870                 long bit = 1L << arg;
2871                 if ((mask & bit) != 0) {
2872                     return i;  // >0 indicates a dup
2873                 }
2874                 mask |= bit;
2875             }
2876             if (mask == (1L << newArity) - 1) {
2877                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
2878                 return 0;
2879             }
2880             // find first zero
2881             long zeroBit = Long.lowestOneBit(~mask);
2882             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
2883             assert(zeroPos <= newArity);
2884             if (zeroPos == newArity) {
2885                 return 0;
2886             }
2887             return ~zeroPos;
2888         } else {
2889             // same algorithm, different bit set
2890             BitSet mask = new BitSet(newArity);
2891             for (int i = 0; i < reorder.length; i++) {
2892                 int arg = reorder[i];
2893                 if (arg >= newArity) {
2894                     return reorder.length;
2895                 }
2896                 if (mask.get(arg)) {
2897                     return i;  // >0 indicates a dup
2898                 }
2899                 mask.set(arg);
2900             }
2901             int zeroPos = mask.nextClearBit(0);
2902             assert(zeroPos <= newArity);
2903             if (zeroPos == newArity) {
2904                 return 0;
2905             }
2906             return ~zeroPos;
2907         }
2908     }
2909 
2910     private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
2911         if (newType.returnType() != oldType.returnType())
2912             throw newIllegalArgumentException("return types do not match",
2913                     oldType, newType);
2914         if (reorder.length == oldType.parameterCount()) {
2915             int limit = newType.parameterCount();
2916             boolean bad = false;
2917             for (int j = 0; j < reorder.length; j++) {
2918                 int i = reorder[j];
2919                 if (i < 0 || i >= limit) {
2920                     bad = true; break;
2921                 }
2922                 Class<?> src = newType.parameterType(i);
2923                 Class<?> dst = oldType.parameterType(j);
2924                 if (src != dst)
2925                     throw newIllegalArgumentException("parameter types do not match after reorder",
2926                             oldType, newType);
2927             }
2928             if (!bad)  return true;
2929         }
2930         throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
2931     }
2932 
2933     /**
2934      * Produces a method handle of the requested return type which returns the given
2935      * constant value every time it is invoked.
2936      * <p>
2937      * Before the method handle is returned, the passed-in value is converted to the requested type.
2938      * If the requested type is primitive, widening primitive conversions are attempted,
2939      * else reference conversions are attempted.
2940      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
2941      * @param type the return type of the desired method handle
2942      * @param value the value to return
2943      * @return a method handle of the given return type and no arguments, which always returns the given value
2944      * @throws NullPointerException if the {@code type} argument is null
2945      * @throws ClassCastException if the value cannot be converted to the required return type
2946      * @throws IllegalArgumentException if the given type is {@code void.class}
2947      */
2948     public static
2949     MethodHandle constant(Class<?> type, Object value) {
2950         if (type.isPrimitive()) {
2951             if (type == void.class)
2952                 throw newIllegalArgumentException("void type");
2953             Wrapper w = Wrapper.forPrimitiveType(type);
2954             value = w.convert(value, type);
2955             if (w.zero().equals(value))
2956                 return zero(w, type);
2957             return insertArguments(identity(type), 0, value);
2958         } else {
2959             if (value == null)
2960                 return zero(Wrapper.OBJECT, type);
2961             return identity(type).bindTo(value);
2962         }
2963     }
2964 
2965     /**
2966      * Produces a method handle which returns its sole argument when invoked.
2967      * @param type the type of the sole parameter and return value of the desired method handle
2968      * @return a unary method handle which accepts and returns the given type
2969      * @throws NullPointerException if the argument is null
2970      * @throws IllegalArgumentException if the given type is {@code void.class}
2971      */
2972     public static
2973     MethodHandle identity(Class<?> type) {
2974         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
2975         int pos = btw.ordinal();
2976         MethodHandle ident = IDENTITY_MHS[pos];
2977         if (ident == null) {
2978             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
2979         }
2980         if (ident.type().returnType() == type)
2981             return ident;
2982         // something like identity(Foo.class); do not bother to intern these
2983         assert (btw == Wrapper.OBJECT);
2984         return makeIdentity(type);
2985     }
2986 
2987     /**
2988      * Produces a constant method handle of the requested return type which
2989      * returns the default value for that type every time it is invoked.
2990      * The resulting constant method handle will have no side effects.
2991      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
2992      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
2993      * since {@code explicitCastArguments} converts {@code null} to default values.
2994      * @param type the expected return type of the desired method handle
2995      * @return a constant method handle that takes no arguments
2996      *         and returns the default value of the given type (or void, if the type is void)
2997      * @throws NullPointerException if the argument is null
2998      * @see MethodHandles#constant
2999      * @see MethodHandles#empty
3000      * @since 9
3001      */
3002     public static  MethodHandle zero(Class<?> type) {
3003         Objects.requireNonNull(type);
3004         return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
3005     }
3006 
3007     private static MethodHandle identityOrVoid(Class<?> type) {
3008         return type == void.class ? zero(type) : identity(type);
3009     }
3010 
3011     /**
3012      * Produces a method handle of the requested type which ignores any arguments, does nothing,
3013      * and returns a suitable default depending on the return type.
3014      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
3015      * <p>The returned method handle is equivalent to
3016      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
3017      * <p>
3018      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
3019      * {@code guardWithTest(pred, target, empty(target.type())}.
3020      * @param type the type of the desired method handle
3021      * @return a constant method handle of the given type, which returns a default value of the given return type
3022      * @throws NullPointerException if the argument is null
3023      * @see MethodHandles#zero
3024      * @see MethodHandles#constant
3025      * @since 9
3026      */
3027     public static  MethodHandle empty(MethodType type) {
3028         Objects.requireNonNull(type);
3029         return dropArguments(zero(type.returnType()), 0, type.parameterList());
3030     }
3031 
3032     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.values().length];
3033     private static MethodHandle makeIdentity(Class<?> ptype) {
3034         MethodType mtype = methodType(ptype, ptype);
3035         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
3036         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
3037     }
3038 
3039     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
3040         int pos = btw.ordinal();
3041         MethodHandle zero = ZERO_MHS[pos];
3042         if (zero == null) {
3043             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
3044         }
3045         if (zero.type().returnType() == rtype)
3046             return zero;
3047         assert(btw == Wrapper.OBJECT);
3048         return makeZero(rtype);
3049     }
3050     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.values().length];
3051     private static MethodHandle makeZero(Class<?> rtype) {
3052         MethodType mtype = methodType(rtype);
3053         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
3054         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
3055     }
3056 
3057     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
3058         // Simulate a CAS, to avoid racy duplication of results.
3059         MethodHandle prev = cache[pos];
3060         if (prev != null) return prev;
3061         return cache[pos] = value;
3062     }
3063 
3064     /**
3065      * Provides a target method handle with one or more <em>bound arguments</em>
3066      * in advance of the method handle's invocation.
3067      * The formal parameters to the target corresponding to the bound
3068      * arguments are called <em>bound parameters</em>.
3069      * Returns a new method handle which saves away the bound arguments.
3070      * When it is invoked, it receives arguments for any non-bound parameters,
3071      * binds the saved arguments to their corresponding parameters,
3072      * and calls the original target.
3073      * <p>
3074      * The type of the new method handle will drop the types for the bound
3075      * parameters from the original target type, since the new method handle
3076      * will no longer require those arguments to be supplied by its callers.
3077      * <p>
3078      * Each given argument object must match the corresponding bound parameter type.
3079      * If a bound parameter type is a primitive, the argument object
3080      * must be a wrapper, and will be unboxed to produce the primitive value.
3081      * <p>
3082      * The {@code pos} argument selects which parameters are to be bound.
3083      * It may range between zero and <i>N-L</i> (inclusively),
3084      * where <i>N</i> is the arity of the target method handle
3085      * and <i>L</i> is the length of the values array.
3086      * <p>
3087      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3088      * variable-arity method handle}, even if the original target method handle was.
3089      * @param target the method handle to invoke after the argument is inserted
3090      * @param pos where to insert the argument (zero for the first)
3091      * @param values the series of arguments to insert
3092      * @return a method handle which inserts an additional argument,
3093      *         before calling the original method handle
3094      * @throws NullPointerException if the target or the {@code values} array is null
3095      * @see MethodHandle#bindTo
3096      */
3097     public static
3098     MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
3099         int insCount = values.length;
3100         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
3101         if (insCount == 0)  return target;
3102         BoundMethodHandle result = target.rebind();
3103         for (int i = 0; i < insCount; i++) {
3104             Object value = values[i];
3105             Class<?> ptype = ptypes[pos+i];
3106             if (ptype.isPrimitive()) {
3107                 result = insertArgumentPrimitive(result, pos, ptype, value);
3108             } else {
3109                 value = ptype.cast(value);  // throw CCE if needed
3110                 result = result.bindArgumentL(pos, value);
3111             }
3112         }
3113         return result;
3114     }
3115 
3116     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
3117                                                              Class<?> ptype, Object value) {
3118         Wrapper w = Wrapper.forPrimitiveType(ptype);
3119         // perform unboxing and/or primitive conversion
3120         value = w.convert(value, ptype);
3121         switch (w) {
3122         case INT:     return result.bindArgumentI(pos, (int)value);
3123         case LONG:    return result.bindArgumentJ(pos, (long)value);
3124         case FLOAT:   return result.bindArgumentF(pos, (float)value);
3125         case DOUBLE:  return result.bindArgumentD(pos, (double)value);
3126         default:      return result.bindArgumentI(pos, ValueConversions.widenSubword(value));
3127         }
3128     }
3129 
3130     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
3131         MethodType oldType = target.type();
3132         int outargs = oldType.parameterCount();
3133         int inargs  = outargs - insCount;
3134         if (inargs < 0)
3135             throw newIllegalArgumentException("too many values to insert");
3136         if (pos < 0 || pos > inargs)
3137             throw newIllegalArgumentException("no argument type to append");
3138         return oldType.ptypes();
3139     }
3140 
3141     /**
3142      * Produces a method handle which will discard some dummy arguments
3143      * before calling some other specified <i>target</i> method handle.
3144      * The type of the new method handle will be the same as the target's type,
3145      * except it will also include the dummy argument types,
3146      * at some given position.
3147      * <p>
3148      * The {@code pos} argument may range between zero and <i>N</i>,
3149      * where <i>N</i> is the arity of the target.
3150      * If {@code pos} is zero, the dummy arguments will precede
3151      * the target's real arguments; if {@code pos} is <i>N</i>
3152      * they will come after.
3153      * <p>
3154      * <b>Example:</b>
3155      * <blockquote><pre>{@code
3156 import static java.lang.invoke.MethodHandles.*;
3157 import static java.lang.invoke.MethodType.*;
3158 ...
3159 MethodHandle cat = lookup().findVirtual(String.class,
3160   "concat", methodType(String.class, String.class));
3161 assertEquals("xy", (String) cat.invokeExact("x", "y"));
3162 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
3163 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
3164 assertEquals(bigType, d0.type());
3165 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
3166      * }</pre></blockquote>
3167      * <p>
3168      * This method is also equivalent to the following code:
3169      * <blockquote><pre>
3170      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
3171      * </pre></blockquote>
3172      * @param target the method handle to invoke after the arguments are dropped
3173      * @param valueTypes the type(s) of the argument(s) to drop
3174      * @param pos position of first argument to drop (zero for the leftmost)
3175      * @return a method handle which drops arguments of the given types,
3176      *         before calling the original method handle
3177      * @throws NullPointerException if the target is null,
3178      *                              or if the {@code valueTypes} list or any of its elements is null
3179      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
3180      *                  or if {@code pos} is negative or greater than the arity of the target,
3181      *                  or if the new method handle's type would have too many parameters
3182      */
3183     public static
3184     MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
3185         MethodType oldType = target.type();  // get NPE
3186         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
3187         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
3188         if (dropped == 0)  return target;
3189         BoundMethodHandle result = target.rebind();
3190         LambdaForm lform = result.form;
3191         int insertFormArg = 1 + pos;
3192         for (Class<?> ptype : valueTypes) {
3193             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
3194         }
3195         result = result.copyWith(newType, lform);
3196         return result;
3197     }
3198 
3199     private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
3200         int dropped = valueTypes.size();
3201         MethodType.checkSlotCount(dropped);
3202         int outargs = oldType.parameterCount();
3203         int inargs  = outargs + dropped;
3204         if (pos < 0 || pos > outargs)
3205             throw newIllegalArgumentException("no argument type to remove"
3206                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
3207                     );
3208         return dropped;
3209     }
3210 
3211     /**
3212      * Produces a method handle which will discard some dummy arguments
3213      * before calling some other specified <i>target</i> method handle.
3214      * The type of the new method handle will be the same as the target's type,
3215      * except it will also include the dummy argument types,
3216      * at some given position.
3217      * <p>
3218      * The {@code pos} argument may range between zero and <i>N</i>,
3219      * where <i>N</i> is the arity of the target.
3220      * If {@code pos} is zero, the dummy arguments will precede
3221      * the target's real arguments; if {@code pos} is <i>N</i>
3222      * they will come after.
3223      * @apiNote
3224      * <blockquote><pre>{@code
3225 import static java.lang.invoke.MethodHandles.*;
3226 import static java.lang.invoke.MethodType.*;
3227 ...
3228 MethodHandle cat = lookup().findVirtual(String.class,
3229   "concat", methodType(String.class, String.class));
3230 assertEquals("xy", (String) cat.invokeExact("x", "y"));
3231 MethodHandle d0 = dropArguments(cat, 0, String.class);
3232 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
3233 MethodHandle d1 = dropArguments(cat, 1, String.class);
3234 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
3235 MethodHandle d2 = dropArguments(cat, 2, String.class);
3236 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
3237 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
3238 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
3239      * }</pre></blockquote>
3240      * <p>
3241      * This method is also equivalent to the following code:
3242      * <blockquote><pre>
3243      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
3244      * </pre></blockquote>
3245      * @param target the method handle to invoke after the arguments are dropped
3246      * @param valueTypes the type(s) of the argument(s) to drop
3247      * @param pos position of first argument to drop (zero for the leftmost)
3248      * @return a method handle which drops arguments of the given types,
3249      *         before calling the original method handle
3250      * @throws NullPointerException if the target is null,
3251      *                              or if the {@code valueTypes} array or any of its elements is null
3252      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
3253      *                  or if {@code pos} is negative or greater than the arity of the target,
3254      *                  or if the new method handle's type would have
3255      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
3256      */
3257     public static
3258     MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
3259         return dropArguments(target, pos, Arrays.asList(valueTypes));
3260     }
3261 
3262     // private version which allows caller some freedom with error handling
3263     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
3264                                       boolean nullOnFailure) {
3265         List<Class<?>> oldTypes = target.type().parameterList();
3266         int match = oldTypes.size();
3267         if (skip != 0) {
3268             if (skip < 0 || skip > match) {
3269                 throw newIllegalArgumentException("illegal skip", skip, target);
3270             }
3271             oldTypes = oldTypes.subList(skip, match);
3272             match -= skip;
3273         }
3274         List<Class<?>> addTypes = newTypes;
3275         int add = addTypes.size();
3276         if (pos != 0) {
3277             if (pos < 0 || pos > add) {
3278                 throw newIllegalArgumentException("illegal pos", pos, newTypes);
3279             }
3280             addTypes = addTypes.subList(pos, add);
3281             add -= pos; assert(addTypes.size() == add);
3282         }
3283         // Do not add types which already match the existing arguments.
3284         if (match > add || !oldTypes.equals(addTypes.subList(0, match))) {
3285             if (nullOnFailure) {
3286                 return null;
3287             }
3288             throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes);
3289         }
3290         addTypes = addTypes.subList(match, add);
3291         add -= match; assert(addTypes.size() == add);
3292         // newTypes:     (   P*[pos], M*[match], A*[add] )
3293         // target: ( S*[skip],        M*[match]  )
3294         MethodHandle adapter = target;
3295         if (add > 0) {
3296             adapter = dropArguments(adapter, skip+ match, addTypes);
3297         }
3298         // adapter: (S*[skip],        M*[match], A*[add] )
3299         if (pos > 0) {
3300             adapter = dropArguments(adapter, skip, newTypes.subList(0, pos));
3301        }
3302         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
3303         return adapter;
3304     }
3305 
3306     /**
3307      * Adapts a target method handle to match the given parameter type list, if necessary, by adding dummy arguments.
3308      * Some leading parameters are first skipped; they will be left unchanged and are otherwise ignored.
3309      * The remaining types in the target's parameter type list must be contained as a sub-list of the given type list,
3310      * at the given position.
3311      * Any non-matching parameter types (before or after the matching sub-list) are inserted in corresponding
3312      * positions of the target method handle's parameters, as if by {@link #dropArguments}.
3313      * (More precisely, elements in the new list before {@code pos} are inserted into the target list at {@code skip},
3314      * while elements in the new list after the match beginning at {@code pos} are inserted at the end of the
3315      * target list.)
3316      * The target's return type will be unchanged.
3317      * @apiNote
3318      * Two method handles whose argument lists are "effectively identical" (i.e., identical
3319      * in a common prefix) may be mutually converted to a common type
3320      * by two calls to {@code dropArgumentsToMatch}, as follows:
3321      * <blockquote><pre>{@code
3322 import static java.lang.invoke.MethodHandles.*;
3323 import static java.lang.invoke.MethodType.*;
3324 ...
3325 ...
3326 MethodHandle h0 = constant(boolean.class, true);
3327 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
3328 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
3329 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
3330 if (h1.type().parameterCount() < h2.type().parameterCount())
3331     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
3332 else
3333     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
3334 MethodHandle h3 = guardWithTest(h0, h1, h2);
3335 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
3336      * }</pre></blockquote>
3337      * @param target the method handle to adapt
3338      * @param skip number of targets parameters to disregard (they will be unchanged)
3339      * @param newTypes the desired argument list of the method handle
3340      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
3341      * @return a possibly adapted method handle
3342      * @throws NullPointerException if either argument is null
3343      * @throws IllegalArgumentException
3344      *         if either index is out of range in its corresponding list, or
3345      *         if the non-skipped target parameter types match the new types at {@code pos}
3346      * @since 9
3347      */
3348     public static
3349     MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
3350         Objects.requireNonNull(target);
3351         Objects.requireNonNull(newTypes);
3352         return dropArgumentsToMatch(target, skip, newTypes, pos, false);
3353     }
3354 
3355     /**
3356      * Adapts a target method handle by pre-processing
3357      * one or more of its arguments, each with its own unary filter function,
3358      * and then calling the target with each pre-processed argument
3359      * replaced by the result of its corresponding filter function.
3360      * <p>
3361      * The pre-processing is performed by one or more method handles,
3362      * specified in the elements of the {@code filters} array.
3363      * The first element of the filter array corresponds to the {@code pos}
3364      * argument of the target, and so on in sequence.
3365      * <p>
3366      * Null arguments in the array are treated as identity functions,
3367      * and the corresponding arguments left unchanged.
3368      * (If there are no non-null elements in the array, the original target is returned.)
3369      * Each filter is applied to the corresponding argument of the adapter.
3370      * <p>
3371      * If a filter {@code F} applies to the {@code N}th argument of
3372      * the target, then {@code F} must be a method handle which
3373      * takes exactly one argument.  The type of {@code F}'s sole argument
3374      * replaces the corresponding argument type of the target
3375      * in the resulting adapted method handle.
3376      * The return type of {@code F} must be identical to the corresponding
3377      * parameter type of the target.
3378      * <p>
3379      * It is an error if there are elements of {@code filters}
3380      * (null or not)
3381      * which do not correspond to argument positions in the target.
3382      * <p><b>Example:</b>
3383      * <blockquote><pre>{@code
3384 import static java.lang.invoke.MethodHandles.*;
3385 import static java.lang.invoke.MethodType.*;
3386 ...
3387 MethodHandle cat = lookup().findVirtual(String.class,
3388   "concat", methodType(String.class, String.class));
3389 MethodHandle upcase = lookup().findVirtual(String.class,
3390   "toUpperCase", methodType(String.class));
3391 assertEquals("xy", (String) cat.invokeExact("x", "y"));
3392 MethodHandle f0 = filterArguments(cat, 0, upcase);
3393 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
3394 MethodHandle f1 = filterArguments(cat, 1, upcase);
3395 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
3396 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
3397 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
3398      * }</pre></blockquote>
3399      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3400      * denotes the return type of both the {@code target} and resulting adapter.
3401      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
3402      * of the parameters and arguments that precede and follow the filter position
3403      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
3404      * values of the filtered parameters and arguments; they also represent the
3405      * return types of the {@code filter[i]} handles. The latter accept arguments
3406      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
3407      * the resulting adapter.
3408      * <blockquote><pre>{@code
3409      * T target(P... p, A[i]... a[i], B... b);
3410      * A[i] filter[i](V[i]);
3411      * T adapter(P... p, V[i]... v[i], B... b) {
3412      *   return target(p..., filter[i](v[i])..., b...);
3413      * }
3414      * }</pre></blockquote>
3415      * <p>
3416      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3417      * variable-arity method handle}, even if the original target method handle was.
3418      *
3419      * @param target the method handle to invoke after arguments are filtered
3420      * @param pos the position of the first argument to filter
3421      * @param filters method handles to call initially on filtered arguments
3422      * @return method handle which incorporates the specified argument filtering logic
3423      * @throws NullPointerException if the target is null
3424      *                              or if the {@code filters} array is null
3425      * @throws IllegalArgumentException if a non-null element of {@code filters}
3426      *          does not match a corresponding argument type of target as described above,
3427      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
3428      *          or if the resulting method handle's type would have
3429      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
3430      */
3431     public static
3432     MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
3433         filterArgumentsCheckArity(target, pos, filters);
3434         MethodHandle adapter = target;
3435         int curPos = pos-1;  // pre-incremented
3436         for (MethodHandle filter : filters) {
3437             curPos += 1;
3438             if (filter == null)  continue;  // ignore null elements of filters
3439             adapter = filterArgument(adapter, curPos, filter);
3440         }
3441         return adapter;
3442     }
3443 
3444     /*non-public*/ static
3445     MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
3446         filterArgumentChecks(target, pos, filter);
3447         MethodType targetType = target.type();
3448         MethodType filterType = filter.type();
3449         BoundMethodHandle result = target.rebind();
3450         Class<?> newParamType = filterType.parameterType(0);
3451         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
3452         MethodType newType = targetType.changeParameterType(pos, newParamType);
3453         result = result.copyWithExtendL(newType, lform, filter);
3454         return result;
3455     }
3456 
3457     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
3458         MethodType targetType = target.type();
3459         int maxPos = targetType.parameterCount();
3460         if (pos + filters.length > maxPos)
3461             throw newIllegalArgumentException("too many filters");
3462     }
3463 
3464     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
3465         MethodType targetType = target.type();
3466         MethodType filterType = filter.type();
3467         if (filterType.parameterCount() != 1
3468             || filterType.returnType() != targetType.parameterType(pos))
3469             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3470     }
3471 
3472     /**
3473      * Adapts a target method handle by pre-processing
3474      * a sub-sequence of its arguments with a filter (another method handle).
3475      * The pre-processed arguments are replaced by the result (if any) of the
3476      * filter function.
3477      * The target is then called on the modified (usually shortened) argument list.
3478      * <p>
3479      * If the filter returns a value, the target must accept that value as
3480      * its argument in position {@code pos}, preceded and/or followed by
3481      * any arguments not passed to the filter.
3482      * If the filter returns void, the target must accept all arguments
3483      * not passed to the filter.
3484      * No arguments are reordered, and a result returned from the filter
3485      * replaces (in order) the whole subsequence of arguments originally
3486      * passed to the adapter.
3487      * <p>
3488      * The argument types (if any) of the filter
3489      * replace zero or one argument types of the target, at position {@code pos},
3490      * in the resulting adapted method handle.
3491      * The return type of the filter (if any) must be identical to the
3492      * argument type of the target at position {@code pos}, and that target argument
3493      * is supplied by the return value of the filter.
3494      * <p>
3495      * In all cases, {@code pos} must be greater than or equal to zero, and
3496      * {@code pos} must also be less than or equal to the target's arity.
3497      * <p><b>Example:</b>
3498      * <blockquote><pre>{@code
3499 import static java.lang.invoke.MethodHandles.*;
3500 import static java.lang.invoke.MethodType.*;
3501 ...
3502 MethodHandle deepToString = publicLookup()
3503   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
3504 
3505 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
3506 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
3507 
3508 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
3509 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
3510 
3511 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
3512 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
3513 assertEquals("[top, [up, down], strange]",
3514              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
3515 
3516 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
3517 assertEquals("[top, [up, down], [strange]]",
3518              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
3519 
3520 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
3521 assertEquals("[top, [[up, down, strange], charm], bottom]",
3522              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
3523      * }</pre></blockquote>
3524      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3525      * represents the return type of the {@code target} and resulting adapter.
3526      * {@code V}/{@code v} stand for the return type and value of the
3527      * {@code filter}, which are also found in the signature and arguments of
3528      * the {@code target}, respectively, unless {@code V} is {@code void}.
3529      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
3530      * and values preceding and following the collection position, {@code pos},
3531      * in the {@code target}'s signature. They also turn up in the resulting
3532      * adapter's signature and arguments, where they surround
3533      * {@code B}/{@code b}, which represent the parameter types and arguments
3534      * to the {@code filter} (if any).
3535      * <blockquote><pre>{@code
3536      * T target(A...,V,C...);
3537      * V filter(B...);
3538      * T adapter(A... a,B... b,C... c) {
3539      *   V v = filter(b...);
3540      *   return target(a...,v,c...);
3541      * }
3542      * // and if the filter has no arguments:
3543      * T target2(A...,V,C...);
3544      * V filter2();
3545      * T adapter2(A... a,C... c) {
3546      *   V v = filter2();
3547      *   return target2(a...,v,c...);
3548      * }
3549      * // and if the filter has a void return:
3550      * T target3(A...,C...);
3551      * void filter3(B...);
3552      * T adapter3(A... a,B... b,C... c) {
3553      *   filter3(b...);
3554      *   return target3(a...,c...);
3555      * }
3556      * }</pre></blockquote>
3557      * <p>
3558      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
3559      * one which first "folds" the affected arguments, and then drops them, in separate
3560      * steps as follows:
3561      * <blockquote><pre>{@code
3562      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
3563      * mh = MethodHandles.foldArguments(mh, coll); //step 1
3564      * }</pre></blockquote>
3565      * If the target method handle consumes no arguments besides than the result
3566      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
3567      * is equivalent to {@code filterReturnValue(coll, mh)}.
3568      * If the filter method handle {@code coll} consumes one argument and produces
3569      * a non-void result, then {@code collectArguments(mh, N, coll)}
3570      * is equivalent to {@code filterArguments(mh, N, coll)}.
3571      * Other equivalences are possible but would require argument permutation.
3572      * <p>
3573      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3574      * variable-arity method handle}, even if the original target method handle was.
3575      *
3576      * @param target the method handle to invoke after filtering the subsequence of arguments
3577      * @param pos the position of the first adapter argument to pass to the filter,
3578      *            and/or the target argument which receives the result of the filter
3579      * @param filter method handle to call on the subsequence of arguments
3580      * @return method handle which incorporates the specified argument subsequence filtering logic
3581      * @throws NullPointerException if either argument is null
3582      * @throws IllegalArgumentException if the return type of {@code filter}
3583      *          is non-void and is not the same as the {@code pos} argument of the target,
3584      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
3585      *          or if the resulting method handle's type would have
3586      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
3587      * @see MethodHandles#foldArguments
3588      * @see MethodHandles#filterArguments
3589      * @see MethodHandles#filterReturnValue
3590      */
3591     public static
3592     MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
3593         MethodType newType = collectArgumentsChecks(target, pos, filter);
3594         MethodType collectorType = filter.type();
3595         BoundMethodHandle result = target.rebind();
3596         LambdaForm lform;
3597         if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) {
3598             lform = result.editor().collectArgumentArrayForm(1 + pos, filter);
3599             if (lform != null) {
3600                 return result.copyWith(newType, lform);
3601             }
3602         }
3603         lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
3604         return result.copyWithExtendL(newType, lform, filter);
3605     }
3606 
3607     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
3608         MethodType targetType = target.type();
3609         MethodType filterType = filter.type();
3610         Class<?> rtype = filterType.returnType();
3611         List<Class<?>> filterArgs = filterType.parameterList();
3612         if (rtype == void.class) {
3613             return targetType.insertParameterTypes(pos, filterArgs);
3614         }
3615         if (rtype != targetType.parameterType(pos)) {
3616             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3617         }
3618         return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
3619     }
3620 
3621     /**
3622      * Adapts a target method handle by post-processing
3623      * its return value (if any) with a filter (another method handle).
3624      * The result of the filter is returned from the adapter.
3625      * <p>
3626      * If the target returns a value, the filter must accept that value as
3627      * its only argument.
3628      * If the target returns void, the filter must accept no arguments.
3629      * <p>
3630      * The return type of the filter
3631      * replaces the return type of the target
3632      * in the resulting adapted method handle.
3633      * The argument type of the filter (if any) must be identical to the
3634      * return type of the target.
3635      * <p><b>Example:</b>
3636      * <blockquote><pre>{@code
3637 import static java.lang.invoke.MethodHandles.*;
3638 import static java.lang.invoke.MethodType.*;
3639 ...
3640 MethodHandle cat = lookup().findVirtual(String.class,
3641   "concat", methodType(String.class, String.class));
3642 MethodHandle length = lookup().findVirtual(String.class,
3643   "length", methodType(int.class));
3644 System.out.println((String) cat.invokeExact("x", "y")); // xy
3645 MethodHandle f0 = filterReturnValue(cat, length);
3646 System.out.println((int) f0.invokeExact("x", "y")); // 2
3647      * }</pre></blockquote>
3648      * <p>Here is pseudocode for the resulting adapter. In the code,
3649      * {@code T}/{@code t} represent the result type and value of the
3650      * {@code target}; {@code V}, the result type of the {@code filter}; and
3651      * {@code A}/{@code a}, the types and values of the parameters and arguments
3652      * of the {@code target} as well as the resulting adapter.
3653      * <blockquote><pre>{@code
3654      * T target(A...);
3655      * V filter(T);
3656      * V adapter(A... a) {
3657      *   T t = target(a...);
3658      *   return filter(t);
3659      * }
3660      * // and if the target has a void return:
3661      * void target2(A...);
3662      * V filter2();
3663      * V adapter2(A... a) {
3664      *   target2(a...);
3665      *   return filter2();
3666      * }
3667      * // and if the filter has a void return:
3668      * T target3(A...);
3669      * void filter3(V);
3670      * void adapter3(A... a) {
3671      *   T t = target3(a...);
3672      *   filter3(t);
3673      * }
3674      * }</pre></blockquote>
3675      * <p>
3676      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3677      * variable-arity method handle}, even if the original target method handle was.
3678      * @param target the method handle to invoke before filtering the return value
3679      * @param filter method handle to call on the return value
3680      * @return method handle which incorporates the specified return value filtering logic
3681      * @throws NullPointerException if either argument is null
3682      * @throws IllegalArgumentException if the argument list of {@code filter}
3683      *          does not match the return type of target as described above
3684      */
3685     public static
3686     MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
3687         MethodType targetType = target.type();
3688         MethodType filterType = filter.type();
3689         filterReturnValueChecks(targetType, filterType);
3690         BoundMethodHandle result = target.rebind();
3691         BasicType rtype = BasicType.basicType(filterType.returnType());
3692         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
3693         MethodType newType = targetType.changeReturnType(filterType.returnType());
3694         result = result.copyWithExtendL(newType, lform, filter);
3695         return result;
3696     }
3697 
3698     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
3699         Class<?> rtype = targetType.returnType();
3700         int filterValues = filterType.parameterCount();
3701         if (filterValues == 0
3702                 ? (rtype != void.class)
3703                 : (rtype != filterType.parameterType(0)))
3704             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3705     }
3706 
3707     /**
3708      * Adapts a target method handle by pre-processing
3709      * some of its arguments, and then calling the target with
3710      * the result of the pre-processing, inserted into the original
3711      * sequence of arguments.
3712      * <p>
3713      * The pre-processing is performed by {@code combiner}, a second method handle.
3714      * Of the arguments passed to the adapter, the first {@code N} arguments
3715      * are copied to the combiner, which is then called.
3716      * (Here, {@code N} is defined as the parameter count of the combiner.)
3717      * After this, control passes to the target, with any result
3718      * from the combiner inserted before the original {@code N} incoming
3719      * arguments.
3720      * <p>
3721      * If the combiner returns a value, the first parameter type of the target
3722      * must be identical with the return type of the combiner, and the next
3723      * {@code N} parameter types of the target must exactly match the parameters
3724      * of the combiner.
3725      * <p>
3726      * If the combiner has a void return, no result will be inserted,
3727      * and the first {@code N} parameter types of the target
3728      * must exactly match the parameters of the combiner.
3729      * <p>
3730      * The resulting adapter is the same type as the target, except that the
3731      * first parameter type is dropped,
3732      * if it corresponds to the result of the combiner.
3733      * <p>
3734      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
3735      * that either the combiner or the target does not wish to receive.
3736      * If some of the incoming arguments are destined only for the combiner,
3737      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
3738      * arguments will not need to be live on the stack on entry to the
3739      * target.)
3740      * <p><b>Example:</b>
3741      * <blockquote><pre>{@code
3742 import static java.lang.invoke.MethodHandles.*;
3743 import static java.lang.invoke.MethodType.*;
3744 ...
3745 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
3746   "println", methodType(void.class, String.class))
3747     .bindTo(System.out);
3748 MethodHandle cat = lookup().findVirtual(String.class,
3749   "concat", methodType(String.class, String.class));
3750 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
3751 MethodHandle catTrace = foldArguments(cat, trace);
3752 // also prints "boo":
3753 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
3754      * }</pre></blockquote>
3755      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3756      * represents the result type of the {@code target} and resulting adapter.
3757      * {@code V}/{@code v} represent the type and value of the parameter and argument
3758      * of {@code target} that precedes the folding position; {@code V} also is
3759      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
3760      * types and values of the {@code N} parameters and arguments at the folding
3761      * position. {@code B}/{@code b} represent the types and values of the
3762      * {@code target} parameters and arguments that follow the folded parameters
3763      * and arguments.
3764      * <blockquote><pre>{@code
3765      * // there are N arguments in A...
3766      * T target(V, A[N]..., B...);
3767      * V combiner(A...);
3768      * T adapter(A... a, B... b) {
3769      *   V v = combiner(a...);
3770      *   return target(v, a..., b...);
3771      * }
3772      * // and if the combiner has a void return:
3773      * T target2(A[N]..., B...);
3774      * void combiner2(A...);
3775      * T adapter2(A... a, B... b) {
3776      *   combiner2(a...);
3777      *   return target2(a..., b...);
3778      * }
3779      * }</pre></blockquote>
3780      * <p>
3781      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3782      * variable-arity method handle}, even if the original target method handle was.
3783      * @param target the method handle to invoke after arguments are combined
3784      * @param combiner method handle to call initially on the incoming arguments
3785      * @return method handle which incorporates the specified argument folding logic
3786      * @throws NullPointerException if either argument is null
3787      * @throws IllegalArgumentException if {@code combiner}'s return type
3788      *          is non-void and not the same as the first argument type of
3789      *          the target, or if the initial {@code N} argument types
3790      *          of the target
3791      *          (skipping one matching the {@code combiner}'s return type)
3792      *          are not identical with the argument types of {@code combiner}
3793      */
3794     public static
3795     MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
3796         return foldArguments(target, 0, combiner);
3797     }
3798 
3799     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
3800         int foldArgs   = combinerType.parameterCount();
3801         Class<?> rtype = combinerType.returnType();
3802         int foldVals = rtype == void.class ? 0 : 1;
3803         int afterInsertPos = foldPos + foldVals;
3804         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
3805         if (ok && !(combinerType.parameterList()
3806                     .equals(targetType.parameterList().subList(afterInsertPos,
3807                                                                afterInsertPos + foldArgs))))
3808             ok = false;
3809         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
3810             ok = false;
3811         if (!ok)
3812             throw misMatchedTypes("target and combiner types", targetType, combinerType);
3813         return rtype;
3814     }
3815 
3816     /**
3817      * Makes a method handle which adapts a target method handle,
3818      * by guarding it with a test, a boolean-valued method handle.
3819      * If the guard fails, a fallback handle is called instead.
3820      * All three method handles must have the same corresponding
3821      * argument and return types, except that the return type
3822      * of the test must be boolean, and the test is allowed
3823      * to have fewer arguments than the other two method handles.
3824      * <p>
3825      * Here is pseudocode for the resulting adapter. In the code, {@code T}
3826      * represents the uniform result type of the three involved handles;
3827      * {@code A}/{@code a}, the types and values of the {@code target}
3828      * parameters and arguments that are consumed by the {@code test}; and
3829      * {@code B}/{@code b}, those types and values of the {@code target}
3830      * parameters and arguments that are not consumed by the {@code test}.
3831      * <blockquote><pre>{@code
3832      * boolean test(A...);
3833      * T target(A...,B...);
3834      * T fallback(A...,B...);
3835      * T adapter(A... a,B... b) {
3836      *   if (test(a...))
3837      *     return target(a..., b...);
3838      *   else
3839      *     return fallback(a..., b...);
3840      * }
3841      * }</pre></blockquote>
3842      * Note that the test arguments ({@code a...} in the pseudocode) cannot
3843      * be modified by execution of the test, and so are passed unchanged
3844      * from the caller to the target or fallback as appropriate.
3845      * @param test method handle used for test, must return boolean
3846      * @param target method handle to call if test passes
3847      * @param fallback method handle to call if test fails
3848      * @return method handle which incorporates the specified if/then/else logic
3849      * @throws NullPointerException if any argument is null
3850      * @throws IllegalArgumentException if {@code test} does not return boolean,
3851      *          or if all three method types do not match (with the return
3852      *          type of {@code test} changed to match that of the target).
3853      */
3854     public static
3855     MethodHandle guardWithTest(MethodHandle test,
3856                                MethodHandle target,
3857                                MethodHandle fallback) {
3858         MethodType gtype = test.type();
3859         MethodType ttype = target.type();
3860         MethodType ftype = fallback.type();
3861         if (!ttype.equals(ftype))
3862             throw misMatchedTypes("target and fallback types", ttype, ftype);
3863         if (gtype.returnType() != boolean.class)
3864             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
3865         List<Class<?>> targs = ttype.parameterList();
3866         test = dropArgumentsToMatch(test, 0, targs, 0, true);
3867         if (test == null) {
3868             throw misMatchedTypes("target and test types", ttype, gtype);
3869         }
3870         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
3871     }
3872 
3873     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
3874         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
3875     }
3876 
3877     /**
3878      * Makes a method handle which adapts a target method handle,
3879      * by running it inside an exception handler.
3880      * If the target returns normally, the adapter returns that value.
3881      * If an exception matching the specified type is thrown, the fallback
3882      * handle is called instead on the exception, plus the original arguments.
3883      * <p>
3884      * The target and handler must have the same corresponding
3885      * argument and return types, except that handler may omit trailing arguments
3886      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
3887      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
3888      * <p>
3889      * Here is pseudocode for the resulting adapter. In the code, {@code T}
3890      * represents the return type of the {@code target} and {@code handler},
3891      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
3892      * the types and values of arguments to the resulting handle consumed by
3893      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
3894      * resulting handle discarded by {@code handler}.
3895      * <blockquote><pre>{@code
3896      * T target(A..., B...);
3897      * T handler(ExType, A...);
3898      * T adapter(A... a, B... b) {
3899      *   try {
3900      *     return target(a..., b...);
3901      *   } catch (ExType ex) {
3902      *     return handler(ex, a...);
3903      *   }
3904      * }
3905      * }</pre></blockquote>
3906      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
3907      * be modified by execution of the target, and so are passed unchanged
3908      * from the caller to the handler, if the handler is invoked.
3909      * <p>
3910      * The target and handler must return the same type, even if the handler
3911      * always throws.  (This might happen, for instance, because the handler
3912      * is simulating a {@code finally} clause).
3913      * To create such a throwing handler, compose the handler creation logic
3914      * with {@link #throwException throwException},
3915      * in order to create a method handle of the correct return type.
3916      * @param target method handle to call
3917      * @param exType the type of exception which the handler will catch
3918      * @param handler method handle to call if a matching exception is thrown
3919      * @return method handle which incorporates the specified try/catch logic
3920      * @throws NullPointerException if any argument is null
3921      * @throws IllegalArgumentException if {@code handler} does not accept
3922      *          the given exception type, or if the method handle types do
3923      *          not match in their return types and their
3924      *          corresponding parameters
3925      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
3926      */
3927     public static
3928     MethodHandle catchException(MethodHandle target,
3929                                 Class<? extends Throwable> exType,
3930                                 MethodHandle handler) {
3931         MethodType ttype = target.type();
3932         MethodType htype = handler.type();
3933         if (!Throwable.class.isAssignableFrom(exType))
3934             throw new ClassCastException(exType.getName());
3935         if (htype.parameterCount() < 1 ||
3936             !htype.parameterType(0).isAssignableFrom(exType))
3937             throw newIllegalArgumentException("handler does not accept exception type "+exType);
3938         if (htype.returnType() != ttype.returnType())
3939             throw misMatchedTypes("target and handler return types", ttype, htype);
3940         handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
3941         if (handler == null) {
3942             throw misMatchedTypes("target and handler types", ttype, htype);
3943         }
3944         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
3945     }
3946 
3947     /**
3948      * Produces a method handle which will throw exceptions of the given {@code exType}.
3949      * The method handle will accept a single argument of {@code exType},
3950      * and immediately throw it as an exception.
3951      * The method type will nominally specify a return of {@code returnType}.
3952      * The return type may be anything convenient:  It doesn't matter to the
3953      * method handle's behavior, since it will never return normally.
3954      * @param returnType the return type of the desired method handle
3955      * @param exType the parameter type of the desired method handle
3956      * @return method handle which can throw the given exceptions
3957      * @throws NullPointerException if either argument is null
3958      */
3959     public static
3960     MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
3961         if (!Throwable.class.isAssignableFrom(exType))
3962             throw new ClassCastException(exType.getName());
3963         return MethodHandleImpl.throwException(methodType(returnType, exType));
3964     }
3965 
3966     /**
3967      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
3968      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
3969      * delivers the loop's result, which is the return value of the resulting handle.
3970      * <p>
3971      * Intuitively, every loop is formed by one or more "clauses", each specifying a local iteration value and/or a loop
3972      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
3973      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
3974      * terms of method handles, each clause will determine four actions:<ul>
3975      * <li>Before the loop executes, the initialization of an iteration variable or loop invariant local.
3976      * <li>When a clause executes, an update step for the iteration variable.
3977      * <li>When a clause executes, a predicate execution to test for loop exit.
3978      * <li>If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
3979      * </ul>
3980      * <p>
3981      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
3982      * this case. See below for a detailed description.
3983      * <p>
3984      * Each clause function, with the exception of clause initializers, is able to observe the entire loop state,
3985      * because it will be passed <em>all</em> current iteration variable values, as well as all incoming loop
3986      * parameters. Most clause functions will not need all of this information, but they will be formally connected as
3987      * if by {@link #dropArguments}.
3988      * <p>
3989      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
3990      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
3991      * corresponds to a place where {@link IllegalArgumentException} may be thrown if the required constraint is not met
3992      * by the inputs to the loop combinator. The term "effectively identical", applied to parameter type lists, means
3993      * that they must be identical, or else one list must be a proper prefix of the other.
3994      * <p>
3995      * <em>Step 0: Determine clause structure.</em><ol type="a">
3996      * <li>The clause array (of type {@code MethodHandle[][]} must be non-{@code null} and contain at least one element.
3997      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
3998      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
3999      * four. Padding takes place by appending elements to the array.
4000      * <li>Clauses with all {@code null}s are disregarded.
4001      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
4002      * </ol>
4003      * <p>
4004      * <em>Step 1A: Determine iteration variables.</em><ol type="a">
4005      * <li>Examine init and step function return types, pairwise, to determine each clause's iteration variable type.
4006      * <li>If both functions are omitted, use {@code void}; else if one is omitted, use the other's return type; else
4007      * use the common return type (they must be identical).
4008      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
4009      * <li>This list of types is called the "common prefix".
4010      * </ol>
4011      * <p>
4012      * <em>Step 1B: Determine loop parameters.</em><ul>
4013      * <li><b>If at least one init function is given,</b><ol type="a">
4014      *   <li>Examine init function parameter lists.
4015      *   <li>Omitted init functions are deemed to have {@code null} parameter lists.
4016      *   <li>All init function parameter lists must be effectively identical.
4017      *   <li>The longest parameter list (which is necessarily unique) is called the "common suffix".
4018      * </ol>
4019      * <li><b>If no init function is given,</b><ol type="a">
4020      *   <li>Examine the suffixes of the step, pred, and fini parameter lists, after removing the "common prefix".
4021      *   <li>The longest of these suffixes is taken as the "common suffix".
4022      * </ol></ul>
4023      * <p>
4024      * <em>Step 1C: Determine loop return type.</em><ol type="a">
4025      * <li>Examine fini function return types, disregarding omitted fini functions.
4026      * <li>If there are no fini functions, use {@code void} as the loop return type.
4027      * <li>Otherwise, use the common return type of the fini functions; they must all be identical.
4028      * </ol>
4029      * <p>
4030      * <em>Step 1D: Check other types.</em><ol type="a">
4031      * <li>There must be at least one non-omitted pred function.
4032      * <li>Every non-omitted pred function must have a {@code boolean} return type.
4033      * </ol>
4034      * <p>
4035      * <em>Step 2: Determine parameter lists.</em><ol type="a">
4036      * <li>The parameter list for the resulting loop handle will be the "common suffix".
4037      * <li>The parameter list for init functions will be adjusted to the "common suffix". (Note that their parameter
4038      * lists are already effectively identical to the common suffix.)
4039      * <li>The parameter list for non-init (step, pred, and fini) functions will be adjusted to the common prefix
4040      * followed by the common suffix, called the "common parameter sequence".
4041      * <li>Every non-init, non-omitted function parameter list must be effectively identical to the common parameter
4042      * sequence.
4043      * </ol>
4044      * <p>
4045      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
4046      * <li>If an init function is omitted, use a {@linkplain #constant constant function} of the appropriate
4047      * {@code null}/zero/{@code false}/{@code void} type. (For this purpose, a constant {@code void} is simply a
4048      * function which does nothing and returns {@code void}; it can be obtained from another constant function by
4049      * {@linkplain MethodHandle#asType type conversion}.)
4050      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
4051      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
4052      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
4053      * <li>If a pred function is omitted, the corresponding fini function must also be omitted.
4054      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
4055      * as this clause is concerned.)
4056      * <li>If a fini function is omitted, use a constant {@code null}/zero/{@code false}/{@code void} function of the
4057      * loop return type.
4058      * </ol>
4059      * <p>
4060      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
4061      * <li>At this point, every init function parameter list is effectively identical to the common suffix, but some
4062      * lists may be shorter. For every init function with a short parameter list, pad out the end of the list by
4063      * {@linkplain #dropArguments dropping arguments}.
4064      * <li>At this point, every non-init function parameter list is effectively identical to the common parameter
4065      * sequence, but some lists may be shorter. For every non-init function with a short parameter list, pad out the end
4066      * of the list by {@linkplain #dropArguments dropping arguments}.
4067      * </ol>
4068      * <p>
4069      * <em>Final observations.</em><ol type="a">
4070      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
4071      * <li>All init functions have a common parameter type list, which the final loop handle will also have.
4072      * <li>All fini functions have a common return type, which the final loop handle will also have.
4073      * <li>All non-init functions have a common parameter type list, which is the common parameter sequence, of
4074      * (non-{@code void}) iteration variables followed by loop parameters.
4075      * <li>Each pair of init and step functions agrees in their return types.
4076      * <li>Each non-init function will be able to observe the current values of all iteration variables, by means of the
4077      * common prefix.
4078      * </ol>
4079      * <p>
4080      * <em>Loop execution.</em><ol type="a">
4081      * <li>When the loop is called, the loop input values are saved in locals, to be passed (as the common suffix) to
4082      * every clause function. These locals are loop invariant.
4083      * <li>Each init function is executed in clause order (passing the common suffix) and the non-{@code void} values
4084      * are saved (as the common prefix) into locals. These locals are loop varying (unless their steps are identity
4085      * functions, as noted above).
4086      * <li>All function executions (except init functions) will be passed the common parameter sequence, consisting of
4087      * the non-{@code void} iteration values (in clause order) and then the loop inputs (in argument order).
4088      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
4089      * returns {@code false}.
4090      * <li>The non-{@code void} result from a step function call is used to update the corresponding loop variable. The
4091      * updated value is immediately visible to all subsequent function calls.
4092      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
4093      * is returned from the loop as a whole.
4094      * </ol>
4095      * <p>
4096      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the types / values
4097      * of loop variables; {@code A}/{@code a}, those of arguments passed to the resulting loop; and {@code R}, the
4098      * result types of finalizers as well as of the resulting loop.
4099      * <blockquote><pre>{@code
4100      * V... init...(A...);
4101      * boolean pred...(V..., A...);
4102      * V... step...(V..., A...);
4103      * R fini...(V..., A...);
4104      * R loop(A... a) {
4105      *   V... v... = init...(a...);
4106      *   for (;;) {
4107      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
4108      *       v = s(v..., a...);
4109      *       if (!p(v..., a...)) {
4110      *         return f(v..., a...);
4111      *       }
4112      *     }
4113      *   }
4114      * }
4115      * }</pre></blockquote>
4116      * <p>
4117      * @apiNote Example:
4118      * <blockquote><pre>{@code
4119      * // iterative implementation of the factorial function as a loop handle
4120      * static int one(int k) { return 1; }
4121      * static int inc(int i, int acc, int k) { return i + 1; }
4122      * static int mult(int i, int acc, int k) { return i * acc; }
4123      * static boolean pred(int i, int acc, int k) { return i < k; }
4124      * static int fin(int i, int acc, int k) { return acc; }
4125      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
4126      * // null initializer for counter, should initialize to 0
4127      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
4128      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
4129      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
4130      * assertEquals(120, loop.invoke(5));
4131      * }</pre></blockquote>
4132      *
4133      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
4134      *
4135      * @return a method handle embodying the looping behavior as defined by the arguments.
4136      *
4137      * @throws IllegalArgumentException in case any of the constraints described above is violated.
4138      *
4139      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
4140      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
4141      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
4142      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
4143      * @since 9
4144      */
4145     public static MethodHandle loop(MethodHandle[]... clauses) {
4146         // Step 0: determine clause structure.
4147         checkLoop0(clauses);
4148 
4149         List<MethodHandle> init = new ArrayList<>();
4150         List<MethodHandle> step = new ArrayList<>();
4151         List<MethodHandle> pred = new ArrayList<>();
4152         List<MethodHandle> fini = new ArrayList<>();
4153 
4154         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
4155             init.add(clause[0]); // all clauses have at least length 1
4156             step.add(clause.length <= 1 ? null : clause[1]);
4157             pred.add(clause.length <= 2 ? null : clause[2]);
4158             fini.add(clause.length <= 3 ? null : clause[3]);
4159         });
4160 
4161         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
4162         final int nclauses = init.size();
4163 
4164         // Step 1A: determine iteration variables.
4165         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
4166         for (int i = 0; i < nclauses; ++i) {
4167             MethodHandle in = init.get(i);
4168             MethodHandle st = step.get(i);
4169             if (in == null && st == null) {
4170                 iterationVariableTypes.add(void.class);
4171             } else if (in != null && st != null) {
4172                 checkLoop1a(i, in, st);
4173                 iterationVariableTypes.add(in.type().returnType());
4174             } else {
4175                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
4176             }
4177         }
4178         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).
4179                 collect(Collectors.toList());
4180 
4181         // Step 1B: determine loop parameters.
4182         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
4183         checkLoop1b(init, commonSuffix);
4184 
4185         // Step 1C: determine loop return type.
4186         // Step 1D: check other types.
4187         final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type).
4188                 map(MethodType::returnType).findFirst().orElse(void.class);
4189         checkLoop1cd(pred, fini, loopReturnType);
4190 
4191         // Step 2: determine parameter lists.
4192         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
4193         commonParameterSequence.addAll(commonSuffix);
4194         checkLoop2(step, pred, fini, commonParameterSequence);
4195 
4196         // Step 3: fill in omitted functions.
4197         for (int i = 0; i < nclauses; ++i) {
4198             Class<?> t = iterationVariableTypes.get(i);
4199             if (init.get(i) == null) {
4200                 init.set(i, empty(methodType(t, commonSuffix)));
4201             }
4202             if (step.get(i) == null) {
4203                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
4204             }
4205             if (pred.get(i) == null) {
4206                 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
4207             }
4208             if (fini.get(i) == null) {
4209                 fini.set(i, empty(methodType(t, commonParameterSequence)));
4210             }
4211         }
4212 
4213         // Step 4: fill in missing parameter types.
4214         List<MethodHandle> finit = fillParameterTypes(init, commonSuffix);
4215         List<MethodHandle> fstep = fillParameterTypes(step, commonParameterSequence);
4216         List<MethodHandle> fpred = fillParameterTypes(pred, commonParameterSequence);
4217         List<MethodHandle> ffini = fillParameterTypes(fini, commonParameterSequence);
4218 
4219         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
4220                 allMatch(pl -> pl.equals(commonSuffix));
4221         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
4222                 allMatch(pl -> pl.equals(commonParameterSequence));
4223 
4224         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, commonPrefix, finit, fstep, fpred, ffini);
4225     }
4226 
4227     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
4228         return hs.stream().map(h -> {
4229             int pc = h.type().parameterCount();
4230             int tpsize = targetParams.size();
4231             return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
4232         }).collect(Collectors.toList());
4233     }
4234 
4235     /**
4236      * Constructs a {@code while} loop from an initializer, a body, and a predicate. This is a convenience wrapper for
4237      * the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
4238      * <p>
4239      * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}.
4240      * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle
4241      * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code
4242      * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][])
4243      * generic loop combinator}.
4244      * <p>
4245      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4246      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4247      * passed to the loop.
4248      * <blockquote><pre>{@code
4249      * V init(A);
4250      * boolean pred(V, A);
4251      * V body(V, A);
4252      * V whileLoop(A a) {
4253      *   V v = init(a);
4254      *   while (pred(v, a)) {
4255      *     v = body(v, a);
4256      *   }
4257      *   return v;
4258      * }
4259      * }</pre></blockquote>
4260      * <p>
4261      * @apiNote Example:
4262      * <blockquote><pre>{@code
4263      * // implement the zip function for lists as a loop handle
4264      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
4265      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
4266      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
4267      *   zip.add(a.next());
4268      *   zip.add(b.next());
4269      *   return zip;
4270      * }
4271      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
4272      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
4273      * List<String> a = Arrays.asList("a", "b", "c", "d");
4274      * List<String> b = Arrays.asList("e", "f", "g", "h");
4275      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
4276      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
4277      * }</pre></blockquote>
4278      *
4279      * <p>
4280      * @implSpec The implementation of this method is equivalent to:
4281      * <blockquote><pre>{@code
4282      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
4283      *     MethodHandle[]
4284      *         checkExit = {null, null, pred, identity(init.type().returnType())},
4285      *         varBody = {init, body};
4286      *     return loop(checkExit, varBody);
4287      * }
4288      * }</pre></blockquote>
4289      *
4290      * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's
4291      *             result type. Passing {@code null} or a {@code void} init function will make the loop's result type
4292      *             {@code void}.
4293      * @param pred condition for the loop, which may not be {@code null}.
4294      * @param body body of the loop, which may not be {@code null}.
4295      *
4296      * @return the value of the loop variable as the loop terminates.
4297      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4298      *
4299      * @see MethodHandles#loop(MethodHandle[][])
4300      * @since 9
4301      */
4302     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
4303         MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) :
4304                 identity(init.type().returnType());
4305         MethodHandle[] checkExit = {null, null, pred, fin};
4306         MethodHandle[] varBody = {init, body};
4307         return loop(checkExit, varBody);
4308     }
4309 
4310     /**
4311      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. This is a convenience wrapper
4312      * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
4313      * <p>
4314      * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}.
4315      * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle
4316      * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code
4317      * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][])
4318      * generic loop combinator}.
4319      * <p>
4320      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4321      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4322      * passed to the loop.
4323      * <blockquote><pre>{@code
4324      * V init(A);
4325      * boolean pred(V, A);
4326      * V body(V, A);
4327      * V doWhileLoop(A a) {
4328      *   V v = init(a);
4329      *   do {
4330      *     v = body(v, a);
4331      *   } while (pred(v, a));
4332      *   return v;
4333      * }
4334      * }</pre></blockquote>
4335      * <p>
4336      * @apiNote Example:
4337      * <blockquote><pre>{@code
4338      * // int i = 0; while (i < limit) { ++i; } return i; => limit
4339      * static int zero(int limit) { return 0; }
4340      * static int step(int i, int limit) { return i + 1; }
4341      * static boolean pred(int i, int limit) { return i < limit; }
4342      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
4343      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
4344      * assertEquals(23, loop.invoke(23));
4345      * }</pre></blockquote>
4346      *
4347      * <p>
4348      * @implSpec The implementation of this method is equivalent to:
4349      * <blockquote><pre>{@code
4350      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
4351      *     MethodHandle[] clause = { init, body, pred, identity(init.type().returnType()) };
4352      *     return loop(clause);
4353      * }
4354      * }</pre></blockquote>
4355      *
4356      *
4357      * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's
4358      *             result type. Passing {@code null} or a {@code void} init function will make the loop's result type
4359      *             {@code void}.
4360      * @param pred condition for the loop, which may not be {@code null}.
4361      * @param body body of the loop, which may not be {@code null}.
4362      *
4363      * @return the value of the loop variable as the loop terminates.
4364      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4365      *
4366      * @see MethodHandles#loop(MethodHandle[][])
4367      * @since 9
4368      */
4369     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
4370         MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) :
4371                 identity(init.type().returnType());
4372         MethodHandle[] clause = {init, body, pred, fin};
4373         return loop(clause);
4374     }
4375 
4376     /**
4377      * Constructs a loop that runs a given number of iterations. The loop counter is an {@code int} initialized from the
4378      * {@code iterations} handle evaluation result. The counter is passed to the {@code body} function, so that must
4379      * accept an initial {@code int} argument. The result of the loop execution is the final value of the additional
4380      * local state. This is a convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop
4381      * combinator}.
4382      * <p>
4383      * The result type and parameter type list of {@code init} determine those of the resulting handle. The {@code
4384      * iterations} handle must accept the same parameter types as {@code init} but return an {@code int}. The {@code
4385      * body} handle must accept the same parameter types as well, preceded by an {@code int} parameter for the counter,
4386      * and a parameter of the same type as {@code init}'s result. These constraints follow directly from those described
4387      * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
4388      * <p>
4389      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4390      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4391      * passed to the loop.
4392      * <blockquote><pre>{@code
4393      * int iterations(A);
4394      * V init(A);
4395      * V body(int, V, A);
4396      * V countedLoop(A a) {
4397      *   int end = iterations(a);
4398      *   V v = init(a);
4399      *   for (int i = 0; i < end; ++i) {
4400      *     v = body(i, v, a);
4401      *   }
4402      *   return v;
4403      * }
4404      * }</pre></blockquote>
4405      * <p>
4406      * @apiNote Example:
4407      * <blockquote><pre>{@code
4408      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
4409      * // => a variation on a well known theme
4410      * static String start(String arg) { return arg; }
4411      * static String step(int counter, String v, String arg) { return "na " + v; }
4412      * // assume MH_start and MH_step are handles to the two methods above
4413      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
4414      * MethodHandle loop = MethodHandles.countedLoop(fit13, MH_start, MH_step);
4415      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
4416      * }</pre></blockquote>
4417      *
4418      * <p>
4419      * @implSpec The implementation of this method is equivalent to:
4420      * <blockquote><pre>{@code
4421      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
4422      *     return countedLoop(null, iterations, init, body);  // null => constant zero
4423      * }
4424      * }</pre></blockquote>
4425      *
4426      * @param iterations a handle to return the number of iterations this loop should run.
4427      * @param init initializer for additional loop state. This determines the loop's result type.
4428      *             Passing {@code null} or a {@code void} init function will make the loop's result type
4429      *             {@code void}.
4430      * @param body the body of the loop, which must not be {@code null}.
4431      *             It must accept an initial {@code int} parameter (for the counter), and then any
4432      *             additional loop-local variable plus loop parameters.
4433      *
4434      * @return a method handle representing the loop.
4435      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4436      *
4437      * @since 9
4438      */
4439     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
4440         return countedLoop(null, iterations, init, body);
4441     }
4442 
4443     /**
4444      * Constructs a loop that counts over a range of numbers. The loop counter is an {@code int} that will be
4445      * initialized to the {@code int} value returned from the evaluation of the {@code start} handle and run to the
4446      * value returned from {@code end} (exclusively) with a step width of 1. The counter value is passed to the {@code
4447      * body} function in each iteration; it has to accept an initial {@code int} parameter
4448      * for that. The result of the loop execution is the final value of the additional local state
4449      * obtained by running {@code init}.
4450      * This is a
4451      * convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
4452      * <p>
4453      * The constraints for the {@code init} and {@code body} handles are the same as for {@link
4454      * #countedLoop(MethodHandle, MethodHandle, MethodHandle)}. Additionally, the {@code start} and {@code end} handles
4455      * must return an {@code int} and accept the same parameters as {@code init}.
4456      * <p>
4457      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4458      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4459      * passed to the loop.
4460      * <blockquote><pre>{@code
4461      * int start(A);
4462      * int end(A);
4463      * V init(A);
4464      * V body(int, V, A);
4465      * V countedLoop(A a) {
4466      *   int s = start(a);
4467      *   int e = end(a);
4468      *   V v = init(a);
4469      *   for (int i = s; i < e; ++i) {
4470      *     v = body(i, v, a);
4471      *   }
4472      *   return v;
4473      * }
4474      * }</pre></blockquote>
4475      *
4476      * <p>
4477      * @implSpec The implementation of this method is equivalent to:
4478      * <blockquote><pre>{@code
4479      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
4480      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
4481      *     // assume MH_increment and MH_lessThan are handles to x+1 and x<y of type int,
4482      *     // assume MH_decrement is a handle to x-1 of type int
4483      *     MethodHandle[]
4484      *         indexVar = {start, MH_increment}, // i = start; i = i+1
4485      *         loopLimit = {end, null, MH_lessThan, returnVar }, // i<end
4486      *         bodyClause = {init,
4487      *                       filterArgument(dropArguments(body, 1, int.class), 0, MH_decrement}; // v = body(i-1, v)
4488      *     return loop(indexVar, loopLimit, bodyClause);
4489      * }
4490      * }</pre></blockquote>
4491      *
4492      * @param start a handle to return the start value of the loop counter.
4493      *              If it is {@code null}, a constant zero is assumed.
4494      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to {@code end-1}).
4495      * @param init initializer for additional loop state. This determines the loop's result type.
4496      *             Passing {@code null} or a {@code void} init function will make the loop's result type
4497      *             {@code void}.
4498      * @param body the body of the loop, which must not be {@code null}.
4499      *             It must accept an initial {@code int} parameter (for the counter), and then any
4500      *             additional loop-local variable plus loop parameters.
4501      *
4502      * @return a method handle representing the loop.
4503      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4504      *
4505      * @since 9
4506      */
4507     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
4508         Class<?> resultType;
4509         MethodHandle actualInit;
4510         if (init == null) {
4511             resultType = body == null ? void.class : body.type().returnType();
4512             actualInit = empty(methodType(resultType));
4513         } else {
4514             resultType = init.type().returnType();
4515             actualInit = init;
4516         }
4517         MethodHandle defaultResultHandle = resultType == void.class ? zero(void.class) : identity(resultType);
4518         MethodHandle actualBody = body == null ? dropArguments(defaultResultHandle, 0, int.class) : body;
4519         MethodHandle returnVar = dropArguments(defaultResultHandle, 0, int.class, int.class);
4520         MethodHandle actualEnd = end == null ? constant(int.class, 0) : end;
4521         MethodHandle[] indexVar = {start, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep)};
4522         MethodHandle[] loopLimit = {actualEnd, null,
4523                 MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred), returnVar};
4524         MethodHandle[] bodyClause = {actualInit,
4525                 filterArgument(dropArguments(actualBody, 1, int.class), 0,
4526                         MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_decrementCounter))};
4527         return loop(indexVar, loopLimit, bodyClause);
4528     }
4529 
4530     /**
4531      * Constructs a loop that ranges over the elements produced by an {@code Iterator<T>}.
4532      * The iterator will be produced by the evaluation of the {@code iterator} handle.
4533      * This handle must have {@link java.util.Iterator} as its return type.
4534      * If this handle is passed as {@code null} the method {@link Iterable#iterator} will be used instead,
4535      * and will be applied to a leading argument of the loop handle.
4536      * Each value produced by the iterator is passed to the {@code body}, which must accept an initial {@code T} parameter.
4537      * The result of the loop execution is the final value of the additional local state
4538      * obtained by running {@code init}.
4539      * <p>
4540      * This is a convenience wrapper for the
4541      * {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}, and the constraints imposed on the {@code body}
4542      * handle follow directly from those described for the latter.
4543      * <p>
4544      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4545      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
4546      * structure the loop iterates over, and {@code A}/{@code a}, that of the argument passed to the loop.
4547      * <blockquote><pre>{@code
4548      * Iterator<T> iterator(A);  // defaults to Iterable::iterator
4549      * V init(A);
4550      * V body(T,V,A);
4551      * V iteratedLoop(A a) {
4552      *   Iterator<T> it = iterator(a);
4553      *   V v = init(a);
4554      *   for (T t : it) {
4555      *     v = body(t, v, a);
4556      *   }
4557      *   return v;
4558      * }
4559      * }</pre></blockquote>
4560      * <p>
4561      * The type {@code T} may be either a primitive or reference.
4562      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type
4563      * {@code Iterator}, the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body}
4564      * to {@code Object} as if by the {@link MethodHandle#asType asType} conversion method.
4565      * Therefore, if an iterator of the wrong type appears as the loop is executed,
4566      * runtime exceptions may occur as the result of dynamic conversions performed by {@code asType}.
4567      * <p>
4568      * @apiNote Example:
4569      * <blockquote><pre>{@code
4570      * // reverse a list
4571      * static List<String> reverseStep(String e, List<String> r, List<String> l) {
4572      *   r.add(0, e);
4573      *   return r;
4574      * }
4575      * static List<String> newArrayList(List<String> l) { return new ArrayList<>(); }
4576      * // assume MH_reverseStep, MH_newArrayList are handles to the above methods
4577      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
4578      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
4579      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
4580      * assertEquals(reversedList, (List<String>) loop.invoke(list));
4581      * }</pre></blockquote>
4582      * <p>
4583      * @implSpec The implementation of this method is equivalent to (excluding error handling):
4584      * <blockquote><pre>{@code
4585      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
4586      *     // assume MH_next and MH_hasNext are handles to methods of Iterator
4587      *     Class<?> itype = iterator.type().returnType();
4588      *     Class<?> ttype = body.type().parameterType(0);
4589      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, itype);
4590      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
4591      *     MethodHandle[]
4592      *         iterVar = {iterator, null, MH_hasNext, returnVar}, // it = iterator(); while (it.hasNext)
4593      *         bodyClause = {init, filterArgument(body, 0, nextVal)};  // v = body(t, v, a);
4594      *     return loop(iterVar, bodyClause);
4595      * }
4596      * }</pre></blockquote>
4597      *
4598      * @param iterator a handle to return the iterator to start the loop.
4599      *             The handle must have {@link java.util.Iterator} as its return type.
4600      *             Passing {@code null} will make the loop call {@link Iterable#iterator()} on the first
4601      *             incoming value.
4602      * @param init initializer for additional loop state. This determines the loop's result type.
4603      *             Passing {@code null} or a {@code void} init function will make the loop's result type
4604      *             {@code void}.
4605      * @param body the body of the loop, which must not be {@code null}.
4606      *             It must accept an initial {@code T} parameter (for the iterated values), and then any
4607      *             additional loop-local variable plus loop parameters.
4608      *
4609      * @return a method handle embodying the iteration loop functionality.
4610      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4611      *
4612      * @since 9
4613      */
4614     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
4615         checkIteratedLoop(iterator, body);
4616         Class<?> resultType = init == null ?
4617                 body == null ? void.class : body.type().returnType() :
4618                 init.type().returnType();
4619         boolean voidResult = resultType == void.class;
4620 
4621         MethodHandle initIterator;
4622         if (iterator == null) {
4623             MethodHandle initit = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
4624             initIterator = initit.asType(initit.type().changeParameterType(0,
4625                     body.type().parameterType(voidResult ? 1 : 2)));
4626         } else {
4627             initIterator = iterator.asType(iterator.type().changeReturnType(Iterator.class));
4628         }
4629 
4630         Class<?> ttype = body.type().parameterType(0);
4631 
4632         MethodHandle returnVar =
4633                 dropArguments(voidResult ? zero(void.class) : identity(resultType), 0, Iterator.class);
4634         MethodHandle initnx = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
4635         MethodHandle nextVal = initnx.asType(initnx.type().changeReturnType(ttype));
4636 
4637         MethodHandle[] iterVar = {initIterator, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred),
4638                 returnVar};
4639         MethodHandle[] bodyClause = {init, filterArgument(body, 0, nextVal)};
4640 
4641         return loop(iterVar, bodyClause);
4642     }
4643 
4644     /**
4645      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
4646      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
4647      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
4648      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
4649      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
4650      * {@code try-finally} handle.
4651      * <p>
4652      * The {@code cleanup} handle will be passed one or two additional leading arguments.
4653      * The first is the exception thrown during the
4654      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
4655      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
4656      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
4657      * The second argument is not present if the {@code target} handle has a {@code void} return type.
4658      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
4659      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
4660      * <p>
4661      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
4662      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
4663      * two extra leading parameters:<ul>
4664      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
4665      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
4666      * the result from the execution of the {@code target} handle.
4667      * This parameter is not present if the {@code target} returns {@code void}.
4668      * </ul>
4669      * <p>
4670      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
4671      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
4672      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
4673      * the cleanup.
4674      * <blockquote><pre>{@code
4675      * V target(A..., B...);
4676      * V cleanup(Throwable, V, A...);
4677      * V adapter(A... a, B... b) {
4678      *   V result = (zero value for V);
4679      *   Throwable throwable = null;
4680      *   try {
4681      *     result = target(a..., b...);
4682      *   } catch (Throwable t) {
4683      *     throwable = t;
4684      *     throw t;
4685      *   } finally {
4686      *     result = cleanup(throwable, result, a...);
4687      *   }
4688      *   return result;
4689      * }
4690      * }</pre></blockquote>
4691      * <p>
4692      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
4693      * be modified by execution of the target, and so are passed unchanged
4694      * from the caller to the cleanup, if it is invoked.
4695      * <p>
4696      * The target and cleanup must return the same type, even if the cleanup
4697      * always throws.
4698      * To create such a throwing cleanup, compose the cleanup logic
4699      * with {@link #throwException throwException},
4700      * in order to create a method handle of the correct return type.
4701      * <p>
4702      * Note that {@code tryFinally} never converts exceptions into normal returns.
4703      * In rare cases where exceptions must be converted in that way, first wrap
4704      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
4705      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
4706      *
4707      * @param target the handle whose execution is to be wrapped in a {@code try} block.
4708      * @param cleanup the handle that is invoked in the finally block.
4709      *
4710      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
4711      * @throws NullPointerException if any argument is null
4712      * @throws IllegalArgumentException if {@code cleanup} does not accept
4713      *          the required leading arguments, or if the method handle types do
4714      *          not match in their return types and their
4715      *          corresponding trailing parameters
4716      *
4717      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
4718      * @since 9
4719      */
4720     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
4721         List<Class<?>> targetParamTypes = target.type().parameterList();
4722         List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
4723         Class<?> rtype = target.type().returnType();
4724 
4725         checkTryFinally(target, cleanup);
4726 
4727         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
4728         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
4729         // target parameter list.
4730         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
4731         MethodHandle aTarget = target.asSpreader(Object[].class, target.type().parameterCount());
4732         MethodHandle aCleanup = cleanup.asSpreader(Object[].class, targetParamTypes.size());
4733 
4734         return MethodHandleImpl.makeTryFinally(aTarget, aCleanup, rtype, targetParamTypes);
4735     }
4736 
4737     /**
4738      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
4739      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
4740      * before the folded arguments.
4741      * <p>
4742      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
4743      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
4744      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
4745      * 0.
4746      * <p>
4747      * @apiNote Example:
4748      * <blockquote><pre>{@code
4749     import static java.lang.invoke.MethodHandles.*;
4750     import static java.lang.invoke.MethodType.*;
4751     ...
4752     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
4753     "println", methodType(void.class, String.class))
4754     .bindTo(System.out);
4755     MethodHandle cat = lookup().findVirtual(String.class,
4756     "concat", methodType(String.class, String.class));
4757     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
4758     MethodHandle catTrace = foldArguments(cat, 1, trace);
4759     // also prints "jum":
4760     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
4761      * }</pre></blockquote>
4762      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
4763      * represents the result type of the {@code target} and resulting adapter.
4764      * {@code V}/{@code v} represent the type and value of the parameter and argument
4765      * of {@code target} that precedes the folding position; {@code V} also is
4766      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
4767      * types and values of the {@code N} parameters and arguments at the folding
4768      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
4769      * and values of the {@code target} parameters and arguments that precede and
4770      * follow the folded parameters and arguments starting at {@code pos},
4771      * respectively.
4772      * <blockquote><pre>{@code
4773      * // there are N arguments in A...
4774      * T target(Z..., V, A[N]..., B...);
4775      * V combiner(A...);
4776      * T adapter(Z... z, A... a, B... b) {
4777      *   V v = combiner(a...);
4778      *   return target(z..., v, a..., b...);
4779      * }
4780      * // and if the combiner has a void return:
4781      * T target2(Z..., A[N]..., B...);
4782      * void combiner2(A...);
4783      * T adapter2(Z... z, A... a, B... b) {
4784      *   combiner2(a...);
4785      *   return target2(z..., a..., b...);
4786      * }
4787      * }</pre></blockquote>
4788      * <p>
4789      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4790      * variable-arity method handle}, even if the original target method handle was.
4791      *
4792      * @param target the method handle to invoke after arguments are combined
4793      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
4794      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
4795      * @param combiner method handle to call initially on the incoming arguments
4796      * @return method handle which incorporates the specified argument folding logic
4797      * @throws NullPointerException if either argument is null
4798      * @throws IllegalArgumentException if {@code combiner}'s return type
4799      *          is non-void and not the same as the argument type at position {@code pos} of
4800      *          the target signature, or if the {@code N} argument types at position {@code pos}
4801      *          of the target signature
4802      *          (skipping one matching the {@code combiner}'s return type)
4803      *          are not identical with the argument types of {@code combiner}
4804      *
4805      * @see #foldArguments(MethodHandle, MethodHandle)
4806      * @since 9
4807      */
4808     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
4809         MethodType targetType = target.type();
4810         MethodType combinerType = combiner.type();
4811         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
4812         BoundMethodHandle result = target.rebind();
4813         boolean dropResult = rtype == void.class;
4814         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
4815         MethodType newType = targetType;
4816         if (!dropResult) {
4817             newType = newType.dropParameterTypes(pos, pos + 1);
4818         }
4819         result = result.copyWithExtendL(newType, lform, combiner);
4820         return result;
4821     }
4822 
4823 
4824     private static void checkLoop0(MethodHandle[][] clauses) {
4825         if (clauses == null || clauses.length == 0) {
4826             throw newIllegalArgumentException("null or no clauses passed");
4827         }
4828         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
4829             throw newIllegalArgumentException("null clauses are not allowed");
4830         }
4831         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
4832             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
4833         }
4834     }
4835 
4836     private static void checkLoop1a(int i, MethodHandle in, MethodHandle st) {
4837         if (in.type().returnType() != st.type().returnType()) {
4838             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
4839                     st.type().returnType());
4840         }
4841     }
4842 
4843     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
4844         final List<Class<?>> empty = List.of();
4845         final List<MethodHandle> nonNullInits = init.stream().filter(Objects::nonNull).collect(Collectors.toList());
4846         if (nonNullInits.isEmpty()) {
4847             final List<Class<?>> longest = Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).
4848                     // take only those that can contribute to a common suffix because they are longer than the prefix
4849                     map(MethodHandle::type).filter(t -> t.parameterCount() > cpSize).map(MethodType::parameterList).
4850                     reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
4851             return longest.size() == 0 ? empty : longest.subList(cpSize, longest.size());
4852         } else {
4853             return nonNullInits.stream().map(MethodHandle::type).map(MethodType::parameterList).
4854                     reduce((p, q) -> p.size() >= q.size() ? p : q).get();
4855         }
4856     }
4857 
4858     private static void checkLoop1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
4859         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::parameterList).
4860                 anyMatch(pl -> !pl.equals(commonSuffix.subList(0, pl.size())))) {
4861             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
4862                     " (common suffix: " + commonSuffix + ")");
4863         }
4864     }
4865 
4866     private static void checkLoop1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
4867         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
4868                 anyMatch(t -> t != loopReturnType)) {
4869             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
4870                     loopReturnType + ")");
4871         }
4872 
4873         if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
4874             throw newIllegalArgumentException("no predicate found", pred);
4875         }
4876         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
4877                 anyMatch(t -> t != boolean.class)) {
4878             throw newIllegalArgumentException("predicates must have boolean return type", pred);
4879         }
4880     }
4881 
4882     private static void checkLoop2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
4883         final int cpSize = commonParameterSequence.size();
4884         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
4885                 map(MethodType::parameterList).
4886                 anyMatch(pl -> pl.size() > cpSize || !pl.equals(commonParameterSequence.subList(0, pl.size())))) {
4887             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
4888                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
4889         }
4890     }
4891 
4892     private static void checkIteratedLoop(MethodHandle iterator, MethodHandle body) {
4893         if (null != iterator && !Iterator.class.isAssignableFrom(iterator.type().returnType())) {
4894             throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
4895         }
4896         if (null == body) {
4897             throw newIllegalArgumentException("iterated loop body must not be null");
4898         }
4899     }
4900 
4901     private static void checkTryFinally(MethodHandle target, MethodHandle cleanup) {
4902         Class<?> rtype = target.type().returnType();
4903         if (rtype != cleanup.type().returnType()) {
4904             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
4905         }
4906         List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
4907         if (!Throwable.class.isAssignableFrom(cleanupParamTypes.get(0))) {
4908             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
4909         }
4910         if (rtype != void.class && cleanupParamTypes.get(1) != rtype) {
4911             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
4912         }
4913         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
4914         // target parameter list.
4915         int cleanupArgIndex = rtype == void.class ? 1 : 2;
4916         List<Class<?>> cleanupArgSuffix = cleanupParamTypes.subList(cleanupArgIndex, cleanupParamTypes.size());
4917         List<Class<?>> targetParamTypes = target.type().parameterList();
4918         if (targetParamTypes.size() < cleanupArgSuffix.size() ||
4919                 !cleanupArgSuffix.equals(targetParamTypes.subList(0, cleanupParamTypes.size() - cleanupArgIndex))) {
4920             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
4921                     cleanup.type(), target.type());
4922         }
4923     }
4924 
4925 }