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 int},
1212          *     {@code long} or a reference type, then atomic update access modes
1213          *     are unsupported.  (Future major platform releases of the JDK may
1214          *     support additional types for certain currently unsupported access
1215          *     modes.)
1216          * <li>if the field type is anything other than {@code int} or
1217          *     {@code long}, then numeric atomic update access modes are
1218          *     unsupported.  (Future major platform releases of the JDK may
1219          *     support additional numeric types for certain currently
1220          *     unsupported access modes.)
1221          * </ul>
1222          * <p>
1223          * If the field is declared {@code volatile} then the returned VarHandle
1224          * will override access to the field (effectively ignore the
1225          * {@code volatile} declaration) in accordance to it's specified
1226          * access modes.
1227          * @param recv the receiver class, of type {@code R}, that declares the
1228          * non-static field
1229          * @param name the field's name
1230          * @param type the field's type, of type {@code T}
1231          * @return a VarHandle giving access to non-static fields.
1232          * @throws NoSuchFieldException if the field does not exist
1233          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1234          * @exception SecurityException if a security manager is present and it
1235          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1236          * @throws NullPointerException if any argument is null
1237          * @since 9
1238          */
1239         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1240             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
1241             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
1242             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
1243         }
1244 
1245         /**
1246          * Produces a method handle giving read access to a static field.
1247          * The type of the method handle will have a return type of the field's
1248          * value type.
1249          * The method handle will take no arguments.
1250          * Access checking is performed immediately on behalf of the lookup class.
1251          * <p>
1252          * If the returned method handle is invoked, the field's class will
1253          * be initialized, if it has not already been initialized.
1254          * @param refc the class or interface from which the method is accessed
1255          * @param name the field's name
1256          * @param type the field's type
1257          * @return a method handle which can load values from the field
1258          * @throws NoSuchFieldException if the field does not exist
1259          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1260          * @exception SecurityException if a security manager is present and it
1261          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1262          * @throws NullPointerException if any argument is null
1263          */
1264         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1265             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
1266             return getDirectField(REF_getStatic, refc, field);
1267         }
1268 
1269         /**
1270          * Produces a method handle giving write access to a static field.
1271          * The type of the method handle will have a void return type.
1272          * The method handle will take a single
1273          * argument, of the field's value type, the value to be stored.
1274          * Access checking is performed immediately on behalf of the lookup class.
1275          * <p>
1276          * If the returned method handle is invoked, the field's class will
1277          * be initialized, if it has not already been initialized.
1278          * @param refc the class or interface from which the method is accessed
1279          * @param name the field's name
1280          * @param type the field's type
1281          * @return a method handle which can store values into the field
1282          * @throws NoSuchFieldException if the field does not exist
1283          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1284          * @exception SecurityException if a security manager is present and it
1285          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1286          * @throws NullPointerException if any argument is null
1287          */
1288         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1289             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
1290             return getDirectField(REF_putStatic, refc, field);
1291         }
1292 
1293         /**
1294          * Produces a VarHandle giving access to a static field of type
1295          * {@code T} declared by a given declaring class, supporting shape
1296          * {@code ((empty) : T)}.
1297          * <p>
1298          * Access checking is performed immediately on behalf of the lookup
1299          * class.
1300          * <p>
1301          * If the returned VarHandle is operated on, the declaring class will be
1302          * initialized, if it has not already been initialized.
1303          * <p>
1304          * Certain access modes of the returned VarHandle are unsupported under
1305          * the following conditions:
1306          * <ul>
1307          * <li>if the field is declared {@code final}, then the write, atomic
1308          *     update, and numeric atomic update access modes are unsupported.
1309          * <li>if the field type is anything other than {@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 int} or
1315          *     {@code long}, then numeric atomic update access modes are
1316          *     unsupported.  (Future major platform releases of the JDK may
1317          *     support additional numeric types for certain currently
1318          *     unsupported access modes.)
1319          * </ul>
1320          * <p>
1321          * If the field is declared {@code volatile} then the returned VarHandle
1322          * will override access to the field (effectively ignore the
1323          * {@code volatile} declaration) in accordance to it's specified
1324          * access modes.
1325          * @param decl the class that declares the static field
1326          * @param name the field's name
1327          * @param type the field's type, of type {@code T}
1328          * @return a VarHandle giving access to a static field
1329          * @throws NoSuchFieldException if the field does not exist
1330          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1331          * @exception SecurityException if a security manager is present and it
1332          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1333          * @throws NullPointerException if any argument is null
1334          * @since 9
1335          */
1336         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1337             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
1338             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
1339             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
1340         }
1341 
1342         /**
1343          * Produces an early-bound method handle for a non-static method.
1344          * The receiver must have a supertype {@code defc} in which a method
1345          * of the given name and type is accessible to the lookup class.
1346          * The method and all its argument types must be accessible to the lookup object.
1347          * The type of the method handle will be that of the method,
1348          * without any insertion of an additional receiver parameter.
1349          * The given receiver will be bound into the method handle,
1350          * so that every call to the method handle will invoke the
1351          * requested method on the given receiver.
1352          * <p>
1353          * The returned method handle will have
1354          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1355          * the method's variable arity modifier bit ({@code 0x0080}) is set
1356          * <em>and</em> the trailing array argument is not the only argument.
1357          * (If the trailing array argument is the only argument,
1358          * the given receiver value will be bound to it.)
1359          * <p>
1360          * This is equivalent to the following code:
1361          * <blockquote><pre>{@code
1362 import static java.lang.invoke.MethodHandles.*;
1363 import static java.lang.invoke.MethodType.*;
1364 ...
1365 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
1366 MethodHandle mh1 = mh0.bindTo(receiver);
1367 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
1368 return mh1;
1369          * }</pre></blockquote>
1370          * where {@code defc} is either {@code receiver.getClass()} or a super
1371          * type of that class, in which the requested method is accessible
1372          * to the lookup class.
1373          * (Note that {@code bindTo} does not preserve variable arity.)
1374          * @param receiver the object from which the method is accessed
1375          * @param name the name of the method
1376          * @param type the type of the method, with the receiver argument omitted
1377          * @return the desired method handle
1378          * @throws NoSuchMethodException if the method does not exist
1379          * @throws IllegalAccessException if access checking fails
1380          *                                or if the method's variable arity modifier bit
1381          *                                is set and {@code asVarargsCollector} fails
1382          * @exception SecurityException if a security manager is present and it
1383          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1384          * @throws NullPointerException if any argument is null
1385          * @see MethodHandle#bindTo
1386          * @see #findVirtual
1387          */
1388         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1389             Class<? extends Object> refc = receiver.getClass(); // may get NPE
1390             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
1391             MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1392             return mh.bindArgumentL(0, receiver).setVarargs(method);
1393         }
1394 
1395         /**
1396          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1397          * to <i>m</i>, if the lookup class has permission.
1398          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
1399          * If <i>m</i> is virtual, overriding is respected on every call.
1400          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
1401          * The type of the method handle will be that of the method,
1402          * with the receiver type prepended (but only if it is non-static).
1403          * If the method's {@code accessible} flag is not set,
1404          * access checking is performed immediately on behalf of the lookup class.
1405          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
1406          * <p>
1407          * The returned method handle will have
1408          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1409          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1410          * <p>
1411          * If <i>m</i> is static, and
1412          * if the returned method handle is invoked, the method's class will
1413          * be initialized, if it has not already been initialized.
1414          * @param m the reflected method
1415          * @return a method handle which can invoke the reflected method
1416          * @throws IllegalAccessException if access checking fails
1417          *                                or if the method's variable arity modifier bit
1418          *                                is set and {@code asVarargsCollector} fails
1419          * @throws NullPointerException if the argument is null
1420          */
1421         public MethodHandle unreflect(Method m) throws IllegalAccessException {
1422             if (m.getDeclaringClass() == MethodHandle.class) {
1423                 MethodHandle mh = unreflectForMH(m);
1424                 if (mh != null)  return mh;
1425             }
1426             if (m.getDeclaringClass() == VarHandle.class) {
1427                 MethodHandle mh = unreflectForVH(m);
1428                 if (mh != null)  return mh;
1429             }
1430             MemberName method = new MemberName(m);
1431             byte refKind = method.getReferenceKind();
1432             if (refKind == REF_invokeSpecial)
1433                 refKind = REF_invokeVirtual;
1434             assert(method.isMethod());
1435             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
1436             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
1437         }
1438         private MethodHandle unreflectForMH(Method m) {
1439             // these names require special lookups because they throw UnsupportedOperationException
1440             if (MemberName.isMethodHandleInvokeName(m.getName()))
1441                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
1442             return null;
1443         }
1444         private MethodHandle unreflectForVH(Method m) {
1445             // these names require special lookups because they throw UnsupportedOperationException
1446             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
1447                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
1448             return null;
1449         }
1450 
1451         /**
1452          * Produces a method handle for a reflected method.
1453          * It will bypass checks for overriding methods on the receiver,
1454          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1455          * instruction from within the explicitly specified {@code specialCaller}.
1456          * The type of the method handle will be that of the method,
1457          * with a suitably restricted receiver type prepended.
1458          * (The receiver type will be {@code specialCaller} or a subtype.)
1459          * If the method's {@code accessible} flag is not set,
1460          * access checking is performed immediately on behalf of the lookup class,
1461          * as if {@code invokespecial} instruction were being linked.
1462          * <p>
1463          * Before method resolution,
1464          * if the explicitly specified caller class is not identical with the
1465          * lookup class, or if this lookup object does not have
1466          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1467          * privileges, the access fails.
1468          * <p>
1469          * The returned method handle will have
1470          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1471          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1472          * @param m the reflected method
1473          * @param specialCaller the class nominally calling the method
1474          * @return a method handle which can invoke the reflected method
1475          * @throws IllegalAccessException if access checking fails,
1476          *                                or if the method is {@code static},
1477          *                                or if the method's variable arity modifier bit
1478          *                                is set and {@code asVarargsCollector} fails
1479          * @throws NullPointerException if any argument is null
1480          */
1481         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
1482             checkSpecialCaller(specialCaller, null);
1483             Lookup specialLookup = this.in(specialCaller);
1484             MemberName method = new MemberName(m, true);
1485             assert(method.isMethod());
1486             // ignore m.isAccessible:  this is a new kind of access
1487             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
1488         }
1489 
1490         /**
1491          * Produces a method handle for a reflected constructor.
1492          * The type of the method handle will be that of the constructor,
1493          * with the return type changed to the declaring class.
1494          * The method handle will perform a {@code newInstance} operation,
1495          * creating a new instance of the constructor's class on the
1496          * arguments passed to the method handle.
1497          * <p>
1498          * If the constructor's {@code accessible} flag is not set,
1499          * access checking is performed immediately on behalf of the lookup class.
1500          * <p>
1501          * The returned method handle will have
1502          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1503          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
1504          * <p>
1505          * If the returned method handle is invoked, the constructor's class will
1506          * be initialized, if it has not already been initialized.
1507          * @param c the reflected constructor
1508          * @return a method handle which can invoke the reflected constructor
1509          * @throws IllegalAccessException if access checking fails
1510          *                                or if the method's variable arity modifier bit
1511          *                                is set and {@code asVarargsCollector} fails
1512          * @throws NullPointerException if the argument is null
1513          */
1514         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
1515             MemberName ctor = new MemberName(c);
1516             assert(ctor.isConstructor());
1517             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
1518             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
1519         }
1520 
1521         /**
1522          * Produces a method handle giving read access to a reflected field.
1523          * The type of the method handle will have a return type of the field's
1524          * value type.
1525          * If the field is static, the method handle will take no arguments.
1526          * Otherwise, its single argument will be the instance containing
1527          * the field.
1528          * If the field's {@code accessible} flag is not set,
1529          * access checking is performed immediately on behalf of the lookup class.
1530          * <p>
1531          * If the field is static, and
1532          * if the returned method handle is invoked, the field's class will
1533          * be initialized, if it has not already been initialized.
1534          * @param f the reflected field
1535          * @return a method handle which can load values from the reflected field
1536          * @throws IllegalAccessException if access checking fails
1537          * @throws NullPointerException if the argument is null
1538          */
1539         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
1540             return unreflectField(f, false);
1541         }
1542         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
1543             MemberName field = new MemberName(f, isSetter);
1544             assert(isSetter
1545                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
1546                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
1547             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
1548             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
1549         }
1550 
1551         /**
1552          * Produces a method handle giving write access to a reflected field.
1553          * The type of the method handle will have a void return type.
1554          * If the field is static, the method handle will take a single
1555          * argument, of the field's value type, the value to be stored.
1556          * Otherwise, the two arguments will be the instance containing
1557          * the field, and the value to be stored.
1558          * If the field's {@code accessible} flag is not set,
1559          * access checking is performed immediately on behalf of the lookup class.
1560          * <p>
1561          * If the field is static, and
1562          * if the returned method handle is invoked, the field's class will
1563          * be initialized, if it has not already been initialized.
1564          * @param f the reflected field
1565          * @return a method handle which can store values into the reflected field
1566          * @throws IllegalAccessException if access checking fails
1567          * @throws NullPointerException if the argument is null
1568          */
1569         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
1570             return unreflectField(f, true);
1571         }
1572 
1573         /**
1574          * Produces a VarHandle that accesses fields of type {@code T} declared
1575          * by a class of type {@code R}, as described by the given reflected
1576          * field.
1577          * If the field is non-static the VarHandle supports a shape of
1578          * {@code (R : T)}, otherwise supports a shape of {@code ((empty) : T)}.
1579          * <p>
1580          * Access checking is performed immediately on behalf of the lookup
1581          * class, regardless of the value of the field's {@code accessible}
1582          * flag.
1583          * <p>
1584          * If the field is static, and if the returned VarHandle is operated
1585          * on, the field's declaring class will be initialized, if it has not
1586          * already been initialized.
1587          * <p>
1588          * Certain access modes of the returned VarHandle are unsupported under
1589          * the following conditions:
1590          * <ul>
1591          * <li>if the field is declared {@code final}, then the write, atomic
1592          *     update, and numeric atomic update access modes are unsupported.
1593          * <li>if the field type is anything other than {@code int},
1594          *     {@code long} or a reference type, then atomic update access modes
1595          *     are unsupported.  (Future major platform releases of the JDK may
1596          *     support additional types for certain currently unsupported access
1597          *     modes.)
1598          * <li>if the field type is anything other than {@code int} or
1599          *     {@code long}, then numeric atomic update access modes are
1600          *     unsupported.  (Future major platform releases of the JDK may
1601          *     support additional numeric types for certain currently
1602          *     unsupported access modes.)
1603          * </ul>
1604          * <p>
1605          * If the field is declared {@code volatile} then the returned VarHandle
1606          * will override access to the field (effectively ignore the
1607          * {@code volatile} declaration) in accordance to it's specified
1608          * access modes.
1609          * @param f the reflected field, with a field of type {@code T}, and
1610          * a declaring class of type {@code R}
1611          * @return a VarHandle giving access to non-static fields or a static
1612          * field
1613          * @throws IllegalAccessException if access checking fails
1614          * @throws NullPointerException if the argument is null
1615          * @since 9
1616          */
1617         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
1618             MemberName getField = new MemberName(f, false);
1619             MemberName putField = new MemberName(f, true);
1620             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
1621                                                       f.getDeclaringClass(), getField, putField);
1622         }
1623 
1624         /**
1625          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1626          * created by this lookup object or a similar one.
1627          * Security and access checks are performed to ensure that this lookup object
1628          * is capable of reproducing the target method handle.
1629          * This means that the cracking may fail if target is a direct method handle
1630          * but was created by an unrelated lookup object.
1631          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
1632          * and was created by a lookup object for a different class.
1633          * @param target a direct method handle to crack into symbolic reference components
1634          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
1635          * @exception SecurityException if a security manager is present and it
1636          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1637          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
1638          * @exception NullPointerException if the target is {@code null}
1639          * @see MethodHandleInfo
1640          * @since 1.8
1641          */
1642         public MethodHandleInfo revealDirect(MethodHandle target) {
1643             MemberName member = target.internalMemberName();
1644             if (member == null || (!member.isResolved() &&
1645                                    !member.isMethodHandleInvoke() &&
1646                                    !member.isVarHandleMethodInvoke()))
1647                 throw newIllegalArgumentException("not a direct method handle");
1648             Class<?> defc = member.getDeclaringClass();
1649             byte refKind = member.getReferenceKind();
1650             assert(MethodHandleNatives.refKindIsValid(refKind));
1651             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
1652                 // Devirtualized method invocation is usually formally virtual.
1653                 // To avoid creating extra MemberName objects for this common case,
1654                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
1655                 refKind = REF_invokeVirtual;
1656             if (refKind == REF_invokeVirtual && defc.isInterface())
1657                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
1658                 refKind = REF_invokeInterface;
1659             // Check SM permissions and member access before cracking.
1660             try {
1661                 checkAccess(refKind, defc, member);
1662                 checkSecurityManager(defc, member);
1663             } catch (IllegalAccessException ex) {
1664                 throw new IllegalArgumentException(ex);
1665             }
1666             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
1667                 Class<?> callerClass = target.internalCallerClass();
1668                 if (!hasPrivateAccess() || callerClass != lookupClass())
1669                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
1670             }
1671             // Produce the handle to the results.
1672             return new InfoFromMemberName(this, member, refKind);
1673         }
1674 
1675         /// Helper methods, all package-private.
1676 
1677         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1678             checkSymbolicClass(refc);  // do this before attempting to resolve
1679             Objects.requireNonNull(name);
1680             Objects.requireNonNull(type);
1681             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1682                                             NoSuchFieldException.class);
1683         }
1684 
1685         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1686             checkSymbolicClass(refc);  // do this before attempting to resolve
1687             Objects.requireNonNull(name);
1688             Objects.requireNonNull(type);
1689             checkMethodName(refKind, name);  // NPE check on name
1690             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1691                                             NoSuchMethodException.class);
1692         }
1693 
1694         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
1695             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
1696             Objects.requireNonNull(member.getName());
1697             Objects.requireNonNull(member.getType());
1698             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
1699                                             ReflectiveOperationException.class);
1700         }
1701 
1702         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
1703             Objects.requireNonNull(refc);
1704             Class<?> caller = lookupClassOrNull();
1705             if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes))
1706                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
1707         }
1708 
1709         /** Check name for an illegal leading "&lt;" character. */
1710         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
1711             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
1712                 throw new NoSuchMethodException("illegal method name: "+name);
1713         }
1714 
1715 
1716         /**
1717          * Find my trustable caller class if m is a caller sensitive method.
1718          * If this lookup object has private access, then the caller class is the lookupClass.
1719          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
1720          */
1721         Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
1722             Class<?> callerClass = null;
1723             if (MethodHandleNatives.isCallerSensitive(m)) {
1724                 // Only lookups with private access are allowed to resolve caller-sensitive methods
1725                 if (hasPrivateAccess()) {
1726                     callerClass = lookupClass;
1727                 } else {
1728                     throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
1729                 }
1730             }
1731             return callerClass;
1732         }
1733 
1734         private boolean hasPrivateAccess() {
1735             return (allowedModes & PRIVATE) != 0;
1736         }
1737 
1738         /**
1739          * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
1740          * Determines a trustable caller class to compare with refc, the symbolic reference class.
1741          * If this lookup object has private access, then the caller class is the lookupClass.
1742          */
1743         void checkSecurityManager(Class<?> refc, MemberName m) {
1744             SecurityManager smgr = System.getSecurityManager();
1745             if (smgr == null)  return;
1746             if (allowedModes == TRUSTED)  return;
1747 
1748             // Step 1:
1749             boolean fullPowerLookup = hasPrivateAccess();
1750             if (!fullPowerLookup ||
1751                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
1752                 ReflectUtil.checkPackageAccess(refc);
1753             }
1754 
1755             if (m == null) {  // findClass or accessClass
1756                 // Step 2b:
1757                 if (!fullPowerLookup) {
1758                     smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
1759                 }
1760                 return;
1761             }
1762 
1763             // Step 2a:
1764             if (m.isPublic()) return;
1765             if (!fullPowerLookup) {
1766                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
1767             }
1768 
1769             // Step 3:
1770             Class<?> defc = m.getDeclaringClass();
1771             if (!fullPowerLookup && defc != refc) {
1772                 ReflectUtil.checkPackageAccess(defc);
1773             }
1774         }
1775 
1776         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1777             boolean wantStatic = (refKind == REF_invokeStatic);
1778             String message;
1779             if (m.isConstructor())
1780                 message = "expected a method, not a constructor";
1781             else if (!m.isMethod())
1782                 message = "expected a method";
1783             else if (wantStatic != m.isStatic())
1784                 message = wantStatic ? "expected a static method" : "expected a non-static method";
1785             else
1786                 { checkAccess(refKind, refc, m); return; }
1787             throw m.makeAccessException(message, this);
1788         }
1789 
1790         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1791             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
1792             String message;
1793             if (wantStatic != m.isStatic())
1794                 message = wantStatic ? "expected a static field" : "expected a non-static field";
1795             else
1796                 { checkAccess(refKind, refc, m); return; }
1797             throw m.makeAccessException(message, this);
1798         }
1799 
1800         /** Check public/protected/private bits on the symbolic reference class and its member. */
1801         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1802             assert(m.referenceKindIsConsistentWith(refKind) &&
1803                    MethodHandleNatives.refKindIsValid(refKind) &&
1804                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
1805             int allowedModes = this.allowedModes;
1806             if (allowedModes == TRUSTED)  return;
1807             int mods = m.getModifiers();
1808             if (Modifier.isProtected(mods) &&
1809                     refKind == REF_invokeVirtual &&
1810                     m.getDeclaringClass() == Object.class &&
1811                     m.getName().equals("clone") &&
1812                     refc.isArray()) {
1813                 // The JVM does this hack also.
1814                 // (See ClassVerifier::verify_invoke_instructions
1815                 // and LinkResolver::check_method_accessability.)
1816                 // Because the JVM does not allow separate methods on array types,
1817                 // there is no separate method for int[].clone.
1818                 // All arrays simply inherit Object.clone.
1819                 // But for access checking logic, we make Object.clone
1820                 // (normally protected) appear to be public.
1821                 // Later on, when the DirectMethodHandle is created,
1822                 // its leading argument will be restricted to the
1823                 // requested array type.
1824                 // N.B. The return type is not adjusted, because
1825                 // that is *not* the bytecode behavior.
1826                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
1827             }
1828             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
1829                 // cannot "new" a protected ctor in a different package
1830                 mods ^= Modifier.PROTECTED;
1831             }
1832             if (Modifier.isFinal(mods) &&
1833                     MethodHandleNatives.refKindIsSetter(refKind))
1834                 throw m.makeAccessException("unexpected set of a final field", this);
1835             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
1836             if ((requestedModes & allowedModes) != 0) {
1837                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
1838                                                     mods, lookupClass(), allowedModes))
1839                     return;
1840             } else {
1841                 // Protected members can also be checked as if they were package-private.
1842                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
1843                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
1844                     return;
1845             }
1846             throw m.makeAccessException(accessFailedMessage(refc, m), this);
1847         }
1848 
1849         String accessFailedMessage(Class<?> refc, MemberName m) {
1850             Class<?> defc = m.getDeclaringClass();
1851             int mods = m.getModifiers();
1852             // check the class first:
1853             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
1854                                (defc == refc ||
1855                                 Modifier.isPublic(refc.getModifiers())));
1856             if (!classOK && (allowedModes & PACKAGE) != 0) {
1857                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
1858                            (defc == refc ||
1859                             VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
1860             }
1861             if (!classOK)
1862                 return "class is not public";
1863             if (Modifier.isPublic(mods))
1864                 return "access to public member failed";  // (how?, module not readable?)
1865             if (Modifier.isPrivate(mods))
1866                 return "member is private";
1867             if (Modifier.isProtected(mods))
1868                 return "member is protected";
1869             return "member is private to package";
1870         }
1871 
1872         private static final boolean ALLOW_NESTMATE_ACCESS = false;
1873 
1874         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
1875             int allowedModes = this.allowedModes;
1876             if (allowedModes == TRUSTED)  return;
1877             if (!hasPrivateAccess()
1878                 || (specialCaller != lookupClass()
1879                        // ensure non-abstract methods in superinterfaces can be special-invoked
1880                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))
1881                     && !(ALLOW_NESTMATE_ACCESS &&
1882                          VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
1883                 throw new MemberName(specialCaller).
1884                     makeAccessException("no private access for invokespecial", this);
1885         }
1886 
1887         private boolean restrictProtectedReceiver(MemberName method) {
1888             // The accessing class only has the right to use a protected member
1889             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
1890             if (!method.isProtected() || method.isStatic()
1891                 || allowedModes == TRUSTED
1892                 || method.getDeclaringClass() == lookupClass()
1893                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
1894                 || (ALLOW_NESTMATE_ACCESS &&
1895                     VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass())))
1896                 return false;
1897             return true;
1898         }
1899         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
1900             assert(!method.isStatic());
1901             // receiver type of mh is too wide; narrow to caller
1902             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
1903                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
1904             }
1905             MethodType rawType = mh.type();
1906             if (rawType.parameterType(0) == caller)  return mh;
1907             MethodType narrowType = rawType.changeParameterType(0, caller);
1908             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
1909             assert(mh.viewAsTypeChecks(narrowType, true));
1910             return mh.copyWith(narrowType, mh.form);
1911         }
1912 
1913         /** Check access and get the requested method. */
1914         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1915             final boolean doRestrict    = true;
1916             final boolean checkSecurity = true;
1917             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1918         }
1919         /** Check access and get the requested method, eliding receiver narrowing rules. */
1920         private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1921             final boolean doRestrict    = false;
1922             final boolean checkSecurity = true;
1923             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1924         }
1925         /** Check access and get the requested method, eliding security manager checks. */
1926         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1927             final boolean doRestrict    = true;
1928             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
1929             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1930         }
1931         /** Common code for all methods; do not call directly except from immediately above. */
1932         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
1933                                                    boolean checkSecurity,
1934                                                    boolean doRestrict, Class<?> callerClass) throws IllegalAccessException {
1935             checkMethod(refKind, refc, method);
1936             // Optionally check with the security manager; this isn't needed for unreflect* calls.
1937             if (checkSecurity)
1938                 checkSecurityManager(refc, method);
1939             assert(!method.isMethodHandleInvoke());
1940 
1941             if (refKind == REF_invokeSpecial &&
1942                 refc != lookupClass() &&
1943                 !refc.isInterface() &&
1944                 refc != lookupClass().getSuperclass() &&
1945                 refc.isAssignableFrom(lookupClass())) {
1946                 assert(!method.getName().equals("<init>"));  // not this code path
1947                 // Per JVMS 6.5, desc. of invokespecial instruction:
1948                 // If the method is in a superclass of the LC,
1949                 // and if our original search was above LC.super,
1950                 // repeat the search (symbolic lookup) from LC.super
1951                 // and continue with the direct superclass of that class,
1952                 // and so forth, until a match is found or no further superclasses exist.
1953                 // FIXME: MemberName.resolve should handle this instead.
1954                 Class<?> refcAsSuper = lookupClass();
1955                 MemberName m2;
1956                 do {
1957                     refcAsSuper = refcAsSuper.getSuperclass();
1958                     m2 = new MemberName(refcAsSuper,
1959                                         method.getName(),
1960                                         method.getMethodType(),
1961                                         REF_invokeSpecial);
1962                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
1963                 } while (m2 == null &&         // no method is found yet
1964                          refc != refcAsSuper); // search up to refc
1965                 if (m2 == null)  throw new InternalError(method.toString());
1966                 method = m2;
1967                 refc = refcAsSuper;
1968                 // redo basic checks
1969                 checkMethod(refKind, refc, method);
1970             }
1971 
1972             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method);
1973             MethodHandle mh = dmh;
1974             // Optionally narrow the receiver argument to refc using restrictReceiver.
1975             if (doRestrict &&
1976                    (refKind == REF_invokeSpecial ||
1977                        (MethodHandleNatives.refKindHasReceiver(refKind) &&
1978                            restrictProtectedReceiver(method)))) {
1979                 mh = restrictReceiver(method, dmh, lookupClass());
1980             }
1981             mh = maybeBindCaller(method, mh, callerClass);
1982             mh = mh.setVarargs(method);
1983             return mh;
1984         }
1985         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
1986                                              Class<?> callerClass)
1987                                              throws IllegalAccessException {
1988             if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
1989                 return mh;
1990             Class<?> hostClass = lookupClass;
1991             if (!hasPrivateAccess())  // caller must have private access
1992                 hostClass = callerClass;  // callerClass came from a security manager style stack walk
1993             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
1994             // Note: caller will apply varargs after this step happens.
1995             return cbmh;
1996         }
1997         /** Check access and get the requested field. */
1998         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
1999             final boolean checkSecurity = true;
2000             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
2001         }
2002         /** Check access and get the requested field, eliding security manager checks. */
2003         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
2004             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
2005             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
2006         }
2007         /** Common code for all fields; do not call directly except from immediately above. */
2008         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
2009                                                   boolean checkSecurity) throws IllegalAccessException {
2010             checkField(refKind, refc, field);
2011             // Optionally check with the security manager; this isn't needed for unreflect* calls.
2012             if (checkSecurity)
2013                 checkSecurityManager(refc, field);
2014             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
2015             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
2016                                     restrictProtectedReceiver(field));
2017             if (doRestrict)
2018                 return restrictReceiver(field, dmh, lookupClass());
2019             return dmh;
2020         }
2021         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
2022                                             Class<?> refc, MemberName getField, MemberName putField)
2023                 throws IllegalAccessException {
2024             final boolean checkSecurity = true;
2025             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
2026         }
2027         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
2028                                                              Class<?> refc, MemberName getField, MemberName putField)
2029                 throws IllegalAccessException {
2030             final boolean checkSecurity = false;
2031             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
2032         }
2033         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
2034                                                   Class<?> refc, MemberName getField, MemberName putField,
2035                                                   boolean checkSecurity) throws IllegalAccessException {
2036             assert getField.isStatic() == putField.isStatic();
2037             assert getField.isGetter() && putField.isSetter();
2038             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
2039             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
2040 
2041             checkField(getRefKind, refc, getField);
2042             if (checkSecurity)
2043                 checkSecurityManager(refc, getField);
2044 
2045             if (!putField.isFinal()) {
2046                 // A VarHandle does not support updates to final fields, any
2047                 // such VarHandle to a final field will be read-only and
2048                 // therefore the following write-based accessibility checks are
2049                 // only required for non-final fields
2050                 checkField(putRefKind, refc, putField);
2051                 if (checkSecurity)
2052                     checkSecurityManager(refc, putField);
2053             }
2054 
2055             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
2056                                   restrictProtectedReceiver(getField));
2057             if (doRestrict) {
2058                 assert !getField.isStatic();
2059                 // receiver type of VarHandle is too wide; narrow to caller
2060                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
2061                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
2062                 }
2063                 refc = lookupClass();
2064             }
2065             return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED);
2066         }
2067         /** Check access and get the requested constructor. */
2068         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
2069             final boolean checkSecurity = true;
2070             return getDirectConstructorCommon(refc, ctor, checkSecurity);
2071         }
2072         /** Check access and get the requested constructor, eliding security manager checks. */
2073         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
2074             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
2075             return getDirectConstructorCommon(refc, ctor, checkSecurity);
2076         }
2077         /** Common code for all constructors; do not call directly except from immediately above. */
2078         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
2079                                                   boolean checkSecurity) throws IllegalAccessException {
2080             assert(ctor.isConstructor());
2081             checkAccess(REF_newInvokeSpecial, refc, ctor);
2082             // Optionally check with the security manager; this isn't needed for unreflect* calls.
2083             if (checkSecurity)
2084                 checkSecurityManager(refc, ctor);
2085             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
2086             return DirectMethodHandle.make(ctor).setVarargs(ctor);
2087         }
2088 
2089         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
2090          */
2091         /*non-public*/
2092         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException {
2093             if (!(type instanceof Class || type instanceof MethodType))
2094                 throw new InternalError("unresolved MemberName");
2095             MemberName member = new MemberName(refKind, defc, name, type);
2096             MethodHandle mh = LOOKASIDE_TABLE.get(member);
2097             if (mh != null) {
2098                 checkSymbolicClass(defc);
2099                 return mh;
2100             }
2101             // Treat MethodHandle.invoke and invokeExact specially.
2102             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
2103                 mh = findVirtualForMH(member.getName(), member.getMethodType());
2104                 if (mh != null) {
2105                     return mh;
2106                 }
2107             }
2108             MemberName resolved = resolveOrFail(refKind, member);
2109             mh = getDirectMethodForConstant(refKind, defc, resolved);
2110             if (mh instanceof DirectMethodHandle
2111                     && canBeCached(refKind, defc, resolved)) {
2112                 MemberName key = mh.internalMemberName();
2113                 if (key != null) {
2114                     key = key.asNormalOriginal();
2115                 }
2116                 if (member.equals(key)) {  // better safe than sorry
2117                     LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
2118                 }
2119             }
2120             return mh;
2121         }
2122         private
2123         boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
2124             if (refKind == REF_invokeSpecial) {
2125                 return false;
2126             }
2127             if (!Modifier.isPublic(defc.getModifiers()) ||
2128                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
2129                     !member.isPublic() ||
2130                     member.isCallerSensitive()) {
2131                 return false;
2132             }
2133             ClassLoader loader = defc.getClassLoader();
2134             if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) {
2135                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
2136                 boolean found = false;
2137                 while (sysl != null) {
2138                     if (loader == sysl) { found = true; break; }
2139                     sysl = sysl.getParent();
2140                 }
2141                 if (!found) {
2142                     return false;
2143                 }
2144             }
2145             try {
2146                 MemberName resolved2 = publicLookup().resolveOrFail(refKind,
2147                     new MemberName(refKind, defc, member.getName(), member.getType()));
2148                 checkSecurityManager(defc, resolved2);
2149             } catch (ReflectiveOperationException | SecurityException ex) {
2150                 return false;
2151             }
2152             return true;
2153         }
2154         private
2155         MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
2156                 throws ReflectiveOperationException {
2157             if (MethodHandleNatives.refKindIsField(refKind)) {
2158                 return getDirectFieldNoSecurityManager(refKind, defc, member);
2159             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
2160                 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
2161             } else if (refKind == REF_newInvokeSpecial) {
2162                 return getDirectConstructorNoSecurityManager(defc, member);
2163             }
2164             // oops
2165             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
2166         }
2167 
2168         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
2169     }
2170 
2171     /**
2172      * Helper class used to lazily create PUBLIC_LOOKUP with a lookup class
2173      * in an <em>unnamed module</em>.
2174      *
2175      * @see Lookup#publicLookup
2176      */
2177     private static class LookupHelper {
2178         private static final String UNNAMED = "Unnamed";
2179         private static final String OBJECT  = "java/lang/Object";
2180 
2181         private static Class<?> createClass() {
2182             try {
2183                 ClassWriter cw = new ClassWriter(0);
2184                 cw.visit(Opcodes.V1_8,
2185                          Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
2186                          UNNAMED,
2187                          null,
2188                          OBJECT,
2189                          null);
2190                 cw.visitSource(UNNAMED, null);
2191                 cw.visitEnd();
2192                 byte[] bytes = cw.toByteArray();
2193                 ClassLoader loader = new ClassLoader(null) {
2194                     @Override
2195                     protected Class<?> findClass(String cn) throws ClassNotFoundException {
2196                         if (cn.equals(UNNAMED))
2197                             return super.defineClass(UNNAMED, bytes, 0, bytes.length);
2198                         throw new ClassNotFoundException(cn);
2199                     }
2200                 };
2201                 return loader.loadClass(UNNAMED);
2202             } catch (Exception e) {
2203                 throw new InternalError(e);
2204             }
2205         }
2206 
2207         private static final Class<?> PUBLIC_LOOKUP_CLASS;
2208         static {
2209             PrivilegedAction<Class<?>> pa = new PrivilegedAction<Class<?>>() {
2210                 public Class<?> run() {
2211                     return createClass();
2212                 }
2213             };
2214             PUBLIC_LOOKUP_CLASS = AccessController.doPrivileged(pa);
2215         }
2216 
2217         /**
2218          * Lookup that is trusted minimally. It can only be used to create
2219          * method handles to publicly accessible members in exported packages.
2220          *
2221          * @see MethodHandles#publicLookup
2222          */
2223         static final Lookup PUBLIC_LOOKUP = new Lookup(PUBLIC_LOOKUP_CLASS, Lookup.PUBLIC);
2224     }
2225 
2226     /**
2227      * Produces a method handle constructing arrays of a desired type.
2228      * The return type of the method handle will be the array type.
2229      * The type of its sole argument will be {@code int}, which specifies the size of the array.
2230      * @param arrayClass an array type
2231      * @return a method handle which can create arrays of the given type
2232      * @throws NullPointerException if the argument is {@code null}
2233      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
2234      * @see java.lang.reflect.Array#newInstance(Class, int)
2235      * @since 9
2236      */
2237     public static
2238     MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
2239         if (!arrayClass.isArray()) {
2240             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
2241         }
2242         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
2243                 bindTo(arrayClass.getComponentType());
2244         return ani.asType(ani.type().changeReturnType(arrayClass));
2245     }
2246 
2247     /**
2248      * Produces a method handle giving read access to elements of an array.
2249      * The type of the method handle will have a return type of the array's
2250      * element type.  Its first argument will be the array type,
2251      * and the second will be {@code int}.
2252      * @param arrayClass an array type
2253      * @return a method handle which can load values from the given array type
2254      * @throws NullPointerException if the argument is null
2255      * @throws  IllegalArgumentException if arrayClass is not an array type
2256      */
2257     public static
2258     MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
2259         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false);
2260     }
2261 
2262     /**
2263      * Produces a method handle giving write access to elements of an array.
2264      * The type of the method handle will have a void return type.
2265      * Its last argument will be the array's element type.
2266      * The first and second arguments will be the array type and int.
2267      * @param arrayClass the class of an array
2268      * @return a method handle which can store values into the array type
2269      * @throws NullPointerException if the argument is null
2270      * @throws IllegalArgumentException if arrayClass is not an array type
2271      */
2272     public static
2273     MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
2274         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true);
2275     }
2276 
2277     /**
2278      *
2279      * Produces a VarHandle giving access to elements of an array type
2280      * {@code T[]}, supporting shape {@code (T[], int : T)}.
2281      * <p>
2282      * Certain access modes of the returned VarHandle are unsupported under
2283      * the following conditions:
2284      * <ul>
2285      * <li>if the component type is anything other than {@code int},
2286      *     {@code long} or a reference type, then atomic update access modes
2287      *     are unsupported.  (Future major platform releases of the JDK may
2288      *     support additional types for certain currently unsupported access
2289      *     modes.)
2290      * <li>if the component type is anything other than {@code int} or
2291      *     {@code long}, then numeric atomic update access modes are
2292      *     unsupported.  (Future major platform releases of the JDK may
2293      *     support additional numeric types for certain currently
2294      *     unsupported access modes.)
2295      * </ul>
2296      * @param arrayClass the class of an array, of type {@code T[]}
2297      * @return a VarHandle giving access to elements of an array
2298      * @throws NullPointerException if the arrayClass is null
2299      * @throws IllegalArgumentException if arrayClass is not an array type
2300      * @since 9
2301      */
2302     public static
2303     VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
2304         return VarHandles.makeArrayElementHandle(arrayClass);
2305     }
2306 
2307     /**
2308      * Produces a VarHandle giving access to elements of a {@code byte[]} array
2309      * viewed as if it were a different primitive array type, such as
2310      * {@code int[]} or {@code long[]}.  The shape of the resulting VarHandle is
2311      * {@code (byte[], int : T)}, where the {@code int} coordinate type
2312      * corresponds to an argument that is an index in a {@code byte[]} array,
2313      * and {@code T} is the component type of the given view array class.  The
2314      * returned VarHandle accesses bytes at an index in a {@code byte[]} array,
2315      * composing bytes to or from a value of {@code T} according to the given
2316      * endianness.
2317      * <p>
2318      * The supported component types (variables types) are {@code short},
2319      * {@code char}, {@code int}, {@code long}, {@code float} and
2320      * {@code double}.
2321      * <p>
2322      * Access of bytes at a given index will result in an
2323      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
2324      * or greater than the {@code byte[]} array length minus the size (in bytes)
2325      * of {@code T}.
2326      * <p>
2327      * Access of bytes at an index may be aligned or misaligned for {@code T},
2328      * with respect to the underlying memory address, {@code A} say, associated
2329      * with the array and index.
2330      * If access is misaligned then access for anything other than the
2331      * {@code get} and {@code set} access modes will result in an
2332      * {@code IllegalStateException}.  In such cases atomic access is only
2333      * guaranteed with respect to the largest power of two that divides the GCD
2334      * of {@code A} and the size (in bytes) of {@code T}.
2335      * If access is aligned then following access modes are supported and are
2336      * guaranteed to support atomic access:
2337      * <ul>
2338      * <li>read write access modes for all {@code T};
2339      * <li>atomic update access modes for {@code int}, {@code long},
2340      *     {@code float} or {@code double}.
2341      *     (Future major platform releases of the JDK may support additional
2342      *     types for certain currently unsupported access modes.)
2343      * <li>numeric atomic update access modes for {@code int} and {@code long}.
2344      *     (Future major platform releases of the JDK may support additional
2345      *     numeric types for certain currently unsupported access modes.)
2346      * </ul>
2347      * <p>
2348      * Misaligned access, and therefore atomicity guarantees, may be determined
2349      * for {@code byte[]} arrays without operating on a specific array.  Given
2350      * an {@code index}, {@code T} and it's corresponding boxed type,
2351      * {@code T_BOX}, misalignment may be determined as follows:
2352      * <pre>{@code
2353      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
2354      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
2355      *     alignmentOffset(0, sizeOfT);
2356      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
2357      * boolean isMisaligned = misalignedAtIndex != 0;
2358      * }</pre>
2359      *
2360      * @implNote
2361      * The variable types {@code float} and {@code double} are supported as if
2362      * by transformation to and access with the variable types {@code int} and
2363      * {@code long} respectively.  For example, the transformation of a
2364      * {@code double} value to a long value is performed as if using
2365      * {@link Double#doubleToRawLongBits(double)}, and the reverse
2366      * transformation is performed as if using
2367      * {@link Double#longBitsToDouble(long)}.
2368      *
2369      * @param viewArrayClass the view array class, with a component type of
2370      * type {@code T}
2371      * @param byteOrder the endianness of the view array elements, as
2372      * stored in the underlying {@code byte} array
2373      * @return a VarHandle giving access to elements of a {@code byte[]} array
2374      * viewed as if elements corresponding to the components type of the view
2375      * array class
2376      * @throws NullPointerException if viewArrayClass or byteOrder is null
2377      * @throws IllegalArgumentException if viewArrayClass is not an array type
2378      * @throws UnsupportedOperationException if the component type of
2379      * viewArrayClass is not supported as a variable type
2380      * @since 9
2381      */
2382     public static
2383     VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
2384                                      ByteOrder byteOrder) throws IllegalArgumentException {
2385         Objects.requireNonNull(byteOrder);
2386         return VarHandles.byteArrayViewHandle(viewArrayClass,
2387                                               byteOrder == ByteOrder.BIG_ENDIAN);
2388     }
2389 
2390     /**
2391      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
2392      * viewed as if it were an array of elements of a different primitive
2393      * component type to that of {@code byte}, such as {@code int[]} or
2394      * {@code long[]}.  The shape of the resulting VarHandle is
2395      * {@code (ByteBuffer, int : T)}, where the {@code int} coordinate type
2396      * corresponds to an argument that is an index in a {@code ByteBuffer}, and
2397      * {@code T} is the component type of the given view array class.  The
2398      * returned VarHandle accesses bytes at an index in a {@code ByteBuffer},
2399      * composing bytes to or from a value of {@code T} according to the given
2400      * endianness.
2401      * <p>
2402      * The supported component types (variables types) are {@code short},
2403      * {@code char}, {@code int}, {@code long}, {@code float} and
2404      * {@code double}.
2405      * <p>
2406      * Access will result in a {@code ReadOnlyBufferException} for anything
2407      * other than the read access modes if the {@code ByteBuffer} is read-only.
2408      * <p>
2409      * Access of bytes at a given index will result in an
2410      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
2411      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
2412      * {@code T}.
2413      * <p>
2414      * Access of bytes at an index may be aligned or misaligned for {@code T},
2415      * with respect to the underlying memory address, {@code A} say, associated
2416      * with the {@code ByteBuffer} and index.
2417      * If access is misaligned then access for anything other than the
2418      * {@code get} and {@code set} access modes will result in an
2419      * {@code IllegalStateException}.  In such cases atomic access is only
2420      * guaranteed with respect to the largest power of two that divides the GCD
2421      * of {@code A} and the size (in bytes) of {@code T}.
2422      * If access is aligned then following access modes are supported and are
2423      * guaranteed to support atomic access:
2424      * <ul>
2425      * <li>read write access modes for all {@code T};
2426      * <li>atomic update access modes for {@code int}, {@code long},
2427      *     {@code float} or {@code double}.
2428      *     (Future major platform releases of the JDK may support additional
2429      *     types for certain currently unsupported access modes.)
2430      * <li>numeric atomic update access modes for {@code int} and {@code long}.
2431      *     (Future major platform releases of the JDK may support additional
2432      *     numeric types for certain currently unsupported access modes.)
2433      * </ul>
2434      * <p>
2435      * Misaligned access, and therefore atomicity guarantees, may be determined
2436      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
2437      * {@code index}, {@code T} and it's corresponding boxed type,
2438      * {@code T_BOX}, as follows:
2439      * <pre>{@code
2440      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
2441      * ByteBuffer bb = ...
2442      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
2443      * boolean isMisaligned = misalignedAtIndex != 0;
2444      * }</pre>
2445      *
2446      * @implNote
2447      * The variable types {@code float} and {@code double} are supported as if
2448      * by transformation to and access with the variable types {@code int} and
2449      * {@code long} respectively.  For example, the transformation of a
2450      * {@code double} value to a long value is performed as if using
2451      * {@link Double#doubleToRawLongBits(double)}, and the reverse
2452      * transformation is performed as if using
2453      * {@link Double#longBitsToDouble(long)}.
2454      *
2455      * @param viewArrayClass the view array class, with a component type of
2456      * type {@code T}
2457      * @param byteOrder the endianness of the view array elements, as
2458      * stored in the underlying {@code ByteBuffer} (Note this overrides the
2459      * endianness of a {@code ByteBuffer})
2460      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
2461      * viewed as if elements corresponding to the components type of the view
2462      * array class
2463      * @throws NullPointerException if viewArrayClass or byteOrder is null
2464      * @throws IllegalArgumentException if viewArrayClass is not an array type
2465      * @throws UnsupportedOperationException if the component type of
2466      * viewArrayClass is not supported as a variable type
2467      * @since 9
2468      */
2469     public static
2470     VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
2471                                       ByteOrder byteOrder) throws IllegalArgumentException {
2472         Objects.requireNonNull(byteOrder);
2473         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
2474                                                    byteOrder == ByteOrder.BIG_ENDIAN);
2475     }
2476 
2477 
2478     /// method handle invocation (reflective style)
2479 
2480     /**
2481      * Produces a method handle which will invoke any method handle of the
2482      * given {@code type}, with a given number of trailing arguments replaced by
2483      * a single trailing {@code Object[]} array.
2484      * The resulting invoker will be a method handle with the following
2485      * arguments:
2486      * <ul>
2487      * <li>a single {@code MethodHandle} target
2488      * <li>zero or more leading values (counted by {@code leadingArgCount})
2489      * <li>an {@code Object[]} array containing trailing arguments
2490      * </ul>
2491      * <p>
2492      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
2493      * the indicated {@code type}.
2494      * That is, if the target is exactly of the given {@code type}, it will behave
2495      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
2496      * is used to convert the target to the required {@code type}.
2497      * <p>
2498      * The type of the returned invoker will not be the given {@code type}, but rather
2499      * will have all parameters except the first {@code leadingArgCount}
2500      * replaced by a single array of type {@code Object[]}, which will be
2501      * the final parameter.
2502      * <p>
2503      * Before invoking its target, the invoker will spread the final array, apply
2504      * reference casts as necessary, and unbox and widen primitive arguments.
2505      * If, when the invoker is called, the supplied array argument does
2506      * not have the correct number of elements, the invoker will throw
2507      * an {@link IllegalArgumentException} instead of invoking the target.
2508      * <p>
2509      * This method is equivalent to the following code (though it may be more efficient):
2510      * <blockquote><pre>{@code
2511 MethodHandle invoker = MethodHandles.invoker(type);
2512 int spreadArgCount = type.parameterCount() - leadingArgCount;
2513 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
2514 return invoker;
2515      * }</pre></blockquote>
2516      * This method throws no reflective or security exceptions.
2517      * @param type the desired target type
2518      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
2519      * @return a method handle suitable for invoking any method handle of the given type
2520      * @throws NullPointerException if {@code type} is null
2521      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
2522      *                  the range from 0 to {@code type.parameterCount()} inclusive,
2523      *                  or if the resulting method handle's type would have
2524      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2525      */
2526     public static
2527     MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
2528         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
2529             throw newIllegalArgumentException("bad argument count", leadingArgCount);
2530         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
2531         return type.invokers().spreadInvoker(leadingArgCount);
2532     }
2533 
2534     /**
2535      * Produces a special <em>invoker method handle</em> which can be used to
2536      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
2537      * The resulting invoker will have a type which is
2538      * exactly equal to the desired type, except that it will accept
2539      * an additional leading argument of type {@code MethodHandle}.
2540      * <p>
2541      * This method is equivalent to the following code (though it may be more efficient):
2542      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
2543      *
2544      * <p style="font-size:smaller;">
2545      * <em>Discussion:</em>
2546      * Invoker method handles can be useful when working with variable method handles
2547      * of unknown types.
2548      * For example, to emulate an {@code invokeExact} call to a variable method
2549      * handle {@code M}, extract its type {@code T},
2550      * look up the invoker method {@code X} for {@code T},
2551      * and call the invoker method, as {@code X.invoke(T, A...)}.
2552      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
2553      * is unknown.)
2554      * If spreading, collecting, or other argument transformations are required,
2555      * they can be applied once to the invoker {@code X} and reused on many {@code M}
2556      * method handle values, as long as they are compatible with the type of {@code X}.
2557      * <p style="font-size:smaller;">
2558      * <em>(Note:  The invoker method is not available via the Core Reflection API.
2559      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
2560      * on the declared {@code invokeExact} or {@code invoke} method will raise an
2561      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
2562      * <p>
2563      * This method throws no reflective or security exceptions.
2564      * @param type the desired target type
2565      * @return a method handle suitable for invoking any method handle of the given type
2566      * @throws IllegalArgumentException if the resulting method handle's type would have
2567      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2568      */
2569     public static
2570     MethodHandle exactInvoker(MethodType type) {
2571         return type.invokers().exactInvoker();
2572     }
2573 
2574     /**
2575      * Produces a special <em>invoker method handle</em> which can be used to
2576      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
2577      * The resulting invoker will have a type which is
2578      * exactly equal to the desired type, except that it will accept
2579      * an additional leading argument of type {@code MethodHandle}.
2580      * <p>
2581      * Before invoking its target, if the target differs from the expected type,
2582      * the invoker will apply reference casts as
2583      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
2584      * Similarly, the return value will be converted as necessary.
2585      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
2586      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
2587      * <p>
2588      * This method is equivalent to the following code (though it may be more efficient):
2589      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
2590      * <p style="font-size:smaller;">
2591      * <em>Discussion:</em>
2592      * A {@linkplain MethodType#genericMethodType general method type} is one which
2593      * mentions only {@code Object} arguments and return values.
2594      * An invoker for such a type is capable of calling any method handle
2595      * of the same arity as the general type.
2596      * <p style="font-size:smaller;">
2597      * <em>(Note:  The invoker method is not available via the Core Reflection API.
2598      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
2599      * on the declared {@code invokeExact} or {@code invoke} method will raise an
2600      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
2601      * <p>
2602      * This method throws no reflective or security exceptions.
2603      * @param type the desired target type
2604      * @return a method handle suitable for invoking any method handle convertible to the given type
2605      * @throws IllegalArgumentException if the resulting method handle's type would have
2606      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2607      */
2608     public static
2609     MethodHandle invoker(MethodType type) {
2610         return type.invokers().genericInvoker();
2611     }
2612 
2613     /**
2614      * Produces a special <em>invoker method handle</em> which can be used to
2615      * invoke a signature-polymorphic access mode method on any VarHandle whose
2616      * associated access mode type is compatible with the given type.
2617      * The resulting invoker will have a type which is exactly equal to the
2618      * desired given type, except that it will accept an additional leading
2619      * argument of type {@code VarHandle}.
2620      *
2621      * @param accessMode the VarHandle access mode
2622      * @param type the desired target type
2623      * @return a method handle suitable for invoking an access mode method of
2624      *         any VarHandle whose access mode type is of the given type.
2625      * @since 9
2626      */
2627     static public
2628     MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
2629         return type.invokers().varHandleMethodExactInvoker(accessMode);
2630     }
2631 
2632     /**
2633      * Produces a special <em>invoker method handle</em> which can be used to
2634      * invoke a signature-polymorphic access mode method on any VarHandle whose
2635      * associated access mode type is compatible with the given type.
2636      * The resulting invoker will have a type which is exactly equal to the
2637      * desired given type, except that it will accept an additional leading
2638      * argument of type {@code VarHandle}.
2639      * <p>
2640      * Before invoking its target, if the access mode type differs from the
2641      * desired given type, the invoker will apply reference casts as necessary
2642      * and box, unbox, or widen primitive values, as if by
2643      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
2644      * converted as necessary.
2645      * <p>
2646      * This method is equivalent to the following code (though it may be more
2647      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
2648      *
2649      * @param accessMode the VarHandle access mode
2650      * @param type the desired target type
2651      * @return a method handle suitable for invoking an access mode method of
2652      *         any VarHandle whose access mode type is convertible to the given
2653      *         type.
2654      * @since 9
2655      */
2656     static public
2657     MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
2658         return type.invokers().varHandleMethodInvoker(accessMode);
2659     }
2660 
2661     static /*non-public*/
2662     MethodHandle basicInvoker(MethodType type) {
2663         return type.invokers().basicInvoker();
2664     }
2665 
2666      /// method handle modification (creation from other method handles)
2667 
2668     /**
2669      * Produces a method handle which adapts the type of the
2670      * given method handle to a new type by pairwise argument and return type conversion.
2671      * The original type and new type must have the same number of arguments.
2672      * The resulting method handle is guaranteed to report a type
2673      * which is equal to the desired new type.
2674      * <p>
2675      * If the original type and new type are equal, returns target.
2676      * <p>
2677      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
2678      * and some additional conversions are also applied if those conversions fail.
2679      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
2680      * if possible, before or instead of any conversions done by {@code asType}:
2681      * <ul>
2682      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
2683      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
2684      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
2685      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
2686      *     the boolean is converted to a byte value, 1 for true, 0 for false.
2687      *     (This treatment follows the usage of the bytecode verifier.)
2688      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
2689      *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
2690      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
2691      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
2692      *     then a Java casting conversion (JLS 5.5) is applied.
2693      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
2694      *     widening and/or narrowing.)
2695      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
2696      *     conversion will be applied at runtime, possibly followed
2697      *     by a Java casting conversion (JLS 5.5) on the primitive value,
2698      *     possibly followed by a conversion from byte to boolean by testing
2699      *     the low-order bit.
2700      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
2701      *     and if the reference is null at runtime, a zero value is introduced.
2702      * </ul>
2703      * @param target the method handle to invoke after arguments are retyped
2704      * @param newType the expected type of the new method handle
2705      * @return a method handle which delegates to the target after performing
2706      *           any necessary argument conversions, and arranges for any
2707      *           necessary return value conversions
2708      * @throws NullPointerException if either argument is null
2709      * @throws WrongMethodTypeException if the conversion cannot be made
2710      * @see MethodHandle#asType
2711      */
2712     public static
2713     MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
2714         explicitCastArgumentsChecks(target, newType);
2715         // use the asTypeCache when possible:
2716         MethodType oldType = target.type();
2717         if (oldType == newType)  return target;
2718         if (oldType.explicitCastEquivalentToAsType(newType)) {
2719             return target.asFixedArity().asType(newType);
2720         }
2721         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
2722     }
2723 
2724     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
2725         if (target.type().parameterCount() != newType.parameterCount()) {
2726             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
2727         }
2728     }
2729 
2730     /**
2731      * Produces a method handle which adapts the calling sequence of the
2732      * given method handle to a new type, by reordering the arguments.
2733      * The resulting method handle is guaranteed to report a type
2734      * which is equal to the desired new type.
2735      * <p>
2736      * The given array controls the reordering.
2737      * Call {@code #I} the number of incoming parameters (the value
2738      * {@code newType.parameterCount()}, and call {@code #O} the number
2739      * of outgoing parameters (the value {@code target.type().parameterCount()}).
2740      * Then the length of the reordering array must be {@code #O},
2741      * and each element must be a non-negative number less than {@code #I}.
2742      * For every {@code N} less than {@code #O}, the {@code N}-th
2743      * outgoing argument will be taken from the {@code I}-th incoming
2744      * argument, where {@code I} is {@code reorder[N]}.
2745      * <p>
2746      * No argument or return value conversions are applied.
2747      * The type of each incoming argument, as determined by {@code newType},
2748      * must be identical to the type of the corresponding outgoing parameter
2749      * or parameters in the target method handle.
2750      * The return type of {@code newType} must be identical to the return
2751      * type of the original target.
2752      * <p>
2753      * The reordering array need not specify an actual permutation.
2754      * An incoming argument will be duplicated if its index appears
2755      * more than once in the array, and an incoming argument will be dropped
2756      * if its index does not appear in the array.
2757      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
2758      * incoming arguments which are not mentioned in the reordering array
2759      * may be of any type, as determined only by {@code newType}.
2760      * <blockquote><pre>{@code
2761 import static java.lang.invoke.MethodHandles.*;
2762 import static java.lang.invoke.MethodType.*;
2763 ...
2764 MethodType intfn1 = methodType(int.class, int.class);
2765 MethodType intfn2 = methodType(int.class, int.class, int.class);
2766 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
2767 assert(sub.type().equals(intfn2));
2768 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
2769 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
2770 assert((int)rsub.invokeExact(1, 100) == 99);
2771 MethodHandle add = ... (int x, int y) -> (x+y) ...;
2772 assert(add.type().equals(intfn2));
2773 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
2774 assert(twice.type().equals(intfn1));
2775 assert((int)twice.invokeExact(21) == 42);
2776      * }</pre></blockquote>
2777      * <p>
2778      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
2779      * variable-arity method handle}, even if the original target method handle was.
2780      * @param target the method handle to invoke after arguments are reordered
2781      * @param newType the expected type of the new method handle
2782      * @param reorder an index array which controls the reordering
2783      * @return a method handle which delegates to the target after it
2784      *           drops unused arguments and moves and/or duplicates the other arguments
2785      * @throws NullPointerException if any argument is null
2786      * @throws IllegalArgumentException if the index array length is not equal to
2787      *                  the arity of the target, or if any index array element
2788      *                  not a valid index for a parameter of {@code newType},
2789      *                  or if two corresponding parameter types in
2790      *                  {@code target.type()} and {@code newType} are not identical,
2791      */
2792     public static
2793     MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
2794         reorder = reorder.clone();  // get a private copy
2795         MethodType oldType = target.type();
2796         permuteArgumentChecks(reorder, newType, oldType);
2797         // first detect dropped arguments and handle them separately
2798         int[] originalReorder = reorder;
2799         BoundMethodHandle result = target.rebind();
2800         LambdaForm form = result.form;
2801         int newArity = newType.parameterCount();
2802         // Normalize the reordering into a real permutation,
2803         // by removing duplicates and adding dropped elements.
2804         // This somewhat improves lambda form caching, as well
2805         // as simplifying the transform by breaking it up into steps.
2806         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
2807             if (ddIdx > 0) {
2808                 // We found a duplicated entry at reorder[ddIdx].
2809                 // Example:  (x,y,z)->asList(x,y,z)
2810                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
2811                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
2812                 // The starred element corresponds to the argument
2813                 // deleted by the dupArgumentForm transform.
2814                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
2815                 boolean killFirst = false;
2816                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
2817                     // Set killFirst if the dup is larger than an intervening position.
2818                     // This will remove at least one inversion from the permutation.
2819                     if (dupVal > val) killFirst = true;
2820                 }
2821                 if (!killFirst) {
2822                     srcPos = dstPos;
2823                     dstPos = ddIdx;
2824                 }
2825                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
2826                 assert (reorder[srcPos] == reorder[dstPos]);
2827                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
2828                 // contract the reordering by removing the element at dstPos
2829                 int tailPos = dstPos + 1;
2830                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
2831                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
2832             } else {
2833                 int dropVal = ~ddIdx, insPos = 0;
2834                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
2835                     // Find first element of reorder larger than dropVal.
2836                     // This is where we will insert the dropVal.
2837                     insPos += 1;
2838                 }
2839                 Class<?> ptype = newType.parameterType(dropVal);
2840                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
2841                 oldType = oldType.insertParameterTypes(insPos, ptype);
2842                 // expand the reordering by inserting an element at insPos
2843                 int tailPos = insPos + 1;
2844                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
2845                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
2846                 reorder[insPos] = dropVal;
2847             }
2848             assert (permuteArgumentChecks(reorder, newType, oldType));
2849         }
2850         assert (reorder.length == newArity);  // a perfect permutation
2851         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
2852         form = form.editor().permuteArgumentsForm(1, reorder);
2853         if (newType == result.type() && form == result.internalForm())
2854             return result;
2855         return result.copyWith(newType, form);
2856     }
2857 
2858     /**
2859      * Return an indication of any duplicate or omission in reorder.
2860      * If the reorder contains a duplicate entry, return the index of the second occurrence.
2861      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
2862      * Otherwise, return zero.
2863      * If an element not in [0..newArity-1] is encountered, return reorder.length.
2864      */
2865     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
2866         final int BIT_LIMIT = 63;  // max number of bits in bit mask
2867         if (newArity < BIT_LIMIT) {
2868             long mask = 0;
2869             for (int i = 0; i < reorder.length; i++) {
2870                 int arg = reorder[i];
2871                 if (arg >= newArity) {
2872                     return reorder.length;
2873                 }
2874                 long bit = 1L << arg;
2875                 if ((mask & bit) != 0) {
2876                     return i;  // >0 indicates a dup
2877                 }
2878                 mask |= bit;
2879             }
2880             if (mask == (1L << newArity) - 1) {
2881                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
2882                 return 0;
2883             }
2884             // find first zero
2885             long zeroBit = Long.lowestOneBit(~mask);
2886             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
2887             assert(zeroPos <= newArity);
2888             if (zeroPos == newArity) {
2889                 return 0;
2890             }
2891             return ~zeroPos;
2892         } else {
2893             // same algorithm, different bit set
2894             BitSet mask = new BitSet(newArity);
2895             for (int i = 0; i < reorder.length; i++) {
2896                 int arg = reorder[i];
2897                 if (arg >= newArity) {
2898                     return reorder.length;
2899                 }
2900                 if (mask.get(arg)) {
2901                     return i;  // >0 indicates a dup
2902                 }
2903                 mask.set(arg);
2904             }
2905             int zeroPos = mask.nextClearBit(0);
2906             assert(zeroPos <= newArity);
2907             if (zeroPos == newArity) {
2908                 return 0;
2909             }
2910             return ~zeroPos;
2911         }
2912     }
2913 
2914     private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
2915         if (newType.returnType() != oldType.returnType())
2916             throw newIllegalArgumentException("return types do not match",
2917                     oldType, newType);
2918         if (reorder.length == oldType.parameterCount()) {
2919             int limit = newType.parameterCount();
2920             boolean bad = false;
2921             for (int j = 0; j < reorder.length; j++) {
2922                 int i = reorder[j];
2923                 if (i < 0 || i >= limit) {
2924                     bad = true; break;
2925                 }
2926                 Class<?> src = newType.parameterType(i);
2927                 Class<?> dst = oldType.parameterType(j);
2928                 if (src != dst)
2929                     throw newIllegalArgumentException("parameter types do not match after reorder",
2930                             oldType, newType);
2931             }
2932             if (!bad)  return true;
2933         }
2934         throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
2935     }
2936 
2937     /**
2938      * Produces a method handle of the requested return type which returns the given
2939      * constant value every time it is invoked.
2940      * <p>
2941      * Before the method handle is returned, the passed-in value is converted to the requested type.
2942      * If the requested type is primitive, widening primitive conversions are attempted,
2943      * else reference conversions are attempted.
2944      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
2945      * @param type the return type of the desired method handle
2946      * @param value the value to return
2947      * @return a method handle of the given return type and no arguments, which always returns the given value
2948      * @throws NullPointerException if the {@code type} argument is null
2949      * @throws ClassCastException if the value cannot be converted to the required return type
2950      * @throws IllegalArgumentException if the given type is {@code void.class}
2951      */
2952     public static
2953     MethodHandle constant(Class<?> type, Object value) {
2954         if (type.isPrimitive()) {
2955             if (type == void.class)
2956                 throw newIllegalArgumentException("void type");
2957             Wrapper w = Wrapper.forPrimitiveType(type);
2958             value = w.convert(value, type);
2959             if (w.zero().equals(value))
2960                 return zero(w, type);
2961             return insertArguments(identity(type), 0, value);
2962         } else {
2963             if (value == null)
2964                 return zero(Wrapper.OBJECT, type);
2965             return identity(type).bindTo(value);
2966         }
2967     }
2968 
2969     /**
2970      * Produces a method handle which returns its sole argument when invoked.
2971      * @param type the type of the sole parameter and return value of the desired method handle
2972      * @return a unary method handle which accepts and returns the given type
2973      * @throws NullPointerException if the argument is null
2974      * @throws IllegalArgumentException if the given type is {@code void.class}
2975      */
2976     public static
2977     MethodHandle identity(Class<?> type) {
2978         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
2979         int pos = btw.ordinal();
2980         MethodHandle ident = IDENTITY_MHS[pos];
2981         if (ident == null) {
2982             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
2983         }
2984         if (ident.type().returnType() == type)
2985             return ident;
2986         // something like identity(Foo.class); do not bother to intern these
2987         assert (btw == Wrapper.OBJECT);
2988         return makeIdentity(type);
2989     }
2990 
2991     /**
2992      * Produces a constant method handle of the requested return type which
2993      * returns the default value for that type every time it is invoked.
2994      * The resulting constant method handle will have no side effects.
2995      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
2996      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
2997      * since {@code explicitCastArguments} converts {@code null} to default values.
2998      * @param type the expected return type of the desired method handle
2999      * @return a constant method handle that takes no arguments
3000      *         and returns the default value of the given type (or void, if the type is void)
3001      * @throws NullPointerException if the argument is null
3002      * @see MethodHandles#constant
3003      * @see MethodHandles#empty
3004      * @since 9
3005      */
3006     public static  MethodHandle zero(Class<?> type) {
3007         Objects.requireNonNull(type);
3008         return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
3009     }
3010 
3011     private static MethodHandle identityOrVoid(Class<?> type) {
3012         return type == void.class ? zero(type) : identity(type);
3013     }
3014 
3015     /**
3016      * Produces a method handle of the requested type which ignores any arguments, does nothing,
3017      * and returns a suitable default depending on the return type.
3018      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
3019      * <p>The returned method handle is equivalent to
3020      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
3021      * <p>
3022      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
3023      * {@code guardWithTest(pred, target, empty(target.type())}.
3024      * @param type the type of the desired method handle
3025      * @return a constant method handle of the given type, which returns a default value of the given return type
3026      * @throws NullPointerException if the argument is null
3027      * @see MethodHandles#zero
3028      * @see MethodHandles#constant
3029      * @since 9
3030      */
3031     public static  MethodHandle empty(MethodType type) {
3032         Objects.requireNonNull(type);
3033         return dropArguments(zero(type.returnType()), 0, type.parameterList());
3034     }
3035 
3036     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.values().length];
3037     private static MethodHandle makeIdentity(Class<?> ptype) {
3038         MethodType mtype = methodType(ptype, ptype);
3039         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
3040         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
3041     }
3042 
3043     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
3044         int pos = btw.ordinal();
3045         MethodHandle zero = ZERO_MHS[pos];
3046         if (zero == null) {
3047             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
3048         }
3049         if (zero.type().returnType() == rtype)
3050             return zero;
3051         assert(btw == Wrapper.OBJECT);
3052         return makeZero(rtype);
3053     }
3054     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.values().length];
3055     private static MethodHandle makeZero(Class<?> rtype) {
3056         MethodType mtype = methodType(rtype);
3057         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
3058         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
3059     }
3060 
3061     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
3062         // Simulate a CAS, to avoid racy duplication of results.
3063         MethodHandle prev = cache[pos];
3064         if (prev != null) return prev;
3065         return cache[pos] = value;
3066     }
3067 
3068     /**
3069      * Provides a target method handle with one or more <em>bound arguments</em>
3070      * in advance of the method handle's invocation.
3071      * The formal parameters to the target corresponding to the bound
3072      * arguments are called <em>bound parameters</em>.
3073      * Returns a new method handle which saves away the bound arguments.
3074      * When it is invoked, it receives arguments for any non-bound parameters,
3075      * binds the saved arguments to their corresponding parameters,
3076      * and calls the original target.
3077      * <p>
3078      * The type of the new method handle will drop the types for the bound
3079      * parameters from the original target type, since the new method handle
3080      * will no longer require those arguments to be supplied by its callers.
3081      * <p>
3082      * Each given argument object must match the corresponding bound parameter type.
3083      * If a bound parameter type is a primitive, the argument object
3084      * must be a wrapper, and will be unboxed to produce the primitive value.
3085      * <p>
3086      * The {@code pos} argument selects which parameters are to be bound.
3087      * It may range between zero and <i>N-L</i> (inclusively),
3088      * where <i>N</i> is the arity of the target method handle
3089      * and <i>L</i> is the length of the values array.
3090      * <p>
3091      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3092      * variable-arity method handle}, even if the original target method handle was.
3093      * @param target the method handle to invoke after the argument is inserted
3094      * @param pos where to insert the argument (zero for the first)
3095      * @param values the series of arguments to insert
3096      * @return a method handle which inserts an additional argument,
3097      *         before calling the original method handle
3098      * @throws NullPointerException if the target or the {@code values} array is null
3099      * @see MethodHandle#bindTo
3100      */
3101     public static
3102     MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
3103         int insCount = values.length;
3104         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
3105         if (insCount == 0)  return target;
3106         BoundMethodHandle result = target.rebind();
3107         for (int i = 0; i < insCount; i++) {
3108             Object value = values[i];
3109             Class<?> ptype = ptypes[pos+i];
3110             if (ptype.isPrimitive()) {
3111                 result = insertArgumentPrimitive(result, pos, ptype, value);
3112             } else {
3113                 value = ptype.cast(value);  // throw CCE if needed
3114                 result = result.bindArgumentL(pos, value);
3115             }
3116         }
3117         return result;
3118     }
3119 
3120     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
3121                                                              Class<?> ptype, Object value) {
3122         Wrapper w = Wrapper.forPrimitiveType(ptype);
3123         // perform unboxing and/or primitive conversion
3124         value = w.convert(value, ptype);
3125         switch (w) {
3126         case INT:     return result.bindArgumentI(pos, (int)value);
3127         case LONG:    return result.bindArgumentJ(pos, (long)value);
3128         case FLOAT:   return result.bindArgumentF(pos, (float)value);
3129         case DOUBLE:  return result.bindArgumentD(pos, (double)value);
3130         default:      return result.bindArgumentI(pos, ValueConversions.widenSubword(value));
3131         }
3132     }
3133 
3134     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
3135         MethodType oldType = target.type();
3136         int outargs = oldType.parameterCount();
3137         int inargs  = outargs - insCount;
3138         if (inargs < 0)
3139             throw newIllegalArgumentException("too many values to insert");
3140         if (pos < 0 || pos > inargs)
3141             throw newIllegalArgumentException("no argument type to append");
3142         return oldType.ptypes();
3143     }
3144 
3145     /**
3146      * Produces a method handle which will discard some dummy arguments
3147      * before calling some other specified <i>target</i> method handle.
3148      * The type of the new method handle will be the same as the target's type,
3149      * except it will also include the dummy argument types,
3150      * at some given position.
3151      * <p>
3152      * The {@code pos} argument may range between zero and <i>N</i>,
3153      * where <i>N</i> is the arity of the target.
3154      * If {@code pos} is zero, the dummy arguments will precede
3155      * the target's real arguments; if {@code pos} is <i>N</i>
3156      * they will come after.
3157      * <p>
3158      * <b>Example:</b>
3159      * <blockquote><pre>{@code
3160 import static java.lang.invoke.MethodHandles.*;
3161 import static java.lang.invoke.MethodType.*;
3162 ...
3163 MethodHandle cat = lookup().findVirtual(String.class,
3164   "concat", methodType(String.class, String.class));
3165 assertEquals("xy", (String) cat.invokeExact("x", "y"));
3166 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
3167 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
3168 assertEquals(bigType, d0.type());
3169 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
3170      * }</pre></blockquote>
3171      * <p>
3172      * This method is also equivalent to the following code:
3173      * <blockquote><pre>
3174      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
3175      * </pre></blockquote>
3176      * @param target the method handle to invoke after the arguments are dropped
3177      * @param valueTypes the type(s) of the argument(s) to drop
3178      * @param pos position of first argument to drop (zero for the leftmost)
3179      * @return a method handle which drops arguments of the given types,
3180      *         before calling the original method handle
3181      * @throws NullPointerException if the target is null,
3182      *                              or if the {@code valueTypes} list or any of its elements is null
3183      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
3184      *                  or if {@code pos} is negative or greater than the arity of the target,
3185      *                  or if the new method handle's type would have too many parameters
3186      */
3187     public static
3188     MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
3189         MethodType oldType = target.type();  // get NPE
3190         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
3191         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
3192         if (dropped == 0)  return target;
3193         BoundMethodHandle result = target.rebind();
3194         LambdaForm lform = result.form;
3195         int insertFormArg = 1 + pos;
3196         for (Class<?> ptype : valueTypes) {
3197             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
3198         }
3199         result = result.copyWith(newType, lform);
3200         return result;
3201     }
3202 
3203     private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
3204         int dropped = valueTypes.size();
3205         MethodType.checkSlotCount(dropped);
3206         int outargs = oldType.parameterCount();
3207         int inargs  = outargs + dropped;
3208         if (pos < 0 || pos > outargs)
3209             throw newIllegalArgumentException("no argument type to remove"
3210                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
3211                     );
3212         return dropped;
3213     }
3214 
3215     /**
3216      * Produces a method handle which will discard some dummy arguments
3217      * before calling some other specified <i>target</i> method handle.
3218      * The type of the new method handle will be the same as the target's type,
3219      * except it will also include the dummy argument types,
3220      * at some given position.
3221      * <p>
3222      * The {@code pos} argument may range between zero and <i>N</i>,
3223      * where <i>N</i> is the arity of the target.
3224      * If {@code pos} is zero, the dummy arguments will precede
3225      * the target's real arguments; if {@code pos} is <i>N</i>
3226      * they will come after.
3227      * @apiNote
3228      * <blockquote><pre>{@code
3229 import static java.lang.invoke.MethodHandles.*;
3230 import static java.lang.invoke.MethodType.*;
3231 ...
3232 MethodHandle cat = lookup().findVirtual(String.class,
3233   "concat", methodType(String.class, String.class));
3234 assertEquals("xy", (String) cat.invokeExact("x", "y"));
3235 MethodHandle d0 = dropArguments(cat, 0, String.class);
3236 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
3237 MethodHandle d1 = dropArguments(cat, 1, String.class);
3238 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
3239 MethodHandle d2 = dropArguments(cat, 2, String.class);
3240 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
3241 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
3242 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
3243      * }</pre></blockquote>
3244      * <p>
3245      * This method is also equivalent to the following code:
3246      * <blockquote><pre>
3247      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
3248      * </pre></blockquote>
3249      * @param target the method handle to invoke after the arguments are dropped
3250      * @param valueTypes the type(s) of the argument(s) to drop
3251      * @param pos position of first argument to drop (zero for the leftmost)
3252      * @return a method handle which drops arguments of the given types,
3253      *         before calling the original method handle
3254      * @throws NullPointerException if the target is null,
3255      *                              or if the {@code valueTypes} array or any of its elements is null
3256      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
3257      *                  or if {@code pos} is negative or greater than the arity of the target,
3258      *                  or if the new method handle's type would have
3259      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
3260      */
3261     public static
3262     MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
3263         return dropArguments(target, pos, Arrays.asList(valueTypes));
3264     }
3265 
3266     // private version which allows caller some freedom with error handling
3267     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
3268                                       boolean nullOnFailure) {
3269         List<Class<?>> oldTypes = target.type().parameterList();
3270         int match = oldTypes.size();
3271         if (skip != 0) {
3272             if (skip < 0 || skip > match) {
3273                 throw newIllegalArgumentException("illegal skip", skip, target);
3274             }
3275             oldTypes = oldTypes.subList(skip, match);
3276             match -= skip;
3277         }
3278         List<Class<?>> addTypes = newTypes;
3279         int add = addTypes.size();
3280         if (pos != 0) {
3281             if (pos < 0 || pos > add) {
3282                 throw newIllegalArgumentException("illegal pos", pos, newTypes);
3283             }
3284             addTypes = addTypes.subList(pos, add);
3285             add -= pos; assert(addTypes.size() == add);
3286         }
3287         // Do not add types which already match the existing arguments.
3288         if (match > add || !oldTypes.equals(addTypes.subList(0, match))) {
3289             if (nullOnFailure) {
3290                 return null;
3291             }
3292             throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes);
3293         }
3294         addTypes = addTypes.subList(match, add);
3295         add -= match; assert(addTypes.size() == add);
3296         // newTypes:     (   P*[pos], M*[match], A*[add] )
3297         // target: ( S*[skip],        M*[match]  )
3298         MethodHandle adapter = target;
3299         if (add > 0) {
3300             adapter = dropArguments(adapter, skip+ match, addTypes);
3301         }
3302         // adapter: (S*[skip],        M*[match], A*[add] )
3303         if (pos > 0) {
3304             adapter = dropArguments(adapter, skip, newTypes.subList(0, pos));
3305        }
3306         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
3307         return adapter;
3308     }
3309 
3310     /**
3311      * Adapts a target method handle to match the given parameter type list, if necessary, by adding dummy arguments.
3312      * Some leading parameters are first skipped; they will be left unchanged and are otherwise ignored.
3313      * The remaining types in the target's parameter type list must be contained as a sub-list of the given type list,
3314      * at the given position.
3315      * Any non-matching parameter types (before or after the matching sub-list) are inserted in corresponding
3316      * positions of the target method handle's parameters, as if by {@link #dropArguments}.
3317      * (More precisely, elements in the new list before {@code pos} are inserted into the target list at {@code skip},
3318      * while elements in the new list after the match beginning at {@code pos} are inserted at the end of the
3319      * target list.)
3320      * The target's return type will be unchanged.
3321      * @apiNote
3322      * Two method handles whose argument lists are "effectively identical" (i.e., identical
3323      * in a common prefix) may be mutually converted to a common type
3324      * by two calls to {@code dropArgumentsToMatch}, as follows:
3325      * <blockquote><pre>{@code
3326 import static java.lang.invoke.MethodHandles.*;
3327 import static java.lang.invoke.MethodType.*;
3328 ...
3329 ...
3330 MethodHandle h0 = constant(boolean.class, true);
3331 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
3332 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
3333 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
3334 if (h1.type().parameterCount() < h2.type().parameterCount())
3335     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
3336 else
3337     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
3338 MethodHandle h3 = guardWithTest(h0, h1, h2);
3339 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
3340      * }</pre></blockquote>
3341      * @param target the method handle to adapt
3342      * @param skip number of targets parameters to disregard (they will be unchanged)
3343      * @param newTypes the desired argument list of the method handle
3344      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
3345      * @return a possibly adapted method handle
3346      * @throws NullPointerException if either argument is null
3347      * @throws IllegalArgumentException
3348      *         if either index is out of range in its corresponding list, or
3349      *         if the non-skipped target parameter types match the new types at {@code pos}
3350      * @since 9
3351      */
3352     public static
3353     MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
3354         Objects.requireNonNull(target);
3355         Objects.requireNonNull(newTypes);
3356         return dropArgumentsToMatch(target, skip, newTypes, pos, false);
3357     }
3358 
3359     /**
3360      * Adapts a target method handle by pre-processing
3361      * one or more of its arguments, each with its own unary filter function,
3362      * and then calling the target with each pre-processed argument
3363      * replaced by the result of its corresponding filter function.
3364      * <p>
3365      * The pre-processing is performed by one or more method handles,
3366      * specified in the elements of the {@code filters} array.
3367      * The first element of the filter array corresponds to the {@code pos}
3368      * argument of the target, and so on in sequence.
3369      * <p>
3370      * Null arguments in the array are treated as identity functions,
3371      * and the corresponding arguments left unchanged.
3372      * (If there are no non-null elements in the array, the original target is returned.)
3373      * Each filter is applied to the corresponding argument of the adapter.
3374      * <p>
3375      * If a filter {@code F} applies to the {@code N}th argument of
3376      * the target, then {@code F} must be a method handle which
3377      * takes exactly one argument.  The type of {@code F}'s sole argument
3378      * replaces the corresponding argument type of the target
3379      * in the resulting adapted method handle.
3380      * The return type of {@code F} must be identical to the corresponding
3381      * parameter type of the target.
3382      * <p>
3383      * It is an error if there are elements of {@code filters}
3384      * (null or not)
3385      * which do not correspond to argument positions in the target.
3386      * <p><b>Example:</b>
3387      * <blockquote><pre>{@code
3388 import static java.lang.invoke.MethodHandles.*;
3389 import static java.lang.invoke.MethodType.*;
3390 ...
3391 MethodHandle cat = lookup().findVirtual(String.class,
3392   "concat", methodType(String.class, String.class));
3393 MethodHandle upcase = lookup().findVirtual(String.class,
3394   "toUpperCase", methodType(String.class));
3395 assertEquals("xy", (String) cat.invokeExact("x", "y"));
3396 MethodHandle f0 = filterArguments(cat, 0, upcase);
3397 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
3398 MethodHandle f1 = filterArguments(cat, 1, upcase);
3399 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
3400 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
3401 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
3402      * }</pre></blockquote>
3403      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3404      * denotes the return type of both the {@code target} and resulting adapter.
3405      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
3406      * of the parameters and arguments that precede and follow the filter position
3407      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
3408      * values of the filtered parameters and arguments; they also represent the
3409      * return types of the {@code filter[i]} handles. The latter accept arguments
3410      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
3411      * the resulting adapter.
3412      * <blockquote><pre>{@code
3413      * T target(P... p, A[i]... a[i], B... b);
3414      * A[i] filter[i](V[i]);
3415      * T adapter(P... p, V[i]... v[i], B... b) {
3416      *   return target(p..., filter[i](v[i])..., b...);
3417      * }
3418      * }</pre></blockquote>
3419      * <p>
3420      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3421      * variable-arity method handle}, even if the original target method handle was.
3422      *
3423      * @param target the method handle to invoke after arguments are filtered
3424      * @param pos the position of the first argument to filter
3425      * @param filters method handles to call initially on filtered arguments
3426      * @return method handle which incorporates the specified argument filtering logic
3427      * @throws NullPointerException if the target is null
3428      *                              or if the {@code filters} array is null
3429      * @throws IllegalArgumentException if a non-null element of {@code filters}
3430      *          does not match a corresponding argument type of target as described above,
3431      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
3432      *          or if the resulting method handle's type would have
3433      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
3434      */
3435     public static
3436     MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
3437         filterArgumentsCheckArity(target, pos, filters);
3438         MethodHandle adapter = target;
3439         int curPos = pos-1;  // pre-incremented
3440         for (MethodHandle filter : filters) {
3441             curPos += 1;
3442             if (filter == null)  continue;  // ignore null elements of filters
3443             adapter = filterArgument(adapter, curPos, filter);
3444         }
3445         return adapter;
3446     }
3447 
3448     /*non-public*/ static
3449     MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
3450         filterArgumentChecks(target, pos, filter);
3451         MethodType targetType = target.type();
3452         MethodType filterType = filter.type();
3453         BoundMethodHandle result = target.rebind();
3454         Class<?> newParamType = filterType.parameterType(0);
3455         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
3456         MethodType newType = targetType.changeParameterType(pos, newParamType);
3457         result = result.copyWithExtendL(newType, lform, filter);
3458         return result;
3459     }
3460 
3461     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
3462         MethodType targetType = target.type();
3463         int maxPos = targetType.parameterCount();
3464         if (pos + filters.length > maxPos)
3465             throw newIllegalArgumentException("too many filters");
3466     }
3467 
3468     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
3469         MethodType targetType = target.type();
3470         MethodType filterType = filter.type();
3471         if (filterType.parameterCount() != 1
3472             || filterType.returnType() != targetType.parameterType(pos))
3473             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3474     }
3475 
3476     /**
3477      * Adapts a target method handle by pre-processing
3478      * a sub-sequence of its arguments with a filter (another method handle).
3479      * The pre-processed arguments are replaced by the result (if any) of the
3480      * filter function.
3481      * The target is then called on the modified (usually shortened) argument list.
3482      * <p>
3483      * If the filter returns a value, the target must accept that value as
3484      * its argument in position {@code pos}, preceded and/or followed by
3485      * any arguments not passed to the filter.
3486      * If the filter returns void, the target must accept all arguments
3487      * not passed to the filter.
3488      * No arguments are reordered, and a result returned from the filter
3489      * replaces (in order) the whole subsequence of arguments originally
3490      * passed to the adapter.
3491      * <p>
3492      * The argument types (if any) of the filter
3493      * replace zero or one argument types of the target, at position {@code pos},
3494      * in the resulting adapted method handle.
3495      * The return type of the filter (if any) must be identical to the
3496      * argument type of the target at position {@code pos}, and that target argument
3497      * is supplied by the return value of the filter.
3498      * <p>
3499      * In all cases, {@code pos} must be greater than or equal to zero, and
3500      * {@code pos} must also be less than or equal to the target's arity.
3501      * <p><b>Example:</b>
3502      * <blockquote><pre>{@code
3503 import static java.lang.invoke.MethodHandles.*;
3504 import static java.lang.invoke.MethodType.*;
3505 ...
3506 MethodHandle deepToString = publicLookup()
3507   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
3508 
3509 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
3510 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
3511 
3512 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
3513 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
3514 
3515 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
3516 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
3517 assertEquals("[top, [up, down], strange]",
3518              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
3519 
3520 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
3521 assertEquals("[top, [up, down], [strange]]",
3522              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
3523 
3524 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
3525 assertEquals("[top, [[up, down, strange], charm], bottom]",
3526              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
3527      * }</pre></blockquote>
3528      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3529      * represents the return type of the {@code target} and resulting adapter.
3530      * {@code V}/{@code v} stand for the return type and value of the
3531      * {@code filter}, which are also found in the signature and arguments of
3532      * the {@code target}, respectively, unless {@code V} is {@code void}.
3533      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
3534      * and values preceding and following the collection position, {@code pos},
3535      * in the {@code target}'s signature. They also turn up in the resulting
3536      * adapter's signature and arguments, where they surround
3537      * {@code B}/{@code b}, which represent the parameter types and arguments
3538      * to the {@code filter} (if any).
3539      * <blockquote><pre>{@code
3540      * T target(A...,V,C...);
3541      * V filter(B...);
3542      * T adapter(A... a,B... b,C... c) {
3543      *   V v = filter(b...);
3544      *   return target(a...,v,c...);
3545      * }
3546      * // and if the filter has no arguments:
3547      * T target2(A...,V,C...);
3548      * V filter2();
3549      * T adapter2(A... a,C... c) {
3550      *   V v = filter2();
3551      *   return target2(a...,v,c...);
3552      * }
3553      * // and if the filter has a void return:
3554      * T target3(A...,C...);
3555      * void filter3(B...);
3556      * T adapter3(A... a,B... b,C... c) {
3557      *   filter3(b...);
3558      *   return target3(a...,c...);
3559      * }
3560      * }</pre></blockquote>
3561      * <p>
3562      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
3563      * one which first "folds" the affected arguments, and then drops them, in separate
3564      * steps as follows:
3565      * <blockquote><pre>{@code
3566      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
3567      * mh = MethodHandles.foldArguments(mh, coll); //step 1
3568      * }</pre></blockquote>
3569      * If the target method handle consumes no arguments besides than the result
3570      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
3571      * is equivalent to {@code filterReturnValue(coll, mh)}.
3572      * If the filter method handle {@code coll} consumes one argument and produces
3573      * a non-void result, then {@code collectArguments(mh, N, coll)}
3574      * is equivalent to {@code filterArguments(mh, N, coll)}.
3575      * Other equivalences are possible but would require argument permutation.
3576      * <p>
3577      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3578      * variable-arity method handle}, even if the original target method handle was.
3579      *
3580      * @param target the method handle to invoke after filtering the subsequence of arguments
3581      * @param pos the position of the first adapter argument to pass to the filter,
3582      *            and/or the target argument which receives the result of the filter
3583      * @param filter method handle to call on the subsequence of arguments
3584      * @return method handle which incorporates the specified argument subsequence filtering logic
3585      * @throws NullPointerException if either argument is null
3586      * @throws IllegalArgumentException if the return type of {@code filter}
3587      *          is non-void and is not the same as the {@code pos} argument of the target,
3588      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
3589      *          or if the resulting method handle's type would have
3590      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
3591      * @see MethodHandles#foldArguments
3592      * @see MethodHandles#filterArguments
3593      * @see MethodHandles#filterReturnValue
3594      */
3595     public static
3596     MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
3597         MethodType newType = collectArgumentsChecks(target, pos, filter);
3598         MethodType collectorType = filter.type();
3599         BoundMethodHandle result = target.rebind();
3600         LambdaForm lform;
3601         if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) {
3602             lform = result.editor().collectArgumentArrayForm(1 + pos, filter);
3603             if (lform != null) {
3604                 return result.copyWith(newType, lform);
3605             }
3606         }
3607         lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
3608         return result.copyWithExtendL(newType, lform, filter);
3609     }
3610 
3611     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
3612         MethodType targetType = target.type();
3613         MethodType filterType = filter.type();
3614         Class<?> rtype = filterType.returnType();
3615         List<Class<?>> filterArgs = filterType.parameterList();
3616         if (rtype == void.class) {
3617             return targetType.insertParameterTypes(pos, filterArgs);
3618         }
3619         if (rtype != targetType.parameterType(pos)) {
3620             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3621         }
3622         return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
3623     }
3624 
3625     /**
3626      * Adapts a target method handle by post-processing
3627      * its return value (if any) with a filter (another method handle).
3628      * The result of the filter is returned from the adapter.
3629      * <p>
3630      * If the target returns a value, the filter must accept that value as
3631      * its only argument.
3632      * If the target returns void, the filter must accept no arguments.
3633      * <p>
3634      * The return type of the filter
3635      * replaces the return type of the target
3636      * in the resulting adapted method handle.
3637      * The argument type of the filter (if any) must be identical to the
3638      * return type of the target.
3639      * <p><b>Example:</b>
3640      * <blockquote><pre>{@code
3641 import static java.lang.invoke.MethodHandles.*;
3642 import static java.lang.invoke.MethodType.*;
3643 ...
3644 MethodHandle cat = lookup().findVirtual(String.class,
3645   "concat", methodType(String.class, String.class));
3646 MethodHandle length = lookup().findVirtual(String.class,
3647   "length", methodType(int.class));
3648 System.out.println((String) cat.invokeExact("x", "y")); // xy
3649 MethodHandle f0 = filterReturnValue(cat, length);
3650 System.out.println((int) f0.invokeExact("x", "y")); // 2
3651      * }</pre></blockquote>
3652      * <p>Here is pseudocode for the resulting adapter. In the code,
3653      * {@code T}/{@code t} represent the result type and value of the
3654      * {@code target}; {@code V}, the result type of the {@code filter}; and
3655      * {@code A}/{@code a}, the types and values of the parameters and arguments
3656      * of the {@code target} as well as the resulting adapter.
3657      * <blockquote><pre>{@code
3658      * T target(A...);
3659      * V filter(T);
3660      * V adapter(A... a) {
3661      *   T t = target(a...);
3662      *   return filter(t);
3663      * }
3664      * // and if the target has a void return:
3665      * void target2(A...);
3666      * V filter2();
3667      * V adapter2(A... a) {
3668      *   target2(a...);
3669      *   return filter2();
3670      * }
3671      * // and if the filter has a void return:
3672      * T target3(A...);
3673      * void filter3(V);
3674      * void adapter3(A... a) {
3675      *   T t = target3(a...);
3676      *   filter3(t);
3677      * }
3678      * }</pre></blockquote>
3679      * <p>
3680      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3681      * variable-arity method handle}, even if the original target method handle was.
3682      * @param target the method handle to invoke before filtering the return value
3683      * @param filter method handle to call on the return value
3684      * @return method handle which incorporates the specified return value filtering logic
3685      * @throws NullPointerException if either argument is null
3686      * @throws IllegalArgumentException if the argument list of {@code filter}
3687      *          does not match the return type of target as described above
3688      */
3689     public static
3690     MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
3691         MethodType targetType = target.type();
3692         MethodType filterType = filter.type();
3693         filterReturnValueChecks(targetType, filterType);
3694         BoundMethodHandle result = target.rebind();
3695         BasicType rtype = BasicType.basicType(filterType.returnType());
3696         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
3697         MethodType newType = targetType.changeReturnType(filterType.returnType());
3698         result = result.copyWithExtendL(newType, lform, filter);
3699         return result;
3700     }
3701 
3702     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
3703         Class<?> rtype = targetType.returnType();
3704         int filterValues = filterType.parameterCount();
3705         if (filterValues == 0
3706                 ? (rtype != void.class)
3707                 : (rtype != filterType.parameterType(0)))
3708             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3709     }
3710 
3711     /**
3712      * Adapts a target method handle by pre-processing
3713      * some of its arguments, and then calling the target with
3714      * the result of the pre-processing, inserted into the original
3715      * sequence of arguments.
3716      * <p>
3717      * The pre-processing is performed by {@code combiner}, a second method handle.
3718      * Of the arguments passed to the adapter, the first {@code N} arguments
3719      * are copied to the combiner, which is then called.
3720      * (Here, {@code N} is defined as the parameter count of the combiner.)
3721      * After this, control passes to the target, with any result
3722      * from the combiner inserted before the original {@code N} incoming
3723      * arguments.
3724      * <p>
3725      * If the combiner returns a value, the first parameter type of the target
3726      * must be identical with the return type of the combiner, and the next
3727      * {@code N} parameter types of the target must exactly match the parameters
3728      * of the combiner.
3729      * <p>
3730      * If the combiner has a void return, no result will be inserted,
3731      * and the first {@code N} parameter types of the target
3732      * must exactly match the parameters of the combiner.
3733      * <p>
3734      * The resulting adapter is the same type as the target, except that the
3735      * first parameter type is dropped,
3736      * if it corresponds to the result of the combiner.
3737      * <p>
3738      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
3739      * that either the combiner or the target does not wish to receive.
3740      * If some of the incoming arguments are destined only for the combiner,
3741      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
3742      * arguments will not need to be live on the stack on entry to the
3743      * target.)
3744      * <p><b>Example:</b>
3745      * <blockquote><pre>{@code
3746 import static java.lang.invoke.MethodHandles.*;
3747 import static java.lang.invoke.MethodType.*;
3748 ...
3749 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
3750   "println", methodType(void.class, String.class))
3751     .bindTo(System.out);
3752 MethodHandle cat = lookup().findVirtual(String.class,
3753   "concat", methodType(String.class, String.class));
3754 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
3755 MethodHandle catTrace = foldArguments(cat, trace);
3756 // also prints "boo":
3757 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
3758      * }</pre></blockquote>
3759      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3760      * represents the result type of the {@code target} and resulting adapter.
3761      * {@code V}/{@code v} represent the type and value of the parameter and argument
3762      * of {@code target} that precedes the folding position; {@code V} also is
3763      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
3764      * types and values of the {@code N} parameters and arguments at the folding
3765      * position. {@code B}/{@code b} represent the types and values of the
3766      * {@code target} parameters and arguments that follow the folded parameters
3767      * and arguments.
3768      * <blockquote><pre>{@code
3769      * // there are N arguments in A...
3770      * T target(V, A[N]..., B...);
3771      * V combiner(A...);
3772      * T adapter(A... a, B... b) {
3773      *   V v = combiner(a...);
3774      *   return target(v, a..., b...);
3775      * }
3776      * // and if the combiner has a void return:
3777      * T target2(A[N]..., B...);
3778      * void combiner2(A...);
3779      * T adapter2(A... a, B... b) {
3780      *   combiner2(a...);
3781      *   return target2(a..., b...);
3782      * }
3783      * }</pre></blockquote>
3784      * <p>
3785      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3786      * variable-arity method handle}, even if the original target method handle was.
3787      * @param target the method handle to invoke after arguments are combined
3788      * @param combiner method handle to call initially on the incoming arguments
3789      * @return method handle which incorporates the specified argument folding logic
3790      * @throws NullPointerException if either argument is null
3791      * @throws IllegalArgumentException if {@code combiner}'s return type
3792      *          is non-void and not the same as the first argument type of
3793      *          the target, or if the initial {@code N} argument types
3794      *          of the target
3795      *          (skipping one matching the {@code combiner}'s return type)
3796      *          are not identical with the argument types of {@code combiner}
3797      */
3798     public static
3799     MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
3800         return foldArguments(target, 0, combiner);
3801     }
3802 
3803     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
3804         int foldArgs   = combinerType.parameterCount();
3805         Class<?> rtype = combinerType.returnType();
3806         int foldVals = rtype == void.class ? 0 : 1;
3807         int afterInsertPos = foldPos + foldVals;
3808         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
3809         if (ok && !(combinerType.parameterList()
3810                     .equals(targetType.parameterList().subList(afterInsertPos,
3811                                                                afterInsertPos + foldArgs))))
3812             ok = false;
3813         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
3814             ok = false;
3815         if (!ok)
3816             throw misMatchedTypes("target and combiner types", targetType, combinerType);
3817         return rtype;
3818     }
3819 
3820     /**
3821      * Makes a method handle which adapts a target method handle,
3822      * by guarding it with a test, a boolean-valued method handle.
3823      * If the guard fails, a fallback handle is called instead.
3824      * All three method handles must have the same corresponding
3825      * argument and return types, except that the return type
3826      * of the test must be boolean, and the test is allowed
3827      * to have fewer arguments than the other two method handles.
3828      * <p>
3829      * Here is pseudocode for the resulting adapter. In the code, {@code T}
3830      * represents the uniform result type of the three involved handles;
3831      * {@code A}/{@code a}, the types and values of the {@code target}
3832      * parameters and arguments that are consumed by the {@code test}; and
3833      * {@code B}/{@code b}, those types and values of the {@code target}
3834      * parameters and arguments that are not consumed by the {@code test}.
3835      * <blockquote><pre>{@code
3836      * boolean test(A...);
3837      * T target(A...,B...);
3838      * T fallback(A...,B...);
3839      * T adapter(A... a,B... b) {
3840      *   if (test(a...))
3841      *     return target(a..., b...);
3842      *   else
3843      *     return fallback(a..., b...);
3844      * }
3845      * }</pre></blockquote>
3846      * Note that the test arguments ({@code a...} in the pseudocode) cannot
3847      * be modified by execution of the test, and so are passed unchanged
3848      * from the caller to the target or fallback as appropriate.
3849      * @param test method handle used for test, must return boolean
3850      * @param target method handle to call if test passes
3851      * @param fallback method handle to call if test fails
3852      * @return method handle which incorporates the specified if/then/else logic
3853      * @throws NullPointerException if any argument is null
3854      * @throws IllegalArgumentException if {@code test} does not return boolean,
3855      *          or if all three method types do not match (with the return
3856      *          type of {@code test} changed to match that of the target).
3857      */
3858     public static
3859     MethodHandle guardWithTest(MethodHandle test,
3860                                MethodHandle target,
3861                                MethodHandle fallback) {
3862         MethodType gtype = test.type();
3863         MethodType ttype = target.type();
3864         MethodType ftype = fallback.type();
3865         if (!ttype.equals(ftype))
3866             throw misMatchedTypes("target and fallback types", ttype, ftype);
3867         if (gtype.returnType() != boolean.class)
3868             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
3869         List<Class<?>> targs = ttype.parameterList();
3870         test = dropArgumentsToMatch(test, 0, targs, 0, true);
3871         if (test == null) {
3872             throw misMatchedTypes("target and test types", ttype, gtype);
3873         }
3874         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
3875     }
3876 
3877     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
3878         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
3879     }
3880 
3881     /**
3882      * Makes a method handle which adapts a target method handle,
3883      * by running it inside an exception handler.
3884      * If the target returns normally, the adapter returns that value.
3885      * If an exception matching the specified type is thrown, the fallback
3886      * handle is called instead on the exception, plus the original arguments.
3887      * <p>
3888      * The target and handler must have the same corresponding
3889      * argument and return types, except that handler may omit trailing arguments
3890      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
3891      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
3892      * <p>
3893      * Here is pseudocode for the resulting adapter. In the code, {@code T}
3894      * represents the return type of the {@code target} and {@code handler},
3895      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
3896      * the types and values of arguments to the resulting handle consumed by
3897      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
3898      * resulting handle discarded by {@code handler}.
3899      * <blockquote><pre>{@code
3900      * T target(A..., B...);
3901      * T handler(ExType, A...);
3902      * T adapter(A... a, B... b) {
3903      *   try {
3904      *     return target(a..., b...);
3905      *   } catch (ExType ex) {
3906      *     return handler(ex, a...);
3907      *   }
3908      * }
3909      * }</pre></blockquote>
3910      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
3911      * be modified by execution of the target, and so are passed unchanged
3912      * from the caller to the handler, if the handler is invoked.
3913      * <p>
3914      * The target and handler must return the same type, even if the handler
3915      * always throws.  (This might happen, for instance, because the handler
3916      * is simulating a {@code finally} clause).
3917      * To create such a throwing handler, compose the handler creation logic
3918      * with {@link #throwException throwException},
3919      * in order to create a method handle of the correct return type.
3920      * @param target method handle to call
3921      * @param exType the type of exception which the handler will catch
3922      * @param handler method handle to call if a matching exception is thrown
3923      * @return method handle which incorporates the specified try/catch logic
3924      * @throws NullPointerException if any argument is null
3925      * @throws IllegalArgumentException if {@code handler} does not accept
3926      *          the given exception type, or if the method handle types do
3927      *          not match in their return types and their
3928      *          corresponding parameters
3929      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
3930      */
3931     public static
3932     MethodHandle catchException(MethodHandle target,
3933                                 Class<? extends Throwable> exType,
3934                                 MethodHandle handler) {
3935         MethodType ttype = target.type();
3936         MethodType htype = handler.type();
3937         if (!Throwable.class.isAssignableFrom(exType))
3938             throw new ClassCastException(exType.getName());
3939         if (htype.parameterCount() < 1 ||
3940             !htype.parameterType(0).isAssignableFrom(exType))
3941             throw newIllegalArgumentException("handler does not accept exception type "+exType);
3942         if (htype.returnType() != ttype.returnType())
3943             throw misMatchedTypes("target and handler return types", ttype, htype);
3944         handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
3945         if (handler == null) {
3946             throw misMatchedTypes("target and handler types", ttype, htype);
3947         }
3948         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
3949     }
3950 
3951     /**
3952      * Produces a method handle which will throw exceptions of the given {@code exType}.
3953      * The method handle will accept a single argument of {@code exType},
3954      * and immediately throw it as an exception.
3955      * The method type will nominally specify a return of {@code returnType}.
3956      * The return type may be anything convenient:  It doesn't matter to the
3957      * method handle's behavior, since it will never return normally.
3958      * @param returnType the return type of the desired method handle
3959      * @param exType the parameter type of the desired method handle
3960      * @return method handle which can throw the given exceptions
3961      * @throws NullPointerException if either argument is null
3962      */
3963     public static
3964     MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
3965         if (!Throwable.class.isAssignableFrom(exType))
3966             throw new ClassCastException(exType.getName());
3967         return MethodHandleImpl.throwException(methodType(returnType, exType));
3968     }
3969 
3970     /**
3971      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
3972      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
3973      * delivers the loop's result, which is the return value of the resulting handle.
3974      * <p>
3975      * Intuitively, every loop is formed by one or more "clauses", each specifying a local iteration value and/or a loop
3976      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
3977      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
3978      * terms of method handles, each clause will determine four actions:<ul>
3979      * <li>Before the loop executes, the initialization of an iteration variable or loop invariant local.
3980      * <li>When a clause executes, an update step for the iteration variable.
3981      * <li>When a clause executes, a predicate execution to test for loop exit.
3982      * <li>If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
3983      * </ul>
3984      * <p>
3985      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
3986      * this case. See below for a detailed description.
3987      * <p>
3988      * Each clause function, with the exception of clause initializers, is able to observe the entire loop state,
3989      * because it will be passed <em>all</em> current iteration variable values, as well as all incoming loop
3990      * parameters. Most clause functions will not need all of this information, but they will be formally connected as
3991      * if by {@link #dropArguments}.
3992      * <p>
3993      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
3994      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
3995      * corresponds to a place where {@link IllegalArgumentException} may be thrown if the required constraint is not met
3996      * by the inputs to the loop combinator. The term "effectively identical", applied to parameter type lists, means
3997      * that they must be identical, or else one list must be a proper prefix of the other.
3998      * <p>
3999      * <em>Step 0: Determine clause structure.</em><ol type="a">
4000      * <li>The clause array (of type {@code MethodHandle[][]} must be non-{@code null} and contain at least one element.
4001      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
4002      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
4003      * four. Padding takes place by appending elements to the array.
4004      * <li>Clauses with all {@code null}s are disregarded.
4005      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
4006      * </ol>
4007      * <p>
4008      * <em>Step 1A: Determine iteration variables.</em><ol type="a">
4009      * <li>Examine init and step function return types, pairwise, to determine each clause's iteration variable type.
4010      * <li>If both functions are omitted, use {@code void}; else if one is omitted, use the other's return type; else
4011      * use the common return type (they must be identical).
4012      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
4013      * <li>This list of types is called the "common prefix".
4014      * </ol>
4015      * <p>
4016      * <em>Step 1B: Determine loop parameters.</em><ul>
4017      * <li><b>If at least one init function is given,</b><ol type="a">
4018      *   <li>Examine init function parameter lists.
4019      *   <li>Omitted init functions are deemed to have {@code null} parameter lists.
4020      *   <li>All init function parameter lists must be effectively identical.
4021      *   <li>The longest parameter list (which is necessarily unique) is called the "common suffix".
4022      * </ol>
4023      * <li><b>If no init function is given,</b><ol type="a">
4024      *   <li>Examine the suffixes of the step, pred, and fini parameter lists, after removing the "common prefix".
4025      *   <li>The longest of these suffixes is taken as the "common suffix".
4026      * </ol></ul>
4027      * <p>
4028      * <em>Step 1C: Determine loop return type.</em><ol type="a">
4029      * <li>Examine fini function return types, disregarding omitted fini functions.
4030      * <li>If there are no fini functions, use {@code void} as the loop return type.
4031      * <li>Otherwise, use the common return type of the fini functions; they must all be identical.
4032      * </ol>
4033      * <p>
4034      * <em>Step 1D: Check other types.</em><ol type="a">
4035      * <li>There must be at least one non-omitted pred function.
4036      * <li>Every non-omitted pred function must have a {@code boolean} return type.
4037      * </ol>
4038      * <p>
4039      * <em>Step 2: Determine parameter lists.</em><ol type="a">
4040      * <li>The parameter list for the resulting loop handle will be the "common suffix".
4041      * <li>The parameter list for init functions will be adjusted to the "common suffix". (Note that their parameter
4042      * lists are already effectively identical to the common suffix.)
4043      * <li>The parameter list for non-init (step, pred, and fini) functions will be adjusted to the common prefix
4044      * followed by the common suffix, called the "common parameter sequence".
4045      * <li>Every non-init, non-omitted function parameter list must be effectively identical to the common parameter
4046      * sequence.
4047      * </ol>
4048      * <p>
4049      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
4050      * <li>If an init function is omitted, use a {@linkplain #constant constant function} of the appropriate
4051      * {@code null}/zero/{@code false}/{@code void} type. (For this purpose, a constant {@code void} is simply a
4052      * function which does nothing and returns {@code void}; it can be obtained from another constant function by
4053      * {@linkplain MethodHandle#asType type conversion}.)
4054      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
4055      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
4056      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
4057      * <li>If a pred function is omitted, the corresponding fini function must also be omitted.
4058      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
4059      * as this clause is concerned.)
4060      * <li>If a fini function is omitted, use a constant {@code null}/zero/{@code false}/{@code void} function of the
4061      * loop return type.
4062      * </ol>
4063      * <p>
4064      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
4065      * <li>At this point, every init function parameter list is effectively identical to the common suffix, but some
4066      * lists may be shorter. For every init function with a short parameter list, pad out the end of the list by
4067      * {@linkplain #dropArguments dropping arguments}.
4068      * <li>At this point, every non-init function parameter list is effectively identical to the common parameter
4069      * sequence, but some lists may be shorter. For every non-init function with a short parameter list, pad out the end
4070      * of the list by {@linkplain #dropArguments dropping arguments}.
4071      * </ol>
4072      * <p>
4073      * <em>Final observations.</em><ol type="a">
4074      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
4075      * <li>All init functions have a common parameter type list, which the final loop handle will also have.
4076      * <li>All fini functions have a common return type, which the final loop handle will also have.
4077      * <li>All non-init functions have a common parameter type list, which is the common parameter sequence, of
4078      * (non-{@code void}) iteration variables followed by loop parameters.
4079      * <li>Each pair of init and step functions agrees in their return types.
4080      * <li>Each non-init function will be able to observe the current values of all iteration variables, by means of the
4081      * common prefix.
4082      * </ol>
4083      * <p>
4084      * <em>Loop execution.</em><ol type="a">
4085      * <li>When the loop is called, the loop input values are saved in locals, to be passed (as the common suffix) to
4086      * every clause function. These locals are loop invariant.
4087      * <li>Each init function is executed in clause order (passing the common suffix) and the non-{@code void} values
4088      * are saved (as the common prefix) into locals. These locals are loop varying (unless their steps are identity
4089      * functions, as noted above).
4090      * <li>All function executions (except init functions) will be passed the common parameter sequence, consisting of
4091      * the non-{@code void} iteration values (in clause order) and then the loop inputs (in argument order).
4092      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
4093      * returns {@code false}.
4094      * <li>The non-{@code void} result from a step function call is used to update the corresponding loop variable. The
4095      * updated value is immediately visible to all subsequent function calls.
4096      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
4097      * is returned from the loop as a whole.
4098      * </ol>
4099      * <p>
4100      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the types / values
4101      * of loop variables; {@code A}/{@code a}, those of arguments passed to the resulting loop; and {@code R}, the
4102      * result types of finalizers as well as of the resulting loop.
4103      * <blockquote><pre>{@code
4104      * V... init...(A...);
4105      * boolean pred...(V..., A...);
4106      * V... step...(V..., A...);
4107      * R fini...(V..., A...);
4108      * R loop(A... a) {
4109      *   V... v... = init...(a...);
4110      *   for (;;) {
4111      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
4112      *       v = s(v..., a...);
4113      *       if (!p(v..., a...)) {
4114      *         return f(v..., a...);
4115      *       }
4116      *     }
4117      *   }
4118      * }
4119      * }</pre></blockquote>
4120      * <p>
4121      * @apiNote Example:
4122      * <blockquote><pre>{@code
4123      * // iterative implementation of the factorial function as a loop handle
4124      * static int one(int k) { return 1; }
4125      * static int inc(int i, int acc, int k) { return i + 1; }
4126      * static int mult(int i, int acc, int k) { return i * acc; }
4127      * static boolean pred(int i, int acc, int k) { return i < k; }
4128      * static int fin(int i, int acc, int k) { return acc; }
4129      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
4130      * // null initializer for counter, should initialize to 0
4131      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
4132      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
4133      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
4134      * assertEquals(120, loop.invoke(5));
4135      * }</pre></blockquote>
4136      *
4137      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
4138      *
4139      * @return a method handle embodying the looping behavior as defined by the arguments.
4140      *
4141      * @throws IllegalArgumentException in case any of the constraints described above is violated.
4142      *
4143      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
4144      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
4145      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
4146      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
4147      * @since 9
4148      */
4149     public static MethodHandle loop(MethodHandle[]... clauses) {
4150         // Step 0: determine clause structure.
4151         checkLoop0(clauses);
4152 
4153         List<MethodHandle> init = new ArrayList<>();
4154         List<MethodHandle> step = new ArrayList<>();
4155         List<MethodHandle> pred = new ArrayList<>();
4156         List<MethodHandle> fini = new ArrayList<>();
4157 
4158         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
4159             init.add(clause[0]); // all clauses have at least length 1
4160             step.add(clause.length <= 1 ? null : clause[1]);
4161             pred.add(clause.length <= 2 ? null : clause[2]);
4162             fini.add(clause.length <= 3 ? null : clause[3]);
4163         });
4164 
4165         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
4166         final int nclauses = init.size();
4167 
4168         // Step 1A: determine iteration variables.
4169         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
4170         for (int i = 0; i < nclauses; ++i) {
4171             MethodHandle in = init.get(i);
4172             MethodHandle st = step.get(i);
4173             if (in == null && st == null) {
4174                 iterationVariableTypes.add(void.class);
4175             } else if (in != null && st != null) {
4176                 checkLoop1a(i, in, st);
4177                 iterationVariableTypes.add(in.type().returnType());
4178             } else {
4179                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
4180             }
4181         }
4182         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).
4183                 collect(Collectors.toList());
4184 
4185         // Step 1B: determine loop parameters.
4186         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
4187         checkLoop1b(init, commonSuffix);
4188 
4189         // Step 1C: determine loop return type.
4190         // Step 1D: check other types.
4191         final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type).
4192                 map(MethodType::returnType).findFirst().orElse(void.class);
4193         checkLoop1cd(pred, fini, loopReturnType);
4194 
4195         // Step 2: determine parameter lists.
4196         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
4197         commonParameterSequence.addAll(commonSuffix);
4198         checkLoop2(step, pred, fini, commonParameterSequence);
4199 
4200         // Step 3: fill in omitted functions.
4201         for (int i = 0; i < nclauses; ++i) {
4202             Class<?> t = iterationVariableTypes.get(i);
4203             if (init.get(i) == null) {
4204                 init.set(i, empty(methodType(t, commonSuffix)));
4205             }
4206             if (step.get(i) == null) {
4207                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
4208             }
4209             if (pred.get(i) == null) {
4210                 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
4211             }
4212             if (fini.get(i) == null) {
4213                 fini.set(i, empty(methodType(t, commonParameterSequence)));
4214             }
4215         }
4216 
4217         // Step 4: fill in missing parameter types.
4218         List<MethodHandle> finit = fillParameterTypes(init, commonSuffix);
4219         List<MethodHandle> fstep = fillParameterTypes(step, commonParameterSequence);
4220         List<MethodHandle> fpred = fillParameterTypes(pred, commonParameterSequence);
4221         List<MethodHandle> ffini = fillParameterTypes(fini, commonParameterSequence);
4222 
4223         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
4224                 allMatch(pl -> pl.equals(commonSuffix));
4225         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
4226                 allMatch(pl -> pl.equals(commonParameterSequence));
4227 
4228         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, commonPrefix, finit, fstep, fpred, ffini);
4229     }
4230 
4231     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
4232         return hs.stream().map(h -> {
4233             int pc = h.type().parameterCount();
4234             int tpsize = targetParams.size();
4235             return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
4236         }).collect(Collectors.toList());
4237     }
4238 
4239     /**
4240      * Constructs a {@code while} loop from an initializer, a body, and a predicate. This is a convenience wrapper for
4241      * the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
4242      * <p>
4243      * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}.
4244      * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle
4245      * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code
4246      * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][])
4247      * generic loop combinator}.
4248      * <p>
4249      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4250      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4251      * passed to the loop.
4252      * <blockquote><pre>{@code
4253      * V init(A);
4254      * boolean pred(V, A);
4255      * V body(V, A);
4256      * V whileLoop(A a) {
4257      *   V v = init(a);
4258      *   while (pred(v, a)) {
4259      *     v = body(v, a);
4260      *   }
4261      *   return v;
4262      * }
4263      * }</pre></blockquote>
4264      * <p>
4265      * @apiNote Example:
4266      * <blockquote><pre>{@code
4267      * // implement the zip function for lists as a loop handle
4268      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
4269      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
4270      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
4271      *   zip.add(a.next());
4272      *   zip.add(b.next());
4273      *   return zip;
4274      * }
4275      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
4276      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
4277      * List<String> a = Arrays.asList("a", "b", "c", "d");
4278      * List<String> b = Arrays.asList("e", "f", "g", "h");
4279      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
4280      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
4281      * }</pre></blockquote>
4282      *
4283      * <p>
4284      * @implSpec The implementation of this method is equivalent to:
4285      * <blockquote><pre>{@code
4286      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
4287      *     MethodHandle[]
4288      *         checkExit = {null, null, pred, identity(init.type().returnType())},
4289      *         varBody = {init, body};
4290      *     return loop(checkExit, varBody);
4291      * }
4292      * }</pre></blockquote>
4293      *
4294      * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's
4295      *             result type. Passing {@code null} or a {@code void} init function will make the loop's result type
4296      *             {@code void}.
4297      * @param pred condition for the loop, which may not be {@code null}.
4298      * @param body body of the loop, which may not be {@code null}.
4299      *
4300      * @return the value of the loop variable as the loop terminates.
4301      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4302      *
4303      * @see MethodHandles#loop(MethodHandle[][])
4304      * @since 9
4305      */
4306     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
4307         MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) :
4308                 identity(init.type().returnType());
4309         MethodHandle[] checkExit = {null, null, pred, fin};
4310         MethodHandle[] varBody = {init, body};
4311         return loop(checkExit, varBody);
4312     }
4313 
4314     /**
4315      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. This is a convenience wrapper
4316      * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
4317      * <p>
4318      * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}.
4319      * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle
4320      * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code
4321      * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][])
4322      * generic loop combinator}.
4323      * <p>
4324      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4325      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4326      * passed to the loop.
4327      * <blockquote><pre>{@code
4328      * V init(A);
4329      * boolean pred(V, A);
4330      * V body(V, A);
4331      * V doWhileLoop(A a) {
4332      *   V v = init(a);
4333      *   do {
4334      *     v = body(v, a);
4335      *   } while (pred(v, a));
4336      *   return v;
4337      * }
4338      * }</pre></blockquote>
4339      * <p>
4340      * @apiNote Example:
4341      * <blockquote><pre>{@code
4342      * // int i = 0; while (i < limit) { ++i; } return i; => limit
4343      * static int zero(int limit) { return 0; }
4344      * static int step(int i, int limit) { return i + 1; }
4345      * static boolean pred(int i, int limit) { return i < limit; }
4346      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
4347      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
4348      * assertEquals(23, loop.invoke(23));
4349      * }</pre></blockquote>
4350      *
4351      * <p>
4352      * @implSpec The implementation of this method is equivalent to:
4353      * <blockquote><pre>{@code
4354      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
4355      *     MethodHandle[] clause = { init, body, pred, identity(init.type().returnType()) };
4356      *     return loop(clause);
4357      * }
4358      * }</pre></blockquote>
4359      *
4360      *
4361      * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's
4362      *             result type. Passing {@code null} or a {@code void} init function will make the loop's result type
4363      *             {@code void}.
4364      * @param pred condition for the loop, which may not be {@code null}.
4365      * @param body body of the loop, which may not be {@code null}.
4366      *
4367      * @return the value of the loop variable as the loop terminates.
4368      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4369      *
4370      * @see MethodHandles#loop(MethodHandle[][])
4371      * @since 9
4372      */
4373     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
4374         MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) :
4375                 identity(init.type().returnType());
4376         MethodHandle[] clause = {init, body, pred, fin};
4377         return loop(clause);
4378     }
4379 
4380     /**
4381      * Constructs a loop that runs a given number of iterations. The loop counter is an {@code int} initialized from the
4382      * {@code iterations} handle evaluation result. The counter is passed to the {@code body} function, so that must
4383      * accept an initial {@code int} argument. The result of the loop execution is the final value of the additional
4384      * local state. This is a convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop
4385      * combinator}.
4386      * <p>
4387      * The result type and parameter type list of {@code init} determine those of the resulting handle. The {@code
4388      * iterations} handle must accept the same parameter types as {@code init} but return an {@code int}. The {@code
4389      * body} handle must accept the same parameter types as well, preceded by an {@code int} parameter for the counter,
4390      * and a parameter of the same type as {@code init}'s result. These constraints follow directly from those described
4391      * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
4392      * <p>
4393      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4394      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4395      * passed to the loop.
4396      * <blockquote><pre>{@code
4397      * int iterations(A);
4398      * V init(A);
4399      * V body(int, V, A);
4400      * V countedLoop(A a) {
4401      *   int end = iterations(a);
4402      *   V v = init(a);
4403      *   for (int i = 0; i < end; ++i) {
4404      *     v = body(i, v, a);
4405      *   }
4406      *   return v;
4407      * }
4408      * }</pre></blockquote>
4409      * <p>
4410      * @apiNote Example:
4411      * <blockquote><pre>{@code
4412      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
4413      * // => a variation on a well known theme
4414      * static String start(String arg) { return arg; }
4415      * static String step(int counter, String v, String arg) { return "na " + v; }
4416      * // assume MH_start and MH_step are handles to the two methods above
4417      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
4418      * MethodHandle loop = MethodHandles.countedLoop(fit13, MH_start, MH_step);
4419      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
4420      * }</pre></blockquote>
4421      *
4422      * <p>
4423      * @implSpec The implementation of this method is equivalent to:
4424      * <blockquote><pre>{@code
4425      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
4426      *     return countedLoop(null, iterations, init, body);  // null => constant zero
4427      * }
4428      * }</pre></blockquote>
4429      *
4430      * @param iterations a handle to return the number of iterations this loop should run.
4431      * @param init initializer for additional loop state. This determines the loop's result type.
4432      *             Passing {@code null} or a {@code void} init function will make the loop's result type
4433      *             {@code void}.
4434      * @param body the body of the loop, which must not be {@code null}.
4435      *             It must accept an initial {@code int} parameter (for the counter), and then any
4436      *             additional loop-local variable plus loop parameters.
4437      *
4438      * @return a method handle representing the loop.
4439      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4440      *
4441      * @since 9
4442      */
4443     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
4444         return countedLoop(null, iterations, init, body);
4445     }
4446 
4447     /**
4448      * Constructs a loop that counts over a range of numbers. The loop counter is an {@code int} that will be
4449      * initialized to the {@code int} value returned from the evaluation of the {@code start} handle and run to the
4450      * value returned from {@code end} (exclusively) with a step width of 1. The counter value is passed to the {@code
4451      * body} function in each iteration; it has to accept an initial {@code int} parameter
4452      * for that. The result of the loop execution is the final value of the additional local state
4453      * obtained by running {@code init}.
4454      * This is a
4455      * convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
4456      * <p>
4457      * The constraints for the {@code init} and {@code body} handles are the same as for {@link
4458      * #countedLoop(MethodHandle, MethodHandle, MethodHandle)}. Additionally, the {@code start} and {@code end} handles
4459      * must return an {@code int} and accept the same parameters as {@code init}.
4460      * <p>
4461      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4462      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4463      * passed to the loop.
4464      * <blockquote><pre>{@code
4465      * int start(A);
4466      * int end(A);
4467      * V init(A);
4468      * V body(int, V, A);
4469      * V countedLoop(A a) {
4470      *   int s = start(a);
4471      *   int e = end(a);
4472      *   V v = init(a);
4473      *   for (int i = s; i < e; ++i) {
4474      *     v = body(i, v, a);
4475      *   }
4476      *   return v;
4477      * }
4478      * }</pre></blockquote>
4479      *
4480      * <p>
4481      * @implSpec The implementation of this method is equivalent to:
4482      * <blockquote><pre>{@code
4483      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
4484      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
4485      *     // assume MH_increment and MH_lessThan are handles to x+1 and x<y of type int,
4486      *     // assume MH_decrement is a handle to x-1 of type int
4487      *     MethodHandle[]
4488      *         indexVar = {start, MH_increment}, // i = start; i = i+1
4489      *         loopLimit = {end, null, MH_lessThan, returnVar }, // i<end
4490      *         bodyClause = {init,
4491      *                       filterArgument(dropArguments(body, 1, int.class), 0, MH_decrement}; // v = body(i-1, v)
4492      *     return loop(indexVar, loopLimit, bodyClause);
4493      * }
4494      * }</pre></blockquote>
4495      *
4496      * @param start a handle to return the start value of the loop counter.
4497      *              If it is {@code null}, a constant zero is assumed.
4498      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to {@code end-1}).
4499      * @param init initializer for additional loop state. This determines the loop's result type.
4500      *             Passing {@code null} or a {@code void} init function will make the loop's result type
4501      *             {@code void}.
4502      * @param body the body of the loop, which must not be {@code null}.
4503      *             It must accept an initial {@code int} parameter (for the counter), and then any
4504      *             additional loop-local variable plus loop parameters.
4505      *
4506      * @return a method handle representing the loop.
4507      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4508      *
4509      * @since 9
4510      */
4511     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
4512         Class<?> resultType;
4513         MethodHandle actualInit;
4514         if (init == null) {
4515             resultType = body == null ? void.class : body.type().returnType();
4516             actualInit = empty(methodType(resultType));
4517         } else {
4518             resultType = init.type().returnType();
4519             actualInit = init;
4520         }
4521         MethodHandle defaultResultHandle = resultType == void.class ? zero(void.class) : identity(resultType);
4522         MethodHandle actualBody = body == null ? dropArguments(defaultResultHandle, 0, int.class) : body;
4523         MethodHandle returnVar = dropArguments(defaultResultHandle, 0, int.class, int.class);
4524         MethodHandle actualEnd = end == null ? constant(int.class, 0) : end;
4525         MethodHandle[] indexVar = {start, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep)};
4526         MethodHandle[] loopLimit = {actualEnd, null,
4527                 MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred), returnVar};
4528         MethodHandle[] bodyClause = {actualInit,
4529                 filterArgument(dropArguments(actualBody, 1, int.class), 0,
4530                         MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_decrementCounter))};
4531         return loop(indexVar, loopLimit, bodyClause);
4532     }
4533 
4534     /**
4535      * Constructs a loop that ranges over the elements produced by an {@code Iterator<T>}.
4536      * The iterator will be produced by the evaluation of the {@code iterator} handle.
4537      * This handle must have {@link java.util.Iterator} as its return type.
4538      * If this handle is passed as {@code null} the method {@link Iterable#iterator} will be used instead,
4539      * and will be applied to a leading argument of the loop handle.
4540      * Each value produced by the iterator is passed to the {@code body}, which must accept an initial {@code T} parameter.
4541      * The result of the loop execution is the final value of the additional local state
4542      * obtained by running {@code init}.
4543      * <p>
4544      * This is a convenience wrapper for the
4545      * {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}, and the constraints imposed on the {@code body}
4546      * handle follow directly from those described for the latter.
4547      * <p>
4548      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4549      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
4550      * structure the loop iterates over, and {@code A}/{@code a}, that of the argument passed to the loop.
4551      * <blockquote><pre>{@code
4552      * Iterator<T> iterator(A);  // defaults to Iterable::iterator
4553      * V init(A);
4554      * V body(T,V,A);
4555      * V iteratedLoop(A a) {
4556      *   Iterator<T> it = iterator(a);
4557      *   V v = init(a);
4558      *   for (T t : it) {
4559      *     v = body(t, v, a);
4560      *   }
4561      *   return v;
4562      * }
4563      * }</pre></blockquote>
4564      * <p>
4565      * The type {@code T} may be either a primitive or reference.
4566      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type
4567      * {@code Iterator}, the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body}
4568      * to {@code Object} as if by the {@link MethodHandle#asType asType} conversion method.
4569      * Therefore, if an iterator of the wrong type appears as the loop is executed,
4570      * runtime exceptions may occur as the result of dynamic conversions performed by {@code asType}.
4571      * <p>
4572      * @apiNote Example:
4573      * <blockquote><pre>{@code
4574      * // reverse a list
4575      * static List<String> reverseStep(String e, List<String> r, List<String> l) {
4576      *   r.add(0, e);
4577      *   return r;
4578      * }
4579      * static List<String> newArrayList(List<String> l) { return new ArrayList<>(); }
4580      * // assume MH_reverseStep, MH_newArrayList are handles to the above methods
4581      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
4582      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
4583      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
4584      * assertEquals(reversedList, (List<String>) loop.invoke(list));
4585      * }</pre></blockquote>
4586      * <p>
4587      * @implSpec The implementation of this method is equivalent to (excluding error handling):
4588      * <blockquote><pre>{@code
4589      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
4590      *     // assume MH_next and MH_hasNext are handles to methods of Iterator
4591      *     Class<?> itype = iterator.type().returnType();
4592      *     Class<?> ttype = body.type().parameterType(0);
4593      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, itype);
4594      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
4595      *     MethodHandle[]
4596      *         iterVar = {iterator, null, MH_hasNext, returnVar}, // it = iterator(); while (it.hasNext)
4597      *         bodyClause = {init, filterArgument(body, 0, nextVal)};  // v = body(t, v, a);
4598      *     return loop(iterVar, bodyClause);
4599      * }
4600      * }</pre></blockquote>
4601      *
4602      * @param iterator a handle to return the iterator to start the loop.
4603      *             The handle must have {@link java.util.Iterator} as its return type.
4604      *             Passing {@code null} will make the loop call {@link Iterable#iterator()} on the first
4605      *             incoming value.
4606      * @param init initializer for additional loop state. This determines the loop's result type.
4607      *             Passing {@code null} or a {@code void} init function will make the loop's result type
4608      *             {@code void}.
4609      * @param body the body of the loop, which must not be {@code null}.
4610      *             It must accept an initial {@code T} parameter (for the iterated values), and then any
4611      *             additional loop-local variable plus loop parameters.
4612      *
4613      * @return a method handle embodying the iteration loop functionality.
4614      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4615      *
4616      * @since 9
4617      */
4618     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
4619         checkIteratedLoop(iterator, body);
4620         Class<?> resultType = init == null ?
4621                 body == null ? void.class : body.type().returnType() :
4622                 init.type().returnType();
4623         boolean voidResult = resultType == void.class;
4624 
4625         MethodHandle initIterator;
4626         if (iterator == null) {
4627             MethodHandle initit = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
4628             initIterator = initit.asType(initit.type().changeParameterType(0,
4629                     body.type().parameterType(voidResult ? 1 : 2)));
4630         } else {
4631             initIterator = iterator.asType(iterator.type().changeReturnType(Iterator.class));
4632         }
4633 
4634         Class<?> ttype = body.type().parameterType(0);
4635 
4636         MethodHandle returnVar =
4637                 dropArguments(voidResult ? zero(void.class) : identity(resultType), 0, Iterator.class);
4638         MethodHandle initnx = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
4639         MethodHandle nextVal = initnx.asType(initnx.type().changeReturnType(ttype));
4640 
4641         MethodHandle[] iterVar = {initIterator, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred),
4642                 returnVar};
4643         MethodHandle[] bodyClause = {init, filterArgument(body, 0, nextVal)};
4644 
4645         return loop(iterVar, bodyClause);
4646     }
4647 
4648     /**
4649      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
4650      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
4651      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
4652      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
4653      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
4654      * {@code try-finally} handle.
4655      * <p>
4656      * The {@code cleanup} handle will be passed one or two additional leading arguments.
4657      * The first is the exception thrown during the
4658      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
4659      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
4660      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
4661      * The second argument is not present if the {@code target} handle has a {@code void} return type.
4662      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
4663      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
4664      * <p>
4665      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
4666      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
4667      * two extra leading parameters:<ul>
4668      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
4669      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
4670      * the result from the execution of the {@code target} handle.
4671      * This parameter is not present if the {@code target} returns {@code void}.
4672      * </ul>
4673      * <p>
4674      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
4675      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
4676      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
4677      * the cleanup.
4678      * <blockquote><pre>{@code
4679      * V target(A..., B...);
4680      * V cleanup(Throwable, V, A...);
4681      * V adapter(A... a, B... b) {
4682      *   V result = (zero value for V);
4683      *   Throwable throwable = null;
4684      *   try {
4685      *     result = target(a..., b...);
4686      *   } catch (Throwable t) {
4687      *     throwable = t;
4688      *     throw t;
4689      *   } finally {
4690      *     result = cleanup(throwable, result, a...);
4691      *   }
4692      *   return result;
4693      * }
4694      * }</pre></blockquote>
4695      * <p>
4696      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
4697      * be modified by execution of the target, and so are passed unchanged
4698      * from the caller to the cleanup, if it is invoked.
4699      * <p>
4700      * The target and cleanup must return the same type, even if the cleanup
4701      * always throws.
4702      * To create such a throwing cleanup, compose the cleanup logic
4703      * with {@link #throwException throwException},
4704      * in order to create a method handle of the correct return type.
4705      * <p>
4706      * Note that {@code tryFinally} never converts exceptions into normal returns.
4707      * In rare cases where exceptions must be converted in that way, first wrap
4708      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
4709      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
4710      *
4711      * @param target the handle whose execution is to be wrapped in a {@code try} block.
4712      * @param cleanup the handle that is invoked in the finally block.
4713      *
4714      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
4715      * @throws NullPointerException if any argument is null
4716      * @throws IllegalArgumentException if {@code cleanup} does not accept
4717      *          the required leading arguments, or if the method handle types do
4718      *          not match in their return types and their
4719      *          corresponding trailing parameters
4720      *
4721      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
4722      * @since 9
4723      */
4724     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
4725         List<Class<?>> targetParamTypes = target.type().parameterList();
4726         List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
4727         Class<?> rtype = target.type().returnType();
4728 
4729         checkTryFinally(target, cleanup);
4730 
4731         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
4732         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
4733         // target parameter list.
4734         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
4735         MethodHandle aTarget = target.asSpreader(Object[].class, target.type().parameterCount());
4736         MethodHandle aCleanup = cleanup.asSpreader(Object[].class, targetParamTypes.size());
4737 
4738         return MethodHandleImpl.makeTryFinally(aTarget, aCleanup, rtype, targetParamTypes);
4739     }
4740 
4741     /**
4742      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
4743      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
4744      * before the folded arguments.
4745      * <p>
4746      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
4747      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
4748      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
4749      * 0.
4750      * <p>
4751      * @apiNote Example:
4752      * <blockquote><pre>{@code
4753     import static java.lang.invoke.MethodHandles.*;
4754     import static java.lang.invoke.MethodType.*;
4755     ...
4756     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
4757     "println", methodType(void.class, String.class))
4758     .bindTo(System.out);
4759     MethodHandle cat = lookup().findVirtual(String.class,
4760     "concat", methodType(String.class, String.class));
4761     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
4762     MethodHandle catTrace = foldArguments(cat, 1, trace);
4763     // also prints "jum":
4764     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
4765      * }</pre></blockquote>
4766      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
4767      * represents the result type of the {@code target} and resulting adapter.
4768      * {@code V}/{@code v} represent the type and value of the parameter and argument
4769      * of {@code target} that precedes the folding position; {@code V} also is
4770      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
4771      * types and values of the {@code N} parameters and arguments at the folding
4772      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
4773      * and values of the {@code target} parameters and arguments that precede and
4774      * follow the folded parameters and arguments starting at {@code pos},
4775      * respectively.
4776      * <blockquote><pre>{@code
4777      * // there are N arguments in A...
4778      * T target(Z..., V, A[N]..., B...);
4779      * V combiner(A...);
4780      * T adapter(Z... z, A... a, B... b) {
4781      *   V v = combiner(a...);
4782      *   return target(z..., v, a..., b...);
4783      * }
4784      * // and if the combiner has a void return:
4785      * T target2(Z..., A[N]..., B...);
4786      * void combiner2(A...);
4787      * T adapter2(Z... z, A... a, B... b) {
4788      *   combiner2(a...);
4789      *   return target2(z..., a..., b...);
4790      * }
4791      * }</pre></blockquote>
4792      * <p>
4793      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4794      * variable-arity method handle}, even if the original target method handle was.
4795      *
4796      * @param target the method handle to invoke after arguments are combined
4797      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
4798      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
4799      * @param combiner method handle to call initially on the incoming arguments
4800      * @return method handle which incorporates the specified argument folding logic
4801      * @throws NullPointerException if either argument is null
4802      * @throws IllegalArgumentException if {@code combiner}'s return type
4803      *          is non-void and not the same as the argument type at position {@code pos} of
4804      *          the target signature, or if the {@code N} argument types at position {@code pos}
4805      *          of the target signature
4806      *          (skipping one matching the {@code combiner}'s return type)
4807      *          are not identical with the argument types of {@code combiner}
4808      *
4809      * @see #foldArguments(MethodHandle, MethodHandle)
4810      * @since 9
4811      */
4812     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
4813         MethodType targetType = target.type();
4814         MethodType combinerType = combiner.type();
4815         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
4816         BoundMethodHandle result = target.rebind();
4817         boolean dropResult = rtype == void.class;
4818         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
4819         MethodType newType = targetType;
4820         if (!dropResult) {
4821             newType = newType.dropParameterTypes(pos, pos + 1);
4822         }
4823         result = result.copyWithExtendL(newType, lform, combiner);
4824         return result;
4825     }
4826 
4827 
4828     private static void checkLoop0(MethodHandle[][] clauses) {
4829         if (clauses == null || clauses.length == 0) {
4830             throw newIllegalArgumentException("null or no clauses passed");
4831         }
4832         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
4833             throw newIllegalArgumentException("null clauses are not allowed");
4834         }
4835         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
4836             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
4837         }
4838     }
4839 
4840     private static void checkLoop1a(int i, MethodHandle in, MethodHandle st) {
4841         if (in.type().returnType() != st.type().returnType()) {
4842             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
4843                     st.type().returnType());
4844         }
4845     }
4846 
4847     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
4848         final List<Class<?>> empty = List.of();
4849         final List<MethodHandle> nonNullInits = init.stream().filter(Objects::nonNull).collect(Collectors.toList());
4850         if (nonNullInits.isEmpty()) {
4851             final List<Class<?>> longest = Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).
4852                     // take only those that can contribute to a common suffix because they are longer than the prefix
4853                     map(MethodHandle::type).filter(t -> t.parameterCount() > cpSize).map(MethodType::parameterList).
4854                     reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
4855             return longest.size() == 0 ? empty : longest.subList(cpSize, longest.size());
4856         } else {
4857             return nonNullInits.stream().map(MethodHandle::type).map(MethodType::parameterList).
4858                     reduce((p, q) -> p.size() >= q.size() ? p : q).get();
4859         }
4860     }
4861 
4862     private static void checkLoop1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
4863         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::parameterList).
4864                 anyMatch(pl -> !pl.equals(commonSuffix.subList(0, pl.size())))) {
4865             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
4866                     " (common suffix: " + commonSuffix + ")");
4867         }
4868     }
4869 
4870     private static void checkLoop1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
4871         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
4872                 anyMatch(t -> t != loopReturnType)) {
4873             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
4874                     loopReturnType + ")");
4875         }
4876 
4877         if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
4878             throw newIllegalArgumentException("no predicate found", pred);
4879         }
4880         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
4881                 anyMatch(t -> t != boolean.class)) {
4882             throw newIllegalArgumentException("predicates must have boolean return type", pred);
4883         }
4884     }
4885 
4886     private static void checkLoop2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
4887         final int cpSize = commonParameterSequence.size();
4888         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
4889                 map(MethodType::parameterList).
4890                 anyMatch(pl -> pl.size() > cpSize || !pl.equals(commonParameterSequence.subList(0, pl.size())))) {
4891             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
4892                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
4893         }
4894     }
4895 
4896     private static void checkIteratedLoop(MethodHandle iterator, MethodHandle body) {
4897         if (null != iterator && !Iterator.class.isAssignableFrom(iterator.type().returnType())) {
4898             throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
4899         }
4900         if (null == body) {
4901             throw newIllegalArgumentException("iterated loop body must not be null");
4902         }
4903     }
4904 
4905     private static void checkTryFinally(MethodHandle target, MethodHandle cleanup) {
4906         Class<?> rtype = target.type().returnType();
4907         if (rtype != cleanup.type().returnType()) {
4908             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
4909         }
4910         List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
4911         if (!Throwable.class.isAssignableFrom(cleanupParamTypes.get(0))) {
4912             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
4913         }
4914         if (rtype != void.class && cleanupParamTypes.get(1) != rtype) {
4915             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
4916         }
4917         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
4918         // target parameter list.
4919         int cleanupArgIndex = rtype == void.class ? 1 : 2;
4920         List<Class<?>> cleanupArgSuffix = cleanupParamTypes.subList(cleanupArgIndex, cleanupParamTypes.size());
4921         List<Class<?>> targetParamTypes = target.type().parameterList();
4922         if (targetParamTypes.size() < cleanupArgSuffix.size() ||
4923                 !cleanupArgSuffix.equals(targetParamTypes.subList(0, cleanupParamTypes.size() - cleanupArgIndex))) {
4924             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
4925                     cleanup.type(), target.type());
4926         }
4927     }
4928 
4929 }