1 /*
   2  * Copyright (c) 2008, 2019, 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.access.JavaLangAccess;
  29 import jdk.internal.access.SharedSecrets;
  30 import jdk.internal.module.IllegalAccessLogger;
  31 import jdk.internal.org.objectweb.asm.ClassReader;
  32 import jdk.internal.reflect.CallerSensitive;
  33 import jdk.internal.reflect.Reflection;
  34 import jdk.internal.vm.annotation.ForceInline;
  35 import sun.invoke.util.ValueConversions;
  36 import sun.invoke.util.VerifyAccess;
  37 import sun.invoke.util.Wrapper;
  38 import sun.reflect.misc.ReflectUtil;
  39 import sun.security.util.SecurityConstants;
  40 
  41 import java.lang.invoke.LambdaForm.BasicType;
  42 import java.lang.reflect.Constructor;
  43 import java.lang.reflect.Field;
  44 import java.lang.reflect.Member;
  45 import java.lang.reflect.Method;
  46 import java.lang.reflect.Modifier;
  47 import java.lang.reflect.ReflectPermission;
  48 import java.nio.ByteOrder;
  49 import java.security.ProtectionDomain;
  50 import java.util.ArrayList;
  51 import java.util.Arrays;
  52 import java.util.BitSet;
  53 import java.util.Iterator;
  54 import java.util.List;
  55 import java.util.Objects;
  56 import java.util.Set;
  57 import java.util.WeakHashMap;
  58 import java.util.concurrent.ConcurrentHashMap;
  59 import java.util.stream.Collectors;
  60 import java.util.stream.Stream;
  61 
  62 import static java.lang.invoke.MethodHandles.Lookup.ClassProperty.*;
  63 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  64 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  65 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  66 import static java.lang.invoke.MethodType.methodType;
  67 
  68 /**
  69  * This class consists exclusively of static methods that operate on or return
  70  * method handles. They fall into several categories:
  71  * <ul>
  72  * <li>Lookup methods which help create method handles for methods and fields.
  73  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  74  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  75  * </ul>
  76  * A lookup, combinator, or factory method will fail and throw an
  77  * {@code IllegalArgumentException} if the created method handle's type
  78  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  79  *
  80  * @author John Rose, JSR 292 EG
  81  * @since 1.7
  82  */
  83 public class MethodHandles {
  84 
  85     private MethodHandles() { }  // do not instantiate
  86 
  87     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  88 
  89     // See IMPL_LOOKUP below.
  90 
  91     //// Method handle creation from ordinary methods.
  92 
  93     /**
  94      * Returns a {@link Lookup lookup object} with
  95      * full capabilities to emulate all supported bytecode behaviors of the caller.
  96      * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller.
  97      * Factory methods on the lookup object can create
  98      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
  99      * for any member that the caller has access to via bytecodes,
 100      * including protected and private fields and methods.
 101      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 102      * Do not store it in place where untrusted code can access it.
 103      * <p>
 104      * This method is caller sensitive, which means that it may return different
 105      * values to different callers.
 106      * @return a lookup object for the caller of this method, with private access
 107      */
 108     @CallerSensitive
 109     @ForceInline // to ensure Reflection.getCallerClass optimization
 110     public static Lookup lookup() {
 111         return new Lookup(Reflection.getCallerClass());
 112     }
 113 
 114     /**
 115      * This reflected$lookup method is the alternate implementation of
 116      * the lookup method when being invoked by reflection.
 117      */
 118     @CallerSensitive
 119     private static Lookup reflected$lookup() {
 120         Class<?> caller = Reflection.getCallerClass();
 121         if (caller.getClassLoader() == null) {
 122             throw newIllegalArgumentException("illegal lookupClass: "+caller);
 123         }
 124         return new Lookup(caller);
 125     }
 126 
 127     /**
 128      * Returns a {@link Lookup lookup object} which is trusted minimally.
 129      * The lookup has the {@code PUBLIC} and {@code UNCONDITIONAL} modes.
 130      * It can only be used to create method handles to public members of
 131      * public classes in packages that are exported unconditionally.
 132      * <p>
 133      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 134      * of this lookup object will be {@link java.lang.Object}.
 135      *
 136      * @apiNote The use of Object is conventional, and because the lookup modes are
 137      * limited, there is no special access provided to the internals of Object, its package
 138      * or its module. Consequently, the lookup context of this lookup object will be the
 139      * bootstrap class loader, which means it cannot find user classes.
 140      *
 141      * <p style="font-size:smaller;">
 142      * <em>Discussion:</em>
 143      * The lookup class can be changed to any other class {@code C} using an expression of the form
 144      * {@link Lookup#in publicLookup().in(C.class)}.
 145      * but may change the lookup context by virtue of changing the class loader.
 146      * A public lookup object is always subject to
 147      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 148      * Also, it cannot access
 149      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 150      * @return a lookup object which is trusted minimally
 151      *
 152      * @revised 9
 153      * @spec JPMS
 154      */
 155     public static Lookup publicLookup() {
 156         return Lookup.PUBLIC_LOOKUP;
 157     }
 158 
 159     /**
 160      * Returns a {@link Lookup lookup object} with full capabilities to emulate all
 161      * supported bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">
 162      * private access</a>, on a target class.
 163      * This method checks that a caller, specified as a {@code Lookup} object, is allowed to
 164      * do <em>deep reflection</em> on the target class. If {@code m1} is the module containing
 165      * the {@link Lookup#lookupClass() lookup class}, and {@code m2} is the module containing
 166      * the target class, then this check ensures that
 167      * <ul>
 168      *     <li>{@code m1} {@link Module#canRead reads} {@code m2}.</li>
 169      *     <li>{@code m2} {@link Module#isOpen(String,Module) opens} the package containing
 170      *     the target class to at least {@code m1}.</li>
 171      *     <li>The lookup has the {@link Lookup#MODULE MODULE} lookup mode.</li>
 172      * </ul>
 173      * <p>
 174      * If there is a security manager, its {@code checkPermission} method is called to
 175      * check {@code ReflectPermission("suppressAccessChecks")}.
 176      * @apiNote The {@code MODULE} lookup mode serves to authenticate that the lookup object
 177      * was created by code in the caller module (or derived from a lookup object originally
 178      * created by the caller). A lookup object with the {@code MODULE} lookup mode can be
 179      * shared with trusted parties without giving away {@code PRIVATE} and {@code PACKAGE}
 180      * access to the caller.
 181      * @param targetClass the target class
 182      * @param lookup the caller lookup object
 183      * @return a lookup object for the target class, with private access
 184      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or array class
 185      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 186      * @throws IllegalAccessException if the access check specified above fails
 187      * @throws SecurityException if denied by the security manager
 188      * @since 9
 189      * @spec JPMS
 190      * @see Lookup#dropLookupMode
 191      */
 192     public static Lookup privateLookupIn(Class<?> targetClass, Lookup lookup) throws IllegalAccessException {
 193         if (lookup.allowedModes == Lookup.TRUSTED) {
 194             return new Lookup(targetClass);
 195         }
 196 
 197         SecurityManager sm = System.getSecurityManager();
 198         if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
 199         if (targetClass.isPrimitive())
 200             throw new IllegalArgumentException(targetClass + " is a primitive class");
 201         if (targetClass.isArray())
 202             throw new IllegalArgumentException(targetClass + " is an array class");
 203         Module targetModule = targetClass.getModule();
 204         Module callerModule = lookup.lookupClass().getModule();
 205         if (!callerModule.canRead(targetModule))
 206             throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 207         if (targetModule.isNamed()) {
 208             String pn = targetClass.getPackageName();
 209             assert !pn.isEmpty() : "unnamed package cannot be in named module";
 210             if (!targetModule.isOpen(pn, callerModule))
 211                 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 212         }
 213         if ((lookup.lookupModes() & Lookup.MODULE) == 0)
 214             throw new IllegalAccessException("lookup does not have MODULE lookup mode");
 215         if (!callerModule.isNamed() && targetModule.isNamed()) {
 216             IllegalAccessLogger logger = IllegalAccessLogger.illegalAccessLogger();
 217             if (logger != null) {
 218                 logger.logIfOpenedForIllegalAccess(lookup, targetClass);
 219             }
 220         }
 221         return new Lookup(targetClass);
 222     }
 223 
 224     /**
 225      * Performs an unchecked "crack" of a
 226      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 227      * The result is as if the user had obtained a lookup object capable enough
 228      * to crack the target method handle, called
 229      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 230      * on the target to obtain its symbolic reference, and then called
 231      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 232      * to resolve the symbolic reference to a member.
 233      * <p>
 234      * If there is a security manager, its {@code checkPermission} method
 235      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 236      * @param <T> the desired type of the result, either {@link Member} or a subtype
 237      * @param target a direct method handle to crack into symbolic reference components
 238      * @param expected a class object representing the desired result type {@code T}
 239      * @return a reference to the method, constructor, or field object
 240      * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
 241      * @exception NullPointerException if either argument is {@code null}
 242      * @exception IllegalArgumentException if the target is not a direct method handle
 243      * @exception ClassCastException if the member is not of the expected type
 244      * @since 1.8
 245      */
 246     public static <T extends Member> T
 247     reflectAs(Class<T> expected, MethodHandle target) {
 248         SecurityManager smgr = System.getSecurityManager();
 249         if (smgr != null)  smgr.checkPermission(ACCESS_PERMISSION);
 250         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 251         return lookup.revealDirect(target).reflectAs(expected, lookup);
 252     }
 253     // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
 254     private static final java.security.Permission ACCESS_PERMISSION =
 255         new ReflectPermission("suppressAccessChecks");
 256 
 257     /**
 258      * A <em>lookup object</em> is a factory for creating method handles,
 259      * when the creation requires access checking.
 260      * Method handles do not perform
 261      * access checks when they are called, but rather when they are created.
 262      * Therefore, method handle access
 263      * restrictions must be enforced when a method handle is created.
 264      * The caller class against which those restrictions are enforced
 265      * is known as the {@linkplain #lookupClass() lookup class}.
 266      * <p>
 267      * A lookup class which needs to create method handles will call
 268      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 269      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 270      * determined, and securely stored in the {@code Lookup} object.
 271      * The lookup class (or its delegates) may then use factory methods
 272      * on the {@code Lookup} object to create method handles for access-checked members.
 273      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 274      * even private ones.
 275      *
 276      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 277      * The factory methods on a {@code Lookup} object correspond to all major
 278      * use cases for methods, constructors, and fields.
 279      * Each method handle created by a factory method is the functional
 280      * equivalent of a particular <em>bytecode behavior</em>.
 281      * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
 282      * Here is a summary of the correspondence between these factory methods and
 283      * the behavior of the resulting method handles:
 284      * <table class="striped">
 285      * <caption style="display:none">lookup method behaviors</caption>
 286      * <thead>
 287      * <tr>
 288      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 289      *     <th scope="col">member</th>
 290      *     <th scope="col">bytecode behavior</th>
 291      * </tr>
 292      * </thead>
 293      * <tbody>
 294      * <tr>
 295      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 296      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 297      * </tr>
 298      * <tr>
 299      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 300      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
 301      * </tr>
 302      * <tr>
 303      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 304      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 305      * </tr>
 306      * <tr>
 307      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 308      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 309      * </tr>
 310      * <tr>
 311      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 312      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 313      * </tr>
 314      * <tr>
 315      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 316      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 317      * </tr>
 318      * <tr>
 319      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 320      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 321      * </tr>
 322      * <tr>
 323      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 324      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 325      * </tr>
 326      * <tr>
 327      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 328      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 329      * </tr>
 330      * <tr>
 331      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 332      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 333      * </tr>
 334      * <tr>
 335      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 336      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 337      * </tr>
 338      * <tr>
 339      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 340      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 341      * </tr>
 342      * <tr>
 343      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 344      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 345      * </tr>
 346      * <tr>
 347      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 348      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 349      * </tr>
 350      * </tbody>
 351      * </table>
 352      *
 353      * Here, the type {@code C} is the class or interface being searched for a member,
 354      * documented as a parameter named {@code refc} in the lookup methods.
 355      * The method type {@code MT} is composed from the return type {@code T}
 356      * and the sequence of argument types {@code A*}.
 357      * The constructor also has a sequence of argument types {@code A*} and
 358      * is deemed to return the newly-created object of type {@code C}.
 359      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 360      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 361      * if it is present, it is always the leading argument to the method handle invocation.
 362      * (In the case of some {@code protected} members, {@code this} may be
 363      * restricted in type to the lookup class; see below.)
 364      * The name {@code arg} stands for all the other method handle arguments.
 365      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 366      * stands for a null reference if the accessed method or field is static,
 367      * and {@code this} otherwise.
 368      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 369      * for reflective objects corresponding to the given members.
 370      * <p>
 371      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 372      * as if by {@code ldc CONSTANT_Class}.
 373      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 374      * <p>
 375      * In cases where the given member is of variable arity (i.e., a method or constructor)
 376      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 377      * In all other cases, the returned method handle will be of fixed arity.
 378      * <p style="font-size:smaller;">
 379      * <em>Discussion:</em>
 380      * The equivalence between looked-up method handles and underlying
 381      * class members and bytecode behaviors
 382      * can break down in a few ways:
 383      * <ul style="font-size:smaller;">
 384      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 385      * the lookup can still succeed, even when there is no equivalent
 386      * Java expression or bytecoded constant.
 387      * <li>Likewise, if {@code T} or {@code MT}
 388      * is not symbolically accessible from the lookup class's loader,
 389      * the lookup can still succeed.
 390      * For example, lookups for {@code MethodHandle.invokeExact} and
 391      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 392      * <li>If there is a security manager installed, it can forbid the lookup
 393      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 394      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 395      * constant is not subject to security manager checks.
 396      * <li>If the looked-up method has a
 397      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 398      * the method handle creation may fail with an
 399      * {@code IllegalArgumentException}, due to the method handle type having
 400      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 401      * </ul>
 402      *
 403      * <h2><a id="access"></a>Access checking</h2>
 404      * Access checks are applied in the factory methods of {@code Lookup},
 405      * when a method handle is created.
 406      * This is a key difference from the Core Reflection API, since
 407      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 408      * performs access checking against every caller, on every call.
 409      * <p>
 410      * All access checks start from a {@code Lookup} object, which
 411      * compares its recorded lookup class against all requests to
 412      * create method handles.
 413      * A single {@code Lookup} object can be used to create any number
 414      * of access-checked method handles, all checked against a single
 415      * lookup class.
 416      * <p>
 417      * A {@code Lookup} object can be shared with other trusted code,
 418      * such as a metaobject protocol.
 419      * A shared {@code Lookup} object delegates the capability
 420      * to create method handles on private members of the lookup class.
 421      * Even if privileged code uses the {@code Lookup} object,
 422      * the access checking is confined to the privileges of the
 423      * original lookup class.
 424      * <p>
 425      * A lookup can fail, because
 426      * the containing class is not accessible to the lookup class, or
 427      * because the desired class member is missing, or because the
 428      * desired class member is not accessible to the lookup class, or
 429      * because the lookup object is not trusted enough to access the member.
 430      * In the case of a field setter function on a {@code final} field,
 431      * finality enforcement is treated as a kind of access control,
 432      * and the lookup will fail, except in special cases of
 433      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 434      * In any of these cases, a {@code ReflectiveOperationException} will be
 435      * thrown from the attempted lookup.  The exact class will be one of
 436      * the following:
 437      * <ul>
 438      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 439      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 440      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 441      * </ul>
 442      * <p>
 443      * In general, the conditions under which a method handle may be
 444      * looked up for a method {@code M} are no more restrictive than the conditions
 445      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 446      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 447      * a method handle lookup will generally raise a corresponding
 448      * checked exception, such as {@code NoSuchMethodException}.
 449      * And the effect of invoking the method handle resulting from the lookup
 450      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 451      * to executing the compiled, verified, and resolved call to {@code M}.
 452      * The same point is true of fields and constructors.
 453      * <p style="font-size:smaller;">
 454      * <em>Discussion:</em>
 455      * Access checks only apply to named and reflected methods,
 456      * constructors, and fields.
 457      * Other method handle creation methods, such as
 458      * {@link MethodHandle#asType MethodHandle.asType},
 459      * do not require any access checks, and are used
 460      * independently of any {@code Lookup} object.
 461      * <p>
 462      * If the desired member is {@code protected}, the usual JVM rules apply,
 463      * including the requirement that the lookup class must either be in the
 464      * same package as the desired member, or must inherit that member.
 465      * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.)
 466      * In addition, if the desired member is a non-static field or method
 467      * in a different package, the resulting method handle may only be applied
 468      * to objects of the lookup class or one of its subclasses.
 469      * This requirement is enforced by narrowing the type of the leading
 470      * {@code this} parameter from {@code C}
 471      * (which will necessarily be a superclass of the lookup class)
 472      * to the lookup class itself.
 473      * <p>
 474      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 475      * that the receiver argument must match both the resolved method <em>and</em>
 476      * the current class.  Again, this requirement is enforced by narrowing the
 477      * type of the leading parameter to the resulting method handle.
 478      * (See the Java Virtual Machine Specification, section 4.10.1.9.)
 479      * <p>
 480      * The JVM represents constructors and static initializer blocks as internal methods
 481      * with special names ({@code "<init>"} and {@code "<clinit>"}).
 482      * The internal syntax of invocation instructions allows them to refer to such internal
 483      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 484      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 485      * <p>
 486      * If the relationship between nested types is expressed directly through the
 487      * {@code NestHost} and {@code NestMembers} attributes
 488      * (see the Java Virtual Machine Specification, sections 4.7.28 and 4.7.29),
 489      * then the associated {@code Lookup} object provides direct access to
 490      * the lookup class and all of its nestmates
 491      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 492      * Otherwise, access between nested classes is obtained by the Java compiler creating
 493      * a wrapper method to access a private method of another class in the same nest.
 494      * For example, a nested class {@code C.D}
 495      * can access private members within other related classes such as
 496      * {@code C}, {@code C.D.E}, or {@code C.B},
 497      * but the Java compiler may need to generate wrapper methods in
 498      * those related classes.  In such cases, a {@code Lookup} object on
 499      * {@code C.E} would be unable to access those private members.
 500      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 501      * which can transform a lookup on {@code C.E} into one on any of those other
 502      * classes, without special elevation of privilege.
 503      * <p>
 504      * The accesses permitted to a given lookup object may be limited,
 505      * according to its set of {@link #lookupModes lookupModes},
 506      * to a subset of members normally accessible to the lookup class.
 507      * For example, the {@link MethodHandles#publicLookup publicLookup}
 508      * method produces a lookup object which is only allowed to access
 509      * public members in public classes of exported packages.
 510      * The caller sensitive method {@link MethodHandles#lookup lookup}
 511      * produces a lookup object with full capabilities relative to
 512      * its caller class, to emulate all supported bytecode behaviors.
 513      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 514      * with fewer access modes than the original lookup object.
 515      *
 516      * <p style="font-size:smaller;">
 517      * <a id="privacc"></a>
 518      * <em>Discussion of private access:</em>
 519      * We say that a lookup has <em>private access</em>
 520      * if its {@linkplain #lookupModes lookup modes}
 521      * include the possibility of accessing {@code private} members
 522      * (which includes the private members of nestmates).
 523      * As documented in the relevant methods elsewhere,
 524      * only lookups with private access possess the following capabilities:
 525      * <ul style="font-size:smaller;">
 526      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 527      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 528      *     such as {@code Class.forName}
 529      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 530      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 531      *     for classes accessible to the lookup class
 532      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 533      *     within the same package member
 534      * </ul>
 535      * <p style="font-size:smaller;">
 536      * Each of these permissions is a consequence of the fact that a lookup object
 537      * with private access can be securely traced back to an originating class,
 538      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 539      * can be reliably determined and emulated by method handles.
 540      *
 541      * <h2><a id="secmgr"></a>Security manager interactions</h2>
 542      * Although bytecode instructions can only refer to classes in
 543      * a related class loader, this API can search for methods in any
 544      * class, as long as a reference to its {@code Class} object is
 545      * available.  Such cross-loader references are also possible with the
 546      * Core Reflection API, and are impossible to bytecode instructions
 547      * such as {@code invokestatic} or {@code getfield}.
 548      * There is a {@linkplain java.lang.SecurityManager security manager API}
 549      * to allow applications to check such cross-loader references.
 550      * These checks apply to both the {@code MethodHandles.Lookup} API
 551      * and the Core Reflection API
 552      * (as found on {@link java.lang.Class Class}).
 553      * <p>
 554      * If a security manager is present, member and class lookups are subject to
 555      * additional checks.
 556      * From one to three calls are made to the security manager.
 557      * Any of these calls can refuse access by throwing a
 558      * {@link java.lang.SecurityException SecurityException}.
 559      * Define {@code smgr} as the security manager,
 560      * {@code lookc} as the lookup class of the current lookup object,
 561      * {@code refc} as the containing class in which the member
 562      * is being sought, and {@code defc} as the class in which the
 563      * member is actually defined.
 564      * (If a class or other type is being accessed,
 565      * the {@code refc} and {@code defc} values are the class itself.)
 566      * The value {@code lookc} is defined as <em>not present</em>
 567      * if the current lookup object does not have
 568      * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 569      * The calls are made according to the following rules:
 570      * <ul>
 571      * <li><b>Step 1:</b>
 572      *     If {@code lookc} is not present, or if its class loader is not
 573      *     the same as or an ancestor of the class loader of {@code refc},
 574      *     then {@link SecurityManager#checkPackageAccess
 575      *     smgr.checkPackageAccess(refcPkg)} is called,
 576      *     where {@code refcPkg} is the package of {@code refc}.
 577      * <li><b>Step 2a:</b>
 578      *     If the retrieved member is not public and
 579      *     {@code lookc} is not present, then
 580      *     {@link SecurityManager#checkPermission smgr.checkPermission}
 581      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
 582      * <li><b>Step 2b:</b>
 583      *     If the retrieved class has a {@code null} class loader,
 584      *     and {@code lookc} is not present, then
 585      *     {@link SecurityManager#checkPermission smgr.checkPermission}
 586      *     with {@code RuntimePermission("getClassLoader")} is called.
 587      * <li><b>Step 3:</b>
 588      *     If the retrieved member is not public,
 589      *     and if {@code lookc} is not present,
 590      *     and if {@code defc} and {@code refc} are different,
 591      *     then {@link SecurityManager#checkPackageAccess
 592      *     smgr.checkPackageAccess(defcPkg)} is called,
 593      *     where {@code defcPkg} is the package of {@code defc}.
 594      * </ul>
 595      * Security checks are performed after other access checks have passed.
 596      * Therefore, the above rules presuppose a member or class that is public,
 597      * or else that is being accessed from a lookup class that has
 598      * rights to access the member or class.
 599      *
 600      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
 601      * A small number of Java methods have a special property called caller sensitivity.
 602      * A <em>caller-sensitive</em> method can behave differently depending on the
 603      * identity of its immediate caller.
 604      * <p>
 605      * If a method handle for a caller-sensitive method is requested,
 606      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
 607      * but they take account of the lookup class in a special way.
 608      * The resulting method handle behaves as if it were called
 609      * from an instruction contained in the lookup class,
 610      * so that the caller-sensitive method detects the lookup class.
 611      * (By contrast, the invoker of the method handle is disregarded.)
 612      * Thus, in the case of caller-sensitive methods,
 613      * different lookup classes may give rise to
 614      * differently behaving method handles.
 615      * <p>
 616      * In cases where the lookup object is
 617      * {@link MethodHandles#publicLookup() publicLookup()},
 618      * or some other lookup object without
 619      * <a href="MethodHandles.Lookup.html#privacc">private access</a>,
 620      * the lookup class is disregarded.
 621      * In such cases, no caller-sensitive method handle can be created,
 622      * access is forbidden, and the lookup fails with an
 623      * {@code IllegalAccessException}.
 624      * <p style="font-size:smaller;">
 625      * <em>Discussion:</em>
 626      * For example, the caller-sensitive method
 627      * {@link java.lang.Class#forName(String) Class.forName(x)}
 628      * can return varying classes or throw varying exceptions,
 629      * depending on the class loader of the class that calls it.
 630      * A public lookup of {@code Class.forName} will fail, because
 631      * there is no reasonable way to determine its bytecode behavior.
 632      * <p style="font-size:smaller;">
 633      * If an application caches method handles for broad sharing,
 634      * it should use {@code publicLookup()} to create them.
 635      * If there is a lookup of {@code Class.forName}, it will fail,
 636      * and the application must take appropriate action in that case.
 637      * It may be that a later lookup, perhaps during the invocation of a
 638      * bootstrap method, can incorporate the specific identity
 639      * of the caller, making the method accessible.
 640      * <p style="font-size:smaller;">
 641      * The function {@code MethodHandles.lookup} is caller sensitive
 642      * so that there can be a secure foundation for lookups.
 643      * Nearly all other methods in the JSR 292 API rely on lookup
 644      * objects to check access requests.
 645      *
 646      * @revised 9
 647      */
 648     public static final
 649     class Lookup {
 650         /** The class on behalf of whom the lookup is being performed. */
 651         private final Class<?> lookupClass;
 652 
 653         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
 654         private final int allowedModes;
 655 
 656         static {
 657             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
 658         }
 659 
 660         /** A single-bit mask representing {@code public} access,
 661          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 662          *  The value, {@code 0x01}, happens to be the same as the value of the
 663          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
 664          */
 665         public static final int PUBLIC = Modifier.PUBLIC;
 666 
 667         /** A single-bit mask representing {@code private} access,
 668          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 669          *  The value, {@code 0x02}, happens to be the same as the value of the
 670          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
 671          */
 672         public static final int PRIVATE = Modifier.PRIVATE;
 673 
 674         /** A single-bit mask representing {@code protected} access,
 675          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 676          *  The value, {@code 0x04}, happens to be the same as the value of the
 677          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
 678          */
 679         public static final int PROTECTED = Modifier.PROTECTED;
 680 
 681         /** A single-bit mask representing {@code package} access (default access),
 682          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 683          *  The value is {@code 0x08}, which does not correspond meaningfully to
 684          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
 685          */
 686         public static final int PACKAGE = Modifier.STATIC;
 687 
 688         /** A single-bit mask representing {@code module} access (default access),
 689          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 690          *  The value is {@code 0x10}, which does not correspond meaningfully to
 691          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
 692          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
 693          *  with this lookup mode can access all public types in the module of the
 694          *  lookup class and public types in packages exported by other modules
 695          *  to the module of the lookup class.
 696          *  @since 9
 697          *  @spec JPMS
 698          */
 699         public static final int MODULE = PACKAGE << 1;
 700 
 701         /** A single-bit mask representing {@code unconditional} access
 702          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 703          *  The value is {@code 0x20}, which does not correspond meaningfully to
 704          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
 705          *  A {@code Lookup} with this lookup mode assumes {@linkplain
 706          *  java.lang.Module#canRead(java.lang.Module) readability}.
 707          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
 708          *  with this lookup mode can access all public members of public types
 709          *  of all modules where the type is in a package that is {@link
 710          *  java.lang.Module#isExported(String) exported unconditionally}.
 711          *  @since 9
 712          *  @spec JPMS
 713          *  @see #publicLookup()
 714          */
 715         public static final int UNCONDITIONAL = PACKAGE << 2;
 716 
 717         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL);
 718         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);
 719         private static final int TRUSTED   = -1;
 720 
 721         private static int fixmods(int mods) {
 722             mods &= (ALL_MODES - PACKAGE - MODULE - UNCONDITIONAL);
 723             return (mods != 0) ? mods : (PACKAGE | MODULE | UNCONDITIONAL);
 724         }
 725 
 726         /** Tells which class is performing the lookup.  It is this class against
 727          *  which checks are performed for visibility and access permissions.
 728          *  <p>
 729          *  The class implies a maximum level of access permission,
 730          *  but the permissions may be additionally limited by the bitmask
 731          *  {@link #lookupModes lookupModes}, which controls whether non-public members
 732          *  can be accessed.
 733          *  @return the lookup class, on behalf of which this lookup object finds members
 734          */
 735         public Class<?> lookupClass() {
 736             return lookupClass;
 737         }
 738 
 739         // This is just for calling out to MethodHandleImpl.
 740         private Class<?> lookupClassOrNull() {
 741             return (allowedModes == TRUSTED) ? null : lookupClass;
 742         }
 743 
 744         /** Tells which access-protection classes of members this lookup object can produce.
 745          *  The result is a bit-mask of the bits
 746          *  {@linkplain #PUBLIC PUBLIC (0x01)},
 747          *  {@linkplain #PRIVATE PRIVATE (0x02)},
 748          *  {@linkplain #PROTECTED PROTECTED (0x04)},
 749          *  {@linkplain #PACKAGE PACKAGE (0x08)},
 750          *  {@linkplain #MODULE MODULE (0x10)},
 751          *  and {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}.
 752          *  <p>
 753          *  A freshly-created lookup object
 754          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
 755          *  all possible bits set, except {@code UNCONDITIONAL}.
 756          *  A lookup object on a new lookup class
 757          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
 758          *  may have some mode bits set to zero.
 759          *  Mode bits can also be
 760          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
 761          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
 762          *  The purpose of this is to restrict access via the new lookup object,
 763          *  so that it can access only names which can be reached by the original
 764          *  lookup object, and also by the new lookup class.
 765          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
 766          *  @see #in
 767          *  @see #dropLookupMode
 768          *
 769          *  @revised 9
 770          *  @spec JPMS
 771          */
 772         public int lookupModes() {
 773             return allowedModes & ALL_MODES;
 774         }
 775 
 776         /** Embody the current class (the lookupClass) as a lookup class
 777          * for method handle creation.
 778          * Must be called by from a method in this package,
 779          * which in turn is called by a method not in this package.
 780          */
 781         Lookup(Class<?> lookupClass) {
 782             this(lookupClass, FULL_POWER_MODES);
 783         }
 784 
 785         private Lookup(Class<?> lookupClass, int allowedModes) {
 786             this.lookupClass = lookupClass;
 787             this.allowedModes = allowedModes;
 788             assert !lookupClass.isPrimitive() && !lookupClass.isArray();
 789         }
 790 
 791         /**
 792          * Creates a lookup on the specified new lookup class.
 793          * The resulting object will report the specified
 794          * class as its own {@link #lookupClass() lookupClass}.
 795          * <p>
 796          * However, the resulting {@code Lookup} object is guaranteed
 797          * to have no more access capabilities than the original.
 798          * In particular, access capabilities can be lost as follows:<ul>
 799          * <li>If the old lookup class is in a {@link Module#isNamed() named} module, and
 800          * the new lookup class is in a different module {@code M}, then no members, not
 801          * even public members in {@code M}'s exported packages, will be accessible.
 802          * The exception to this is when this lookup is {@link #publicLookup()
 803          * publicLookup}, in which case {@code PUBLIC} access is not lost.
 804          * <li>If the old lookup class is in an unnamed module, and the new lookup class
 805          * is a different module then {@link #MODULE MODULE} access is lost.
 806          * <li>If the new lookup class differs from the old one then {@code UNCONDITIONAL} is lost.
 807          * <li>If the new lookup class is in a different package
 808          * than the old one, protected and default (package) members will not be accessible.
 809          * <li>If the new lookup class is not within the same package member
 810          * as the old one, private members will not be accessible, and protected members
 811          * will not be accessible by virtue of inheritance.
 812          * (Protected members may continue to be accessible because of package sharing.)
 813          * <li>If the new lookup class is not accessible to the old lookup class,
 814          * then no members, not even public members, will be accessible.
 815          * (In all other cases, public members will continue to be accessible.)
 816          * </ul>
 817          * <p>
 818          * The resulting lookup's capabilities for loading classes
 819          * (used during {@link #findClass} invocations)
 820          * are determined by the lookup class' loader,
 821          * which may change due to this operation.
 822          *
 823          * @param requestedLookupClass the desired lookup class for the new lookup object
 824          * @return a lookup object which reports the desired lookup class, or the same object
 825          * if there is no change
 826          * @throws IllegalArgumentException if {@code requestedLookupClass} is
 827          * a primitive type or array class
 828          * @throws NullPointerException if the argument is null
 829          *
 830          * @revised 9
 831          * @spec JPMS
 832          */
 833         public Lookup in(Class<?> requestedLookupClass) {
 834             Objects.requireNonNull(requestedLookupClass);
 835             if (requestedLookupClass.isPrimitive())
 836                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
 837             if (requestedLookupClass.isArray())
 838                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
 839 
 840             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
 841                 return new Lookup(requestedLookupClass, FULL_POWER_MODES);
 842             if (requestedLookupClass == this.lookupClass)
 843                 return this;  // keep same capabilities
 844             int newModes = (allowedModes & FULL_POWER_MODES);
 845             if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) {
 846                 // Need to drop all access when teleporting from a named module to another
 847                 // module. The exception is publicLookup where PUBLIC is not lost.
 848                 if (this.lookupClass.getModule().isNamed()
 849                     && (this.allowedModes & UNCONDITIONAL) == 0)
 850                     newModes = 0;
 851                 else
 852                     newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
 853             }
 854             if ((newModes & PACKAGE) != 0
 855                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
 856                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
 857             }
 858             // Allow nestmate lookups to be created without special privilege:
 859             if ((newModes & PRIVATE) != 0
 860                 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
 861                 newModes &= ~(PRIVATE|PROTECTED);
 862             }
 863             if ((newModes & PUBLIC) != 0
 864                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
 865                 // The requested class it not accessible from the lookup class.
 866                 // No permissions.
 867                 newModes = 0;
 868             }
 869 
 870             checkUnprivilegedlookupClass(requestedLookupClass);
 871             return new Lookup(requestedLookupClass, newModes);
 872         }
 873 
 874 
 875         /**
 876          * Creates a lookup on the same lookup class which this lookup object
 877          * finds members, but with a lookup mode that has lost the given lookup mode.
 878          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
 879          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED} or {@link #PRIVATE PRIVATE}.
 880          * {@link #PROTECTED PROTECTED} and {@link #UNCONDITIONAL UNCONDITIONAL} are always
 881          * dropped and so the resulting lookup mode will never have these access capabilities.
 882          * When dropping {@code PACKAGE} then the resulting lookup will not have {@code PACKAGE}
 883          * or {@code PRIVATE} access. When dropping {@code MODULE} then the resulting lookup will
 884          * not have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. If {@code PUBLIC}
 885          * is dropped then the resulting lookup has no access.
 886          * @param modeToDrop the lookup mode to drop
 887          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
 888          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
 889          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE} or {@code UNCONDITIONAL}
 890          * @see MethodHandles#privateLookupIn
 891          * @since 9
 892          */
 893         public Lookup dropLookupMode(int modeToDrop) {
 894             int oldModes = lookupModes();
 895             int newModes = oldModes & ~(modeToDrop | PROTECTED | UNCONDITIONAL);
 896             switch (modeToDrop) {
 897                 case PUBLIC: newModes &= ~(ALL_MODES); break;
 898                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
 899                 case PACKAGE: newModes &= ~(PRIVATE); break;
 900                 case PROTECTED:
 901                 case PRIVATE:
 902                 case UNCONDITIONAL: break;
 903                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
 904             }
 905             if (newModes == oldModes) return this;  // return self if no change
 906             return new Lookup(lookupClass(), newModes);
 907         }
 908 
 909         /**
 910          * Defines a class to the same class loader and in the same runtime package and
 911          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
 912          * {@linkplain #lookupClass() lookup class}.
 913          *
 914          * This method is equivalent to calling
 915          * {@link #defineClass(byte[], ClassProperty[])
 916          * defineClass(bytes, (ClassProperty[])null)}.
 917          *
 918          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
 919          * {@link #PACKAGE PACKAGE} access as default (package) members will be
 920          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
 921          * that the lookup object was created by a caller in the runtime package (or derived
 922          * from a lookup originally created by suitably privileged code to a target class in
 923          * the runtime package). </p>
 924          *
 925          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
 926          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
 927          * same package as the lookup class. </p>
 928          *
 929          * <p> This method does not run the class initializer. The class initializer may
 930          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
 931          * Specification</em>. </p>
 932          *
 933          * <p> If there is a security manager, its {@code checkPermission} method is first called
 934          * to check {@code RuntimePermission("defineClass")}. </p>
 935          *
 936          * @param bytes the class bytes
 937          * @return the {@code Class} object for the class
 938          * @throws IllegalArgumentException the bytes are for a class in a different package
 939          * to the lookup class
 940          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
 941          * @throws LinkageError if the class is malformed ({@code ClassFormatError}), cannot be
 942          * verified ({@code VerifyError}), is already defined, or another linkage error occurs
 943          * @throws SecurityException if denied by the security manager
 944          * @throws NullPointerException if {@code bytes} is {@code null}
 945          * @since 9
 946          * @spec JPMS
 947          * @see Lookup#privateLookupIn
 948          * @see Lookup#dropLookupMode
 949          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
 950          */
 951         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
 952             return defineClass(bytes, (ClassProperty[])null);
 953         }
 954 
 955         /**
 956          * Defines a class to the same class loader and in the same runtime package
 957          * and {@linkplain java.security.ProtectionDomain protection domain} as
 958          * this lookup's {@linkplain #lookupClass() lookup class}.
 959          * The {@code props} parameter specifies the properties of the class.
 960          *
 961          * <p> A class can be defined with the following properties:
 962          * <ul>
 963          * <li>A {@linkplain ClassProperty#NESTMATE <em>nestmate</em>} of the lookup class,
 964          *     i.e. in the same {@linkplain Class#getNestHost nest}
 965          *     of the lookup class.  The class will have access to the private members
 966          *     of all classes and interfaces in the same nest.
 967          *     </li>
 968          * <li>A {@linkplain ClassProperty#HIDDEN <em>hidden</em>} class,
 969          *     i.e. a class cannot be referenced by other classes.
 970          *     A hidden class has the following properties:
 971          *     <ul>
 972          *     <li>Naming:
 973          *     The name of this class is derived from the name of
 974          *     the class in the class bytes so that the class name does not
 975          *     collide with other classes defined to the same class loader.
 976          *     <li>Class resolution:
 977          *     The Java virtual machine does not find a hidden class with
 978          *     its name.  A hidden class can reference its members
 979          *     locally with the name of the class in the class bytes as if
 980          *     a non-hidden class. The name returned by {@link Class#getName()}
 981          *     is not known when the class bytes are generated.
 982          *     <li>Class retransformation:
 983          *     The class is not modifiable by Java agents or tool agents using
 984          *     the <a href="{@docRoot}/../specs/jvmti.html">JVM Tool Interface</a>.
 985          *     </ul>
 986          *     </li>
 987          * <li>A {@linkplain ClassProperty#WEAK <em>weak</em>} class,
 988          *     i.e. a class may be unloaded even if its defining class loader is
 989          *     <a href="../ref/package.html#reachability">reachable</a>,
 990          *     as if the defining class loader would only hold a
 991          *     {@linkplain java.lang.ref.WeakReference weak reference} of
 992          *     the class.
 993          *     A weak class is hidden.  If the {@code WEAK} property is set,
 994          *     then it implies that {@code HIDDEN} property is also set.</li>
 995          * </ul>
 996          *
 997          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must
 998          * include {@link #PACKAGE PACKAGE} access as default (package) members
 999          * will be accessible to the class. The {@code PACKAGE} lookup mode serves
1000          * to authenticate that the lookup object was created by a caller in
1001          * the runtime package (or derived from a lookup originally created by
1002          * suitably privileged code to a target class in the runtime package).
1003          * If the class is defined as a {@linkplain ClassProperty#NESTMATE nestmate}
1004          * then the {@linkplain #lookupModes() lookup modes} for this lookup must
1005          * include {@link #PRIVATE PRIVATE} access. </p>
1006          *
1007          * <p> The {@code bytes} parameter is the class bytes of a valid class file
1008          * (as defined by the <em>The Java Virtual Machine Specification</em>)
1009          * with a class name in the same package as the lookup class.
1010          * The class bytes of a nestmate class must not contain
1011          * the {@code NestHost} attribute nor the {@code NestMembers} attribute. </p>
1012          *
1013          * <p> If there is a security manager, its {@code checkPermission} method is first called
1014          * to check {@code RuntimePermission("defineClass")}. </p>
1015          *
1016          * <p> This method does not run the class initializer. The class initializer
1017          * may run at a later time, as detailed in section 12.4 of the The Java Language Specification.
1018          *
1019          * <p> The class can obtain {@code classData} by calling
1020          * the {@link Lookup#classData()} method of its {@code Lookup} object.
1021          *
1022          * @apiNote  An implementation of the Java Progamming Language may
1023          * unload classes as specified in section 12.7 of the Java Language Specification.
1024          * A class or interface may be unloaded if and only if
1025          * its defining class loader may be reclaimed by the garbage collector.
1026          * If the implementation supports class loading, a weak class
1027          * may become weakly reachable as if the defining class loader would
1028          * only hold a {@linkplain java.lang.ref.WeakReference weak reference}
1029          * of the class.
1030          *
1031          * @param bytes      the class bytes
1032          * @param props {@linkplain ClassProperty class properties}
1033          * @return the {@code Class} object for the class
1034          *
1035          * @throws IllegalArgumentException the bytes are for a class in a different package
1036          *                                  to the lookup class
1037          * @throws IllegalAccessException   if this lookup does not have {@code PACKAGE} access, or
1038          *                                  if {@code properties} contains {@code NESTMATE} but this lookup
1039          *                                  does not have {@code PRIVATE} access
1040          * @throws LinkageError             if the class is malformed ({@code ClassFormatError}), cannot be
1041          *                                  verified ({@code VerifyError}), is already defined,
1042          *                                  or another linkage error occurs
1043          * @throws SecurityException        if denied by the security manager
1044          * @throws NullPointerException     if {@code bytes} is {@code null}
1045          *
1046          * @since 12
1047          * @jls 12.7 Unloading of Classes and Interfaces
1048          * @see Lookup#privateLookupIn(Class, Lookup)
1049          * @see Lookup#dropLookupMode(int)
1050          */
1051         public Class<?> defineClass(byte[] bytes, ClassProperty... props) throws IllegalAccessException {
1052             Objects.requireNonNull(bytes);
1053 
1054             // clone the properties before access
1055             Set<ClassProperty> properties;
1056             if (props == null || props.length == 0) {
1057                 properties = EMPTY_PROPS;
1058             } else {
1059                 properties = Set.of(props);
1060             }
1061 
1062             // Is it ever possible to create Lookup for int.class or Object[].class?
1063             assert !lookupClass.isPrimitive() && !lookupClass.isArray();
1064 
1065             if ((lookupModes() & PACKAGE) == 0){
1066                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1067             }
1068 
1069             if (properties.contains(NESTMATE) && (lookupModes() & PRIVATE) == 0){
1070                 throw new IllegalAccessException("Lookup does not have PRIVATE access");
1071             }
1072 
1073             assert (lookupModes() & (MODULE | PUBLIC)) != 0;
1074 
1075             SecurityManager sm = System.getSecurityManager();
1076             if (sm != null)
1077                 sm.checkPermission(new RuntimePermission("defineClass"));
1078 
1079             return defineClassWithNoCheck(bytes, classPropertiesToFlags(properties));
1080         }
1081 
1082         /**
1083          * Defines a class to the same class loader and in the same runtime package
1084          * and {@linkplain java.security.ProtectionDomain protection domain} as
1085          * this lookup's {@linkplain #lookupClass() lookup class} with
1086          * the given class properties and {@code classData}.
1087          *
1088          * <p> This method defines a class as if calling
1089          * {@link #defineClass(byte[], ClassProperty...) defineClass(bytes, props)}
1090          * and then the class initializer with an injected the {@code classData}
1091          * as a pre-initialized static unnamed field.
1092          * The injected pre-initialized static unnamed field can be
1093          * obtained by calling the {@link Lookup#classData()} method of
1094          * its {@code Lookup} object.
1095          *
1096          * <p> If there is a security manager, its {@code checkPermission} method is first called
1097          * to check {@code RuntimePermission("defineClass")}. </p>
1098          *
1099          * @apiNote
1100          * This method initializes the class, as opposed to the {@link #defineClass(byte[], ClassProperty...)}
1101          * method which does not invoke {@code <clinit>}, because the returned {@code Class}
1102          * is as if it contains a private static unnamed field that is initialized to
1103          * the given {@code classData} along with other declared static fields
1104          * via {@code <clinit>}.
1105          *
1106          * @param bytes      the class bytes
1107          * @param classData pre-initialized class data
1108          * @param props {@linkplain ClassProperty class properties}
1109          * @return the {@code Class} object for the class
1110          *
1111          * @throws IllegalArgumentException the bytes are for a class in a different package
1112          *                                  to the lookup class
1113          * @throws IllegalAccessException   if this lookup does not have {@code PACKAGE} access, or
1114          *                                  if {@code properties} contains {@code NESTMATE} but this lookup
1115          *                                  does not have {@code PRIVATE} access
1116          * @throws LinkageError             if the class is malformed ({@code ClassFormatError}), cannot be
1117          *                                  verified ({@code VerifyError}), is already defined,
1118          *                                  or another linkage error occurs
1119          * @throws SecurityException        if denied by the security manager
1120          * @throws NullPointerException     if {@code bytes} or {@code classData} is {@code null}
1121          *
1122          * @since 12
1123          * @jls 12.7 Unloading of Classes and Interfaces
1124          * @see Lookup#privateLookupIn(Class, Lookup)
1125          * @see Lookup#dropLookupMode(int)
1126          */
1127         public Class<?> defineClassWithClassData(byte[] bytes, Object classData, ClassProperty... props)
1128                 throws IllegalAccessException
1129         {
1130             Objects.requireNonNull(bytes);
1131             Objects.requireNonNull(classData);
1132 
1133             // Is it ever possible to create Lookup for int.class or Object[].class?
1134             assert !lookupClass.isPrimitive() && !lookupClass.isArray();
1135 
1136             if ((lookupModes() & PACKAGE) == 0){
1137                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1138             }
1139 
1140             Set<ClassProperty> properties;
1141             if (props == null || props.length == 0) {
1142                 properties = EMPTY_PROPS;
1143             } else {
1144                 properties = Set.of(props);
1145             }
1146 
1147             if (properties.contains(NESTMATE) && (lookupModes() & PRIVATE) == 0){
1148                 throw new IllegalAccessException("Lookup does not have PRIVATE access");
1149             }
1150 
1151             assert (lookupModes() & (MODULE | PUBLIC)) != 0;
1152 
1153             SecurityManager sm = System.getSecurityManager();
1154             if (sm != null)
1155                 sm.checkPermission(new RuntimePermission("defineClass"));
1156 
1157             return defineClassWithNoCheck(bytes, classPropertiesToFlags(properties), classData);
1158         }
1159 
1160         private static int classPropertiesToFlags(Set<ClassProperty> props) {
1161             if (props.isEmpty()) return 0;
1162 
1163             int flags = 0;
1164             for (ClassProperty cp : props) {
1165                 flags |= cp.flag;
1166                 if (cp == WEAK) {
1167                     // weak class property implies hidden
1168                     flags |= HIDDEN.flag;
1169                 }
1170             }
1171             return flags;
1172         }
1173 
1174         /**
1175          * Returns the class data associated with this lookup class.
1176          * If this lookup class was defined via
1177          * {@link #defineClassWithClassData(byte[], Object, ClassProperty...)
1178          * defineClassWithClassData(bytes, classData, properties)}
1179          * then the supplied {@code classData} object is returned; otherwise,
1180          * {@code null}.
1181          *
1182          * <p> This method will invoke the static class initializer of
1183          * this lookup class if it has not been initialized.
1184          *
1185          * @apiNote
1186          * A class data can be considered as
1187          * private static unnamed field that has been pre-initialized
1188          * and supplied at define class time.
1189          *
1190          * <p> For example a class can pack one or more pre-initialized objects
1191          * in a {@code List} as the class data and at class initialization
1192          * time unpack them for subsequent access.
1193          * The class data is {@code List.of(o1, o2, o3....)}
1194          * passed to {@link #defineClassWithClassData(byte[], Object, ClassProperty...)} where
1195          * {@code <clinit>} of the class bytes does the following:
1196          *
1197          * <pre>{@code
1198          *     private static final T t;
1199          *     private static final R r;
1200          *     static {
1201          *        List<Object> data = (List<Object>) MethodHandles.lookup().classData();
1202          *        t = (T)data.get(0);
1203          *        r = (R)data.get(1);
1204          *     }
1205          *}</pre>
1206          *
1207          * @return the class data if this lookup class was defined via
1208          * {@link #defineClassWithClassData(byte[], Object, ClassProperty...)}; otherwise {@code null}.
1209          *
1210          * @throws IllegalAccessException if this lookup does not have {@code PRIVATE} access
1211          * @since 12
1212          */
1213         public Object classData() throws IllegalAccessException {
1214             if ((lookupModes() & PRIVATE) == 0){
1215                 throw new IllegalAccessException("Lookup does not have PRIVATE access");
1216             }
1217 
1218             // should we allow clearing?  getAndClearClassData
1219             return MethodHandleNatives.classData(lookupClass);
1220         }
1221 
1222         // package-private
1223         static final int HIDDEN_NESTMATE = NESTMATE_CLASS|NONFINDABLE_CLASS|ACCESS_VM_ANNOTATIONS;
1224         static final int WEAK_HIDDEN_NESTMATE =  WEAK_CLASS|NESTMATE_CLASS|NONFINDABLE_CLASS|ACCESS_VM_ANNOTATIONS;
1225         static final Set<ClassProperty> EMPTY_PROPS = Set.of();
1226 
1227         Class<?> defineClassWithNoCheck(byte[] bytes, int flags) {
1228             return defineClassWithNoCheck(bytes, flags, null);
1229         }
1230 
1231         Class<?> defineClassWithNoCheck(byte[] bytes, int flags, Object classData) {
1232             // Can't use lambda during bootstrapping
1233             // parse class bytes to get class name (in internal form)
1234             bytes = bytes.clone();
1235             String name;
1236             try {
1237                 ClassReader reader = new ClassReader(bytes);
1238                 name = reader.getClassName();
1239             } catch (RuntimeException e) {
1240                 // ASM exceptions are poorly specified
1241                 ClassFormatError cfe = new ClassFormatError();
1242                 cfe.initCause(e);
1243                 throw cfe;
1244             }
1245 
1246             // get package and class name in binary form
1247             String cn, pn;
1248             int index = name.lastIndexOf('/');
1249             if (index == -1) {
1250                 cn = name;
1251                 pn = "";
1252             } else {
1253                 cn = name.replace('/', '.');
1254                 pn = cn.substring(0, index);
1255             }
1256             if (!pn.equals(lookupClass.getPackageName())) {
1257                 throw new IllegalArgumentException(cn + " not in same package as lookup class: " + lookupClass.getName());
1258             }
1259 
1260             if ((flags & NONFINDABLE_CLASS) != 0) {
1261                 // ## TODO use '/' as in the name of the VM anonymous class.
1262                 cn = cn + '\\' + ++seq;
1263             }
1264 
1265             // invoke the class loader's defineClass method
1266             ClassLoader loader = lookupClass.getClassLoader();
1267             ProtectionDomain pd = (loader != null) ? lookupClassProtectionDomain() : null;
1268             Class<?> clazz = JLA.defineClass(loader, lookupClass, cn, bytes, pd, flags, classData);
1269             assert clazz.getClassLoader() == lookupClass.getClassLoader()
1270                    && clazz.getPackageName().equals(lookupClass.getPackageName());
1271 
1272             return clazz;
1273         }
1274 
1275         private static volatile int seq = 0;
1276 
1277         private ProtectionDomain lookupClassProtectionDomain() {
1278             ProtectionDomain pd = cachedProtectionDomain;
1279             if (pd == null) {
1280                 cachedProtectionDomain = pd = JLA.protectionDomain(lookupClass);
1281             }
1282             return pd;
1283         }
1284 
1285         // cached protection domain
1286         private volatile ProtectionDomain cachedProtectionDomain;
1287 
1288         // Make sure outer class is initialized first.
1289         static { IMPL_NAMES.getClass(); }
1290 
1291         /** Package-private version of lookup which is trusted. */
1292         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
1293 
1294         /** Version of lookup which is trusted minimally.
1295          *  It can only be used to create method handles to publicly accessible
1296          *  members in packages that are exported unconditionally.
1297          */
1298         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, (PUBLIC|UNCONDITIONAL));
1299 
1300         static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
1301 
1302         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
1303             String name = lookupClass.getName();
1304             if (name.startsWith("java.lang.invoke."))
1305                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
1306         }
1307 
1308         /**
1309          * Displays the name of the class from which lookups are to be made.
1310          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
1311          * If there are restrictions on the access permitted to this lookup,
1312          * this is indicated by adding a suffix to the class name, consisting
1313          * of a slash and a keyword.  The keyword represents the strongest
1314          * allowed access, and is chosen as follows:
1315          * <ul>
1316          * <li>If no access is allowed, the suffix is "/noaccess".
1317          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
1318          * <li>If only public access and unconditional access are allowed, the suffix is "/publicLookup".
1319          * <li>If only public and module access are allowed, the suffix is "/module".
1320          * <li>If only public, module and package access are allowed, the suffix is "/package".
1321          * <li>If only public, module, package, and private access are allowed, the suffix is "/private".
1322          * </ul>
1323          * If none of the above cases apply, it is the case that full
1324          * access (public, module, package, private, and protected) is allowed.
1325          * In this case, no suffix is added.
1326          * This is true only of an object obtained originally from
1327          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
1328          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
1329          * always have restricted access, and will display a suffix.
1330          * <p>
1331          * (It may seem strange that protected access should be
1332          * stronger than private access.  Viewed independently from
1333          * package access, protected access is the first to be lost,
1334          * because it requires a direct subclass relationship between
1335          * caller and callee.)
1336          * @see #in
1337          *
1338          * @revised 9
1339          * @spec JPMS
1340          */
1341         @Override
1342         public String toString() {
1343             String cname = lookupClass.getName();
1344             switch (allowedModes) {
1345             case 0:  // no privileges
1346                 return cname + "/noaccess";
1347             case PUBLIC:
1348                 return cname + "/public";
1349             case PUBLIC|UNCONDITIONAL:
1350                 return cname  + "/publicLookup";
1351             case PUBLIC|MODULE:
1352                 return cname + "/module";
1353             case PUBLIC|MODULE|PACKAGE:
1354                 return cname + "/package";
1355             case FULL_POWER_MODES & ~PROTECTED:
1356                 return cname + "/private";
1357             case FULL_POWER_MODES:
1358                 return cname;
1359             case TRUSTED:
1360                 return "/trusted";  // internal only; not exported
1361             default:  // Should not happen, but it's a bitfield...
1362                 cname = cname + "/" + Integer.toHexString(allowedModes);
1363                 assert(false) : cname;
1364                 return cname;
1365             }
1366         }
1367 
1368         /**
1369          * Produces a method handle for a static method.
1370          * The type of the method handle will be that of the method.
1371          * (Since static methods do not take receivers, there is no
1372          * additional receiver argument inserted into the method handle type,
1373          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
1374          * The method and all its argument types must be accessible to the lookup object.
1375          * <p>
1376          * The returned method handle will have
1377          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1378          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1379          * <p>
1380          * If the returned method handle is invoked, the method's class will
1381          * be initialized, if it has not already been initialized.
1382          * <p><b>Example:</b>
1383          * <blockquote><pre>{@code
1384 import static java.lang.invoke.MethodHandles.*;
1385 import static java.lang.invoke.MethodType.*;
1386 ...
1387 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
1388   "asList", methodType(List.class, Object[].class));
1389 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
1390          * }</pre></blockquote>
1391          * @param refc the class from which the method is accessed
1392          * @param name the name of the method
1393          * @param type the type of the method
1394          * @return the desired method handle
1395          * @throws NoSuchMethodException if the method does not exist
1396          * @throws IllegalAccessException if access checking fails,
1397          *                                or if the method is not {@code static},
1398          *                                or if the method's variable arity modifier bit
1399          *                                is set and {@code asVarargsCollector} fails
1400          * @exception SecurityException if a security manager is present and it
1401          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1402          * @throws NullPointerException if any argument is null
1403          */
1404         public
1405         MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1406             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
1407             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method));
1408         }
1409 
1410         /**
1411          * Produces a method handle for a virtual method.
1412          * The type of the method handle will be that of the method,
1413          * with the receiver type (usually {@code refc}) prepended.
1414          * The method and all its argument types must be accessible to the lookup object.
1415          * <p>
1416          * When called, the handle will treat the first argument as a receiver
1417          * and, for non-private methods, dispatch on the receiver's type to determine which method
1418          * implementation to enter.
1419          * For private methods the named method in {@code refc} will be invoked on the receiver.
1420          * (The dispatching action is identical with that performed by an
1421          * {@code invokevirtual} or {@code invokeinterface} instruction.)
1422          * <p>
1423          * The first argument will be of type {@code refc} if the lookup
1424          * class has full privileges to access the member.  Otherwise
1425          * the member must be {@code protected} and the first argument
1426          * will be restricted in type to the lookup class.
1427          * <p>
1428          * The returned method handle will have
1429          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1430          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1431          * <p>
1432          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
1433          * instructions and method handles produced by {@code findVirtual},
1434          * if the class is {@code MethodHandle} and the name string is
1435          * {@code invokeExact} or {@code invoke}, the resulting
1436          * method handle is equivalent to one produced by
1437          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
1438          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
1439          * with the same {@code type} argument.
1440          * <p>
1441          * If the class is {@code VarHandle} and the name string corresponds to
1442          * the name of a signature-polymorphic access mode method, the resulting
1443          * method handle is equivalent to one produced by
1444          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
1445          * the access mode corresponding to the name string and with the same
1446          * {@code type} arguments.
1447          * <p>
1448          * <b>Example:</b>
1449          * <blockquote><pre>{@code
1450 import static java.lang.invoke.MethodHandles.*;
1451 import static java.lang.invoke.MethodType.*;
1452 ...
1453 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
1454   "concat", methodType(String.class, String.class));
1455 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
1456   "hashCode", methodType(int.class));
1457 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
1458   "hashCode", methodType(int.class));
1459 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
1460 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
1461 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
1462 // interface method:
1463 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
1464   "subSequence", methodType(CharSequence.class, int.class, int.class));
1465 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
1466 // constructor "internal method" must be accessed differently:
1467 MethodType MT_newString = methodType(void.class); //()V for new String()
1468 try { assertEquals("impossible", lookup()
1469         .findVirtual(String.class, "<init>", MT_newString));
1470  } catch (NoSuchMethodException ex) { } // OK
1471 MethodHandle MH_newString = publicLookup()
1472   .findConstructor(String.class, MT_newString);
1473 assertEquals("", (String) MH_newString.invokeExact());
1474          * }</pre></blockquote>
1475          *
1476          * @param refc the class or interface from which the method is accessed
1477          * @param name the name of the method
1478          * @param type the type of the method, with the receiver argument omitted
1479          * @return the desired method handle
1480          * @throws NoSuchMethodException if the method does not exist
1481          * @throws IllegalAccessException if access checking fails,
1482          *                                or if the method is {@code static},
1483          *                                or if the method's variable arity modifier bit
1484          *                                is set and {@code asVarargsCollector} fails
1485          * @exception SecurityException if a security manager is present and it
1486          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1487          * @throws NullPointerException if any argument is null
1488          */
1489         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1490             if (refc == MethodHandle.class) {
1491                 MethodHandle mh = findVirtualForMH(name, type);
1492                 if (mh != null)  return mh;
1493             } else if (refc == VarHandle.class) {
1494                 MethodHandle mh = findVirtualForVH(name, type);
1495                 if (mh != null)  return mh;
1496             }
1497             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
1498             MemberName method = resolveOrFail(refKind, refc, name, type);
1499             return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
1500         }
1501         private MethodHandle findVirtualForMH(String name, MethodType type) {
1502             // these names require special lookups because of the implicit MethodType argument
1503             if ("invoke".equals(name))
1504                 return invoker(type);
1505             if ("invokeExact".equals(name))
1506                 return exactInvoker(type);
1507             assert(!MemberName.isMethodHandleInvokeName(name));
1508             return null;
1509         }
1510         private MethodHandle findVirtualForVH(String name, MethodType type) {
1511             try {
1512                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
1513             } catch (IllegalArgumentException e) {
1514                 return null;
1515             }
1516         }
1517 
1518         /**
1519          * Produces a method handle which creates an object and initializes it, using
1520          * the constructor of the specified type.
1521          * The parameter types of the method handle will be those of the constructor,
1522          * while the return type will be a reference to the constructor's class.
1523          * The constructor and all its argument types must be accessible to the lookup object.
1524          * <p>
1525          * The requested type must have a return type of {@code void}.
1526          * (This is consistent with the JVM's treatment of constructor type descriptors.)
1527          * <p>
1528          * The returned method handle will have
1529          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1530          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
1531          * <p>
1532          * If the returned method handle is invoked, the constructor's class will
1533          * be initialized, if it has not already been initialized.
1534          * <p><b>Example:</b>
1535          * <blockquote><pre>{@code
1536 import static java.lang.invoke.MethodHandles.*;
1537 import static java.lang.invoke.MethodType.*;
1538 ...
1539 MethodHandle MH_newArrayList = publicLookup().findConstructor(
1540   ArrayList.class, methodType(void.class, Collection.class));
1541 Collection orig = Arrays.asList("x", "y");
1542 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
1543 assert(orig != copy);
1544 assertEquals(orig, copy);
1545 // a variable-arity constructor:
1546 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
1547   ProcessBuilder.class, methodType(void.class, String[].class));
1548 ProcessBuilder pb = (ProcessBuilder)
1549   MH_newProcessBuilder.invoke("x", "y", "z");
1550 assertEquals("[x, y, z]", pb.command().toString());
1551          * }</pre></blockquote>
1552          * @param refc the class or interface from which the method is accessed
1553          * @param type the type of the method, with the receiver argument omitted, and a void return type
1554          * @return the desired method handle
1555          * @throws NoSuchMethodException if the constructor does not exist
1556          * @throws IllegalAccessException if access checking fails
1557          *                                or if the method's variable arity modifier bit
1558          *                                is set and {@code asVarargsCollector} fails
1559          * @exception SecurityException if a security manager is present and it
1560          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1561          * @throws NullPointerException if any argument is null
1562          */
1563         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1564             if (refc.isArray()) {
1565                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
1566             }
1567             String name = "<init>";
1568             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
1569             return getDirectConstructor(refc, ctor);
1570         }
1571 
1572         /**
1573          * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static
1574          * initializer of the class is not run.
1575          * <p>
1576          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, its class
1577          * loader, and the {@linkplain #lookupModes() lookup modes}. In particular, the method first attempts to
1578          * load the requested class, and then determines whether the class is accessible to this lookup object.
1579          *
1580          * @param targetName the fully qualified name of the class to be looked up.
1581          * @return the requested class.
1582          * @exception SecurityException if a security manager is present and it
1583          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1584          * @throws LinkageError if the linkage fails
1585          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader
1586          *                                or the class is not {@linkplain Class#isHidden hidden}
1587          * @throws IllegalAccessException if the class is not accessible, using the allowed access modes.
1588 
1589          * @since 9
1590          * @see Class#isHidden
1591          */
1592         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
1593             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
1594             return accessClass(targetClass);
1595         }
1596 
1597         /**
1598          * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The
1599          * static initializer of the class is not run.
1600          * <p>
1601          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class} and the
1602          * {@linkplain #lookupModes() lookup modes}.
1603          *
1604          * @param targetClass the class to be access-checked
1605          *
1606          * @return the class that has been access-checked
1607          *
1608          * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access
1609          * modes.
1610          * @exception SecurityException if a security manager is present and it
1611          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1612          * @since 9
1613          */
1614         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
1615             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) {
1616                 throw new MemberName(targetClass).makeAccessException("access violation", this);
1617             }
1618             checkSecurityManager(targetClass, null);
1619             return targetClass;
1620         }
1621 
1622         /**
1623          * Produces an early-bound method handle for a virtual method.
1624          * It will bypass checks for overriding methods on the receiver,
1625          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1626          * instruction from within the explicitly specified {@code specialCaller}.
1627          * The type of the method handle will be that of the method,
1628          * with a suitably restricted receiver type prepended.
1629          * (The receiver type will be {@code specialCaller} or a subtype.)
1630          * The method and all its argument types must be accessible
1631          * to the lookup object.
1632          * <p>
1633          * Before method resolution,
1634          * if the explicitly specified caller class is not identical with the
1635          * lookup class, or if this lookup object does not have
1636          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1637          * privileges, the access fails.
1638          * <p>
1639          * The returned method handle will have
1640          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1641          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1642          * <p style="font-size:smaller;">
1643          * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
1644          * even though the {@code invokespecial} instruction can refer to them
1645          * in special circumstances.  Use {@link #findConstructor findConstructor}
1646          * to access instance initialization methods in a safe manner.)</em>
1647          * <p><b>Example:</b>
1648          * <blockquote><pre>{@code
1649 import static java.lang.invoke.MethodHandles.*;
1650 import static java.lang.invoke.MethodType.*;
1651 ...
1652 static class Listie extends ArrayList {
1653   public String toString() { return "[wee Listie]"; }
1654   static Lookup lookup() { return MethodHandles.lookup(); }
1655 }
1656 ...
1657 // no access to constructor via invokeSpecial:
1658 MethodHandle MH_newListie = Listie.lookup()
1659   .findConstructor(Listie.class, methodType(void.class));
1660 Listie l = (Listie) MH_newListie.invokeExact();
1661 try { assertEquals("impossible", Listie.lookup().findSpecial(
1662         Listie.class, "<init>", methodType(void.class), Listie.class));
1663  } catch (NoSuchMethodException ex) { } // OK
1664 // access to super and self methods via invokeSpecial:
1665 MethodHandle MH_super = Listie.lookup().findSpecial(
1666   ArrayList.class, "toString" , methodType(String.class), Listie.class);
1667 MethodHandle MH_this = Listie.lookup().findSpecial(
1668   Listie.class, "toString" , methodType(String.class), Listie.class);
1669 MethodHandle MH_duper = Listie.lookup().findSpecial(
1670   Object.class, "toString" , methodType(String.class), Listie.class);
1671 assertEquals("[]", (String) MH_super.invokeExact(l));
1672 assertEquals(""+l, (String) MH_this.invokeExact(l));
1673 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
1674 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
1675         String.class, "toString", methodType(String.class), Listie.class));
1676  } catch (IllegalAccessException ex) { } // OK
1677 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
1678 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
1679          * }</pre></blockquote>
1680          *
1681          * @param refc the class or interface from which the method is accessed
1682          * @param name the name of the method (which must not be "&lt;init&gt;")
1683          * @param type the type of the method, with the receiver argument omitted
1684          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
1685          * @return the desired method handle
1686          * @throws NoSuchMethodException if the method does not exist
1687          * @throws IllegalAccessException if access checking fails,
1688          *                                or if the method is {@code static},
1689          *                                or if the method's variable arity modifier bit
1690          *                                is set and {@code asVarargsCollector} fails
1691          * @exception SecurityException if a security manager is present and it
1692          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1693          * @throws NullPointerException if any argument is null
1694          */
1695         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
1696                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
1697             checkSpecialCaller(specialCaller, refc);
1698             Lookup specialLookup = this.in(specialCaller);
1699             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
1700             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1701         }
1702 
1703         /**
1704          * Produces a method handle giving read access to a non-static field.
1705          * The type of the method handle will have a return type of the field's
1706          * value type.
1707          * The method handle's single argument will be the instance containing
1708          * the field.
1709          * Access checking is performed immediately on behalf of the lookup class.
1710          * @param refc the class or interface from which the method is accessed
1711          * @param name the field's name
1712          * @param type the field's type
1713          * @return a method handle which can load values from the field
1714          * @throws NoSuchFieldException if the field does not exist
1715          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1716          * @exception SecurityException if a security manager is present and it
1717          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1718          * @throws NullPointerException if any argument is null
1719          * @see #findVarHandle(Class, String, Class)
1720          */
1721         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1722             MemberName field = resolveOrFail(REF_getField, refc, name, type);
1723             return getDirectField(REF_getField, refc, field);
1724         }
1725 
1726         /**
1727          * Produces a method handle giving write access to a non-static field.
1728          * The type of the method handle will have a void return type.
1729          * The method handle will take two arguments, the instance containing
1730          * the field, and the value to be stored.
1731          * The second argument will be of the field's value type.
1732          * Access checking is performed immediately on behalf of the lookup class.
1733          * @param refc the class or interface from which the method is accessed
1734          * @param name the field's name
1735          * @param type the field's type
1736          * @return a method handle which can store values into the field
1737          * @throws NoSuchFieldException if the field does not exist
1738          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1739          *                                or {@code final}
1740          * @exception SecurityException if a security manager is present and it
1741          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1742          * @throws NullPointerException if any argument is null
1743          * @see #findVarHandle(Class, String, Class)
1744          */
1745         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1746             MemberName field = resolveOrFail(REF_putField, refc, name, type);
1747             return getDirectField(REF_putField, refc, field);
1748         }
1749 
1750         /**
1751          * Produces a VarHandle giving access to a non-static field {@code name}
1752          * of type {@code type} declared in a class of type {@code recv}.
1753          * The VarHandle's variable type is {@code type} and it has one
1754          * coordinate type, {@code recv}.
1755          * <p>
1756          * Access checking is performed immediately on behalf of the lookup
1757          * class.
1758          * <p>
1759          * Certain access modes of the returned VarHandle are unsupported under
1760          * the following conditions:
1761          * <ul>
1762          * <li>if the field is declared {@code final}, then the write, atomic
1763          *     update, numeric atomic update, and bitwise atomic update access
1764          *     modes are unsupported.
1765          * <li>if the field type is anything other than {@code byte},
1766          *     {@code short}, {@code char}, {@code int}, {@code long},
1767          *     {@code float}, or {@code double} then numeric atomic update
1768          *     access modes are unsupported.
1769          * <li>if the field type is anything other than {@code boolean},
1770          *     {@code byte}, {@code short}, {@code char}, {@code int} or
1771          *     {@code long} then bitwise atomic update access modes are
1772          *     unsupported.
1773          * </ul>
1774          * <p>
1775          * If the field is declared {@code volatile} then the returned VarHandle
1776          * will override access to the field (effectively ignore the
1777          * {@code volatile} declaration) in accordance to its specified
1778          * access modes.
1779          * <p>
1780          * If the field type is {@code float} or {@code double} then numeric
1781          * and atomic update access modes compare values using their bitwise
1782          * representation (see {@link Float#floatToRawIntBits} and
1783          * {@link Double#doubleToRawLongBits}, respectively).
1784          * @apiNote
1785          * Bitwise comparison of {@code float} values or {@code double} values,
1786          * as performed by the numeric and atomic update access modes, differ
1787          * from the primitive {@code ==} operator and the {@link Float#equals}
1788          * and {@link Double#equals} methods, specifically with respect to
1789          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
1790          * Care should be taken when performing a compare and set or a compare
1791          * and exchange operation with such values since the operation may
1792          * unexpectedly fail.
1793          * There are many possible NaN values that are considered to be
1794          * {@code NaN} in Java, although no IEEE 754 floating-point operation
1795          * provided by Java can distinguish between them.  Operation failure can
1796          * occur if the expected or witness value is a NaN value and it is
1797          * transformed (perhaps in a platform specific manner) into another NaN
1798          * value, and thus has a different bitwise representation (see
1799          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
1800          * details).
1801          * The values {@code -0.0} and {@code +0.0} have different bitwise
1802          * representations but are considered equal when using the primitive
1803          * {@code ==} operator.  Operation failure can occur if, for example, a
1804          * numeric algorithm computes an expected value to be say {@code -0.0}
1805          * and previously computed the witness value to be say {@code +0.0}.
1806          * @param recv the receiver class, of type {@code R}, that declares the
1807          * non-static field
1808          * @param name the field's name
1809          * @param type the field's type, of type {@code T}
1810          * @return a VarHandle giving access to non-static fields.
1811          * @throws NoSuchFieldException if the field does not exist
1812          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1813          * @exception SecurityException if a security manager is present and it
1814          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1815          * @throws NullPointerException if any argument is null
1816          * @since 9
1817          */
1818         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1819             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
1820             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
1821             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
1822         }
1823 
1824         /**
1825          * Produces a method handle giving read access to a static field.
1826          * The type of the method handle will have a return type of the field's
1827          * value type.
1828          * The method handle will take no arguments.
1829          * Access checking is performed immediately on behalf of the lookup class.
1830          * <p>
1831          * If the returned method handle is invoked, the field's class will
1832          * be initialized, if it has not already been initialized.
1833          * @param refc the class or interface from which the method is accessed
1834          * @param name the field's name
1835          * @param type the field's type
1836          * @return a method handle which can load values from the field
1837          * @throws NoSuchFieldException if the field does not exist
1838          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1839          * @exception SecurityException if a security manager is present and it
1840          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1841          * @throws NullPointerException if any argument is null
1842          */
1843         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1844             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
1845             return getDirectField(REF_getStatic, refc, field);
1846         }
1847 
1848         /**
1849          * Produces a method handle giving write access to a static field.
1850          * The type of the method handle will have a void return type.
1851          * The method handle will take a single
1852          * argument, of the field's value type, the value to be stored.
1853          * Access checking is performed immediately on behalf of the lookup class.
1854          * <p>
1855          * If the returned method handle is invoked, the field's class will
1856          * be initialized, if it has not already been initialized.
1857          * @param refc the class or interface from which the method is accessed
1858          * @param name the field's name
1859          * @param type the field's type
1860          * @return a method handle which can store values into the field
1861          * @throws NoSuchFieldException if the field does not exist
1862          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1863          *                                or is {@code final}
1864          * @exception SecurityException if a security manager is present and it
1865          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1866          * @throws NullPointerException if any argument is null
1867          */
1868         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1869             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
1870             return getDirectField(REF_putStatic, refc, field);
1871         }
1872 
1873         /**
1874          * Produces a VarHandle giving access to a static field {@code name} of
1875          * type {@code type} declared in a class of type {@code decl}.
1876          * The VarHandle's variable type is {@code type} and it has no
1877          * coordinate types.
1878          * <p>
1879          * Access checking is performed immediately on behalf of the lookup
1880          * class.
1881          * <p>
1882          * If the returned VarHandle is operated on, the declaring class will be
1883          * initialized, if it has not already been initialized.
1884          * <p>
1885          * Certain access modes of the returned VarHandle are unsupported under
1886          * the following conditions:
1887          * <ul>
1888          * <li>if the field is declared {@code final}, then the write, atomic
1889          *     update, numeric atomic update, and bitwise atomic update access
1890          *     modes are unsupported.
1891          * <li>if the field type is anything other than {@code byte},
1892          *     {@code short}, {@code char}, {@code int}, {@code long},
1893          *     {@code float}, or {@code double}, then numeric atomic update
1894          *     access modes are unsupported.
1895          * <li>if the field type is anything other than {@code boolean},
1896          *     {@code byte}, {@code short}, {@code char}, {@code int} or
1897          *     {@code long} then bitwise atomic update access modes are
1898          *     unsupported.
1899          * </ul>
1900          * <p>
1901          * If the field is declared {@code volatile} then the returned VarHandle
1902          * will override access to the field (effectively ignore the
1903          * {@code volatile} declaration) in accordance to its specified
1904          * access modes.
1905          * <p>
1906          * If the field type is {@code float} or {@code double} then numeric
1907          * and atomic update access modes compare values using their bitwise
1908          * representation (see {@link Float#floatToRawIntBits} and
1909          * {@link Double#doubleToRawLongBits}, respectively).
1910          * @apiNote
1911          * Bitwise comparison of {@code float} values or {@code double} values,
1912          * as performed by the numeric and atomic update access modes, differ
1913          * from the primitive {@code ==} operator and the {@link Float#equals}
1914          * and {@link Double#equals} methods, specifically with respect to
1915          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
1916          * Care should be taken when performing a compare and set or a compare
1917          * and exchange operation with such values since the operation may
1918          * unexpectedly fail.
1919          * There are many possible NaN values that are considered to be
1920          * {@code NaN} in Java, although no IEEE 754 floating-point operation
1921          * provided by Java can distinguish between them.  Operation failure can
1922          * occur if the expected or witness value is a NaN value and it is
1923          * transformed (perhaps in a platform specific manner) into another NaN
1924          * value, and thus has a different bitwise representation (see
1925          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
1926          * details).
1927          * The values {@code -0.0} and {@code +0.0} have different bitwise
1928          * representations but are considered equal when using the primitive
1929          * {@code ==} operator.  Operation failure can occur if, for example, a
1930          * numeric algorithm computes an expected value to be say {@code -0.0}
1931          * and previously computed the witness value to be say {@code +0.0}.
1932          * @param decl the class that declares the static field
1933          * @param name the field's name
1934          * @param type the field's type, of type {@code T}
1935          * @return a VarHandle giving access to a static field
1936          * @throws NoSuchFieldException if the field does not exist
1937          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1938          * @exception SecurityException if a security manager is present and it
1939          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1940          * @throws NullPointerException if any argument is null
1941          * @since 9
1942          */
1943         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1944             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
1945             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
1946             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
1947         }
1948 
1949         /**
1950          * Produces an early-bound method handle for a non-static method.
1951          * The receiver must have a supertype {@code defc} in which a method
1952          * of the given name and type is accessible to the lookup class.
1953          * The method and all its argument types must be accessible to the lookup object.
1954          * The type of the method handle will be that of the method,
1955          * without any insertion of an additional receiver parameter.
1956          * The given receiver will be bound into the method handle,
1957          * so that every call to the method handle will invoke the
1958          * requested method on the given receiver.
1959          * <p>
1960          * The returned method handle will have
1961          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1962          * the method's variable arity modifier bit ({@code 0x0080}) is set
1963          * <em>and</em> the trailing array argument is not the only argument.
1964          * (If the trailing array argument is the only argument,
1965          * the given receiver value will be bound to it.)
1966          * <p>
1967          * This is almost equivalent to the following code, with some differences noted below:
1968          * <blockquote><pre>{@code
1969 import static java.lang.invoke.MethodHandles.*;
1970 import static java.lang.invoke.MethodType.*;
1971 ...
1972 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
1973 MethodHandle mh1 = mh0.bindTo(receiver);
1974 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
1975 return mh1;
1976          * }</pre></blockquote>
1977          * where {@code defc} is either {@code receiver.getClass()} or a super
1978          * type of that class, in which the requested method is accessible
1979          * to the lookup class.
1980          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
1981          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
1982          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
1983          * the receiver is restricted by {@code findVirtual} to the lookup class.)
1984          * @param receiver the object from which the method is accessed
1985          * @param name the name of the method
1986          * @param type the type of the method, with the receiver argument omitted
1987          * @return the desired method handle
1988          * @throws NoSuchMethodException if the method does not exist
1989          * @throws IllegalAccessException if access checking fails
1990          *                                or if the method's variable arity modifier bit
1991          *                                is set and {@code asVarargsCollector} fails
1992          * @exception SecurityException if a security manager is present and it
1993          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1994          * @throws NullPointerException if any argument is null
1995          * @see MethodHandle#bindTo
1996          * @see #findVirtual
1997          */
1998         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1999             Class<? extends Object> refc = receiver.getClass(); // may get NPE
2000             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
2001             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerClass(method));
2002             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
2003                 throw new IllegalAccessException("The restricted defining class " +
2004                                                  mh.type().leadingReferenceParameter().getName() +
2005                                                  " is not assignable from receiver class " +
2006                                                  receiver.getClass().getName());
2007             }
2008             return mh.bindArgumentL(0, receiver).setVarargs(method);
2009         }
2010 
2011         /**
2012          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
2013          * to <i>m</i>, if the lookup class has permission.
2014          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
2015          * If <i>m</i> is virtual, overriding is respected on every call.
2016          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
2017          * The type of the method handle will be that of the method,
2018          * with the receiver type prepended (but only if it is non-static).
2019          * If the method's {@code accessible} flag is not set,
2020          * access checking is performed immediately on behalf of the lookup class.
2021          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
2022          * <p>
2023          * The returned method handle will have
2024          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2025          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2026          * <p>
2027          * If <i>m</i> is static, and
2028          * if the returned method handle is invoked, the method's class will
2029          * be initialized, if it has not already been initialized.
2030          * @param m the reflected method
2031          * @return a method handle which can invoke the reflected method
2032          * @throws IllegalAccessException if access checking fails
2033          *                                or if the method's variable arity modifier bit
2034          *                                is set and {@code asVarargsCollector} fails
2035          * @throws NullPointerException if the argument is null
2036          */
2037         public MethodHandle unreflect(Method m) throws IllegalAccessException {
2038             if (m.getDeclaringClass() == MethodHandle.class) {
2039                 MethodHandle mh = unreflectForMH(m);
2040                 if (mh != null)  return mh;
2041             }
2042             if (m.getDeclaringClass() == VarHandle.class) {
2043                 MethodHandle mh = unreflectForVH(m);
2044                 if (mh != null)  return mh;
2045             }
2046             MemberName method = new MemberName(m);
2047             byte refKind = method.getReferenceKind();
2048             if (refKind == REF_invokeSpecial)
2049                 refKind = REF_invokeVirtual;
2050             assert(method.isMethod());
2051             @SuppressWarnings("deprecation")
2052             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
2053             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
2054         }
2055         private MethodHandle unreflectForMH(Method m) {
2056             // these names require special lookups because they throw UnsupportedOperationException
2057             if (MemberName.isMethodHandleInvokeName(m.getName()))
2058                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
2059             return null;
2060         }
2061         private MethodHandle unreflectForVH(Method m) {
2062             // these names require special lookups because they throw UnsupportedOperationException
2063             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
2064                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
2065             return null;
2066         }
2067 
2068         /**
2069          * Produces a method handle for a reflected method.
2070          * It will bypass checks for overriding methods on the receiver,
2071          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
2072          * instruction from within the explicitly specified {@code specialCaller}.
2073          * The type of the method handle will be that of the method,
2074          * with a suitably restricted receiver type prepended.
2075          * (The receiver type will be {@code specialCaller} or a subtype.)
2076          * If the method's {@code accessible} flag is not set,
2077          * access checking is performed immediately on behalf of the lookup class,
2078          * as if {@code invokespecial} instruction were being linked.
2079          * <p>
2080          * Before method resolution,
2081          * if the explicitly specified caller class is not identical with the
2082          * lookup class, or if this lookup object does not have
2083          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
2084          * privileges, the access fails.
2085          * <p>
2086          * The returned method handle will have
2087          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2088          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2089          * @param m the reflected method
2090          * @param specialCaller the class nominally calling the method
2091          * @return a method handle which can invoke the reflected method
2092          * @throws IllegalAccessException if access checking fails,
2093          *                                or if the method is {@code static},
2094          *                                or if the method's variable arity modifier bit
2095          *                                is set and {@code asVarargsCollector} fails
2096          * @throws NullPointerException if any argument is null
2097          */
2098         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
2099             checkSpecialCaller(specialCaller, null);
2100             Lookup specialLookup = this.in(specialCaller);
2101             MemberName method = new MemberName(m, true);
2102             assert(method.isMethod());
2103             // ignore m.isAccessible:  this is a new kind of access
2104             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
2105         }
2106 
2107         /**
2108          * Produces a method handle for a reflected constructor.
2109          * The type of the method handle will be that of the constructor,
2110          * with the return type changed to the declaring class.
2111          * The method handle will perform a {@code newInstance} operation,
2112          * creating a new instance of the constructor's class on the
2113          * arguments passed to the method handle.
2114          * <p>
2115          * If the constructor's {@code accessible} flag is not set,
2116          * access checking is performed immediately on behalf of the lookup class.
2117          * <p>
2118          * The returned method handle will have
2119          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2120          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2121          * <p>
2122          * If the returned method handle is invoked, the constructor's class will
2123          * be initialized, if it has not already been initialized.
2124          * @param c the reflected constructor
2125          * @return a method handle which can invoke the reflected constructor
2126          * @throws IllegalAccessException if access checking fails
2127          *                                or if the method's variable arity modifier bit
2128          *                                is set and {@code asVarargsCollector} fails
2129          * @throws NullPointerException if the argument is null
2130          */
2131         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
2132             MemberName ctor = new MemberName(c);
2133             assert(ctor.isConstructor());
2134             @SuppressWarnings("deprecation")
2135             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
2136             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
2137         }
2138 
2139         /**
2140          * Produces a method handle giving read access to a reflected field.
2141          * The type of the method handle will have a return type of the field's
2142          * value type.
2143          * If the field is {@code static}, the method handle will take no arguments.
2144          * Otherwise, its single argument will be the instance containing
2145          * the field.
2146          * If the {@code Field} object's {@code accessible} flag is not set,
2147          * access checking is performed immediately on behalf of the lookup class.
2148          * <p>
2149          * If the field is static, and
2150          * if the returned method handle is invoked, the field's class will
2151          * be initialized, if it has not already been initialized.
2152          * @param f the reflected field
2153          * @return a method handle which can load values from the reflected field
2154          * @throws IllegalAccessException if access checking fails
2155          * @throws NullPointerException if the argument is null
2156          */
2157         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
2158             return unreflectField(f, false);
2159         }
2160 
2161         /**
2162          * Produces a method handle giving write access to a reflected field.
2163          * The type of the method handle will have a void return type.
2164          * If the field is {@code static}, the method handle will take a single
2165          * argument, of the field's value type, the value to be stored.
2166          * Otherwise, the two arguments will be the instance containing
2167          * the field, and the value to be stored.
2168          * If the {@code Field} object's {@code accessible} flag is not set,
2169          * access checking is performed immediately on behalf of the lookup class.
2170          * <p>
2171          * If the field is {@code final}, write access will not be
2172          * allowed and access checking will fail, except under certain
2173          * narrow circumstances documented for {@link Field#set Field.set}.
2174          * A method handle is returned only if a corresponding call to
2175          * the {@code Field} object's {@code set} method could return
2176          * normally.  In particular, fields which are both {@code static}
2177          * and {@code final} may never be set.
2178          * <p>
2179          * If the field is {@code static}, and
2180          * if the returned method handle is invoked, the field's class will
2181          * be initialized, if it has not already been initialized.
2182          * @param f the reflected field
2183          * @return a method handle which can store values into the reflected field
2184          * @throws IllegalAccessException if access checking fails,
2185          *         or if the field is {@code final} and write access
2186          *         is not enabled on the {@code Field} object
2187          * @throws NullPointerException if the argument is null
2188          */
2189         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
2190             return unreflectField(f, true);
2191         }
2192 
2193         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
2194             MemberName field = new MemberName(f, isSetter);
2195             if (isSetter && field.isStatic() && field.isFinal())
2196                 throw field.makeAccessException("static final field has no write access", this);
2197             assert(isSetter
2198                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
2199                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
2200             @SuppressWarnings("deprecation")
2201             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
2202             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
2203         }
2204 
2205         /**
2206          * Produces a VarHandle giving access to a reflected field {@code f}
2207          * of type {@code T} declared in a class of type {@code R}.
2208          * The VarHandle's variable type is {@code T}.
2209          * If the field is non-static the VarHandle has one coordinate type,
2210          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
2211          * coordinate types.
2212          * <p>
2213          * Access checking is performed immediately on behalf of the lookup
2214          * class, regardless of the value of the field's {@code accessible}
2215          * flag.
2216          * <p>
2217          * If the field is static, and if the returned VarHandle is operated
2218          * on, the field's declaring class will be initialized, if it has not
2219          * already been initialized.
2220          * <p>
2221          * Certain access modes of the returned VarHandle are unsupported under
2222          * the following conditions:
2223          * <ul>
2224          * <li>if the field is declared {@code final}, then the write, atomic
2225          *     update, numeric atomic update, and bitwise atomic update access
2226          *     modes are unsupported.
2227          * <li>if the field type is anything other than {@code byte},
2228          *     {@code short}, {@code char}, {@code int}, {@code long},
2229          *     {@code float}, or {@code double} then numeric atomic update
2230          *     access modes are unsupported.
2231          * <li>if the field type is anything other than {@code boolean},
2232          *     {@code byte}, {@code short}, {@code char}, {@code int} or
2233          *     {@code long} then bitwise atomic update access modes are
2234          *     unsupported.
2235          * </ul>
2236          * <p>
2237          * If the field is declared {@code volatile} then the returned VarHandle
2238          * will override access to the field (effectively ignore the
2239          * {@code volatile} declaration) in accordance to its specified
2240          * access modes.
2241          * <p>
2242          * If the field type is {@code float} or {@code double} then numeric
2243          * and atomic update access modes compare values using their bitwise
2244          * representation (see {@link Float#floatToRawIntBits} and
2245          * {@link Double#doubleToRawLongBits}, respectively).
2246          * @apiNote
2247          * Bitwise comparison of {@code float} values or {@code double} values,
2248          * as performed by the numeric and atomic update access modes, differ
2249          * from the primitive {@code ==} operator and the {@link Float#equals}
2250          * and {@link Double#equals} methods, specifically with respect to
2251          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
2252          * Care should be taken when performing a compare and set or a compare
2253          * and exchange operation with such values since the operation may
2254          * unexpectedly fail.
2255          * There are many possible NaN values that are considered to be
2256          * {@code NaN} in Java, although no IEEE 754 floating-point operation
2257          * provided by Java can distinguish between them.  Operation failure can
2258          * occur if the expected or witness value is a NaN value and it is
2259          * transformed (perhaps in a platform specific manner) into another NaN
2260          * value, and thus has a different bitwise representation (see
2261          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
2262          * details).
2263          * The values {@code -0.0} and {@code +0.0} have different bitwise
2264          * representations but are considered equal when using the primitive
2265          * {@code ==} operator.  Operation failure can occur if, for example, a
2266          * numeric algorithm computes an expected value to be say {@code -0.0}
2267          * and previously computed the witness value to be say {@code +0.0}.
2268          * @param f the reflected field, with a field of type {@code T}, and
2269          * a declaring class of type {@code R}
2270          * @return a VarHandle giving access to non-static fields or a static
2271          * field
2272          * @throws IllegalAccessException if access checking fails
2273          * @throws NullPointerException if the argument is null
2274          * @since 9
2275          */
2276         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
2277             MemberName getField = new MemberName(f, false);
2278             MemberName putField = new MemberName(f, true);
2279             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
2280                                                       f.getDeclaringClass(), getField, putField);
2281         }
2282 
2283         /**
2284          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
2285          * created by this lookup object or a similar one.
2286          * Security and access checks are performed to ensure that this lookup object
2287          * is capable of reproducing the target method handle.
2288          * This means that the cracking may fail if target is a direct method handle
2289          * but was created by an unrelated lookup object.
2290          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
2291          * and was created by a lookup object for a different class.
2292          * @param target a direct method handle to crack into symbolic reference components
2293          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
2294          * @exception SecurityException if a security manager is present and it
2295          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2296          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
2297          * @exception NullPointerException if the target is {@code null}
2298          * @see MethodHandleInfo
2299          * @since 1.8
2300          */
2301         public MethodHandleInfo revealDirect(MethodHandle target) {
2302             MemberName member = target.internalMemberName();
2303             if (member == null || (!member.isResolved() &&
2304                                    !member.isMethodHandleInvoke() &&
2305                                    !member.isVarHandleMethodInvoke()))
2306                 throw newIllegalArgumentException("not a direct method handle");
2307             Class<?> defc = member.getDeclaringClass();
2308             byte refKind = member.getReferenceKind();
2309             assert(MethodHandleNatives.refKindIsValid(refKind));
2310             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
2311                 // Devirtualized method invocation is usually formally virtual.
2312                 // To avoid creating extra MemberName objects for this common case,
2313                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
2314                 refKind = REF_invokeVirtual;
2315             if (refKind == REF_invokeVirtual && defc.isInterface())
2316                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
2317                 refKind = REF_invokeInterface;
2318             // Check SM permissions and member access before cracking.
2319             try {
2320                 checkAccess(refKind, defc, member);
2321                 checkSecurityManager(defc, member);
2322             } catch (IllegalAccessException ex) {
2323                 throw new IllegalArgumentException(ex);
2324             }
2325             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
2326                 Class<?> callerClass = target.internalCallerClass();
2327                 if (!hasPrivateAccess() || callerClass != lookupClass())
2328                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
2329             }
2330             // Produce the handle to the results.
2331             return new InfoFromMemberName(this, member, refKind);
2332         }
2333 
2334         /// Helper methods, all package-private.
2335 
2336         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
2337             checkSymbolicClass(refc);  // do this before attempting to resolve
2338             Objects.requireNonNull(name);
2339             Objects.requireNonNull(type);
2340             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
2341                                             NoSuchFieldException.class);
2342         }
2343 
2344         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2345             checkSymbolicClass(refc);  // do this before attempting to resolve
2346             Objects.requireNonNull(name);
2347             Objects.requireNonNull(type);
2348             checkMethodName(refKind, name);  // NPE check on name
2349             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
2350                                             NoSuchMethodException.class);
2351         }
2352 
2353         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
2354             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
2355             Objects.requireNonNull(member.getName());
2356             Objects.requireNonNull(member.getType());
2357             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
2358                                             ReflectiveOperationException.class);
2359         }
2360 
2361         MemberName resolveOrNull(byte refKind, MemberName member) {
2362             // do this before attempting to resolve
2363             if (!isClassAccessible(member.getDeclaringClass())) {
2364                 return null;
2365             }
2366             Objects.requireNonNull(member.getName());
2367             Objects.requireNonNull(member.getType());
2368             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull());
2369         }
2370 
2371         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
2372             if (!isClassAccessible(refc)) {
2373                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
2374             }
2375         }
2376 
2377         boolean isClassAccessible(Class<?> refc) {
2378             Objects.requireNonNull(refc);
2379             Class<?> caller = lookupClassOrNull();
2380             return caller == null || VerifyAccess.isClassAccessible(refc, caller, allowedModes);
2381         }
2382 
2383         /** Check name for an illegal leading "&lt;" character. */
2384         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
2385             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
2386                 throw new NoSuchMethodException("illegal method name: "+name);
2387         }
2388 
2389 
2390         /**
2391          * Find my trustable caller class if m is a caller sensitive method.
2392          * If this lookup object has private access, then the caller class is the lookupClass.
2393          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
2394          */
2395         Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
2396             Class<?> callerClass = null;
2397             if (MethodHandleNatives.isCallerSensitive(m)) {
2398                 // Only lookups with private access are allowed to resolve caller-sensitive methods
2399                 if (hasPrivateAccess()) {
2400                     callerClass = lookupClass;
2401                 } else {
2402                     throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
2403                 }
2404             }
2405             return callerClass;
2406         }
2407 
2408         /**
2409          * Returns {@code true} if this lookup has {@code PRIVATE} access.
2410          * @return {@code true} if this lookup has {@code PRIVATE} access.
2411          * @since 9
2412          */
2413         public boolean hasPrivateAccess() {
2414             return (allowedModes & PRIVATE) != 0;
2415         }
2416 
2417         /**
2418          * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
2419          * Determines a trustable caller class to compare with refc, the symbolic reference class.
2420          * If this lookup object has private access, then the caller class is the lookupClass.
2421          */
2422         void checkSecurityManager(Class<?> refc, MemberName m) {
2423             SecurityManager smgr = System.getSecurityManager();
2424             if (smgr == null)  return;
2425             if (allowedModes == TRUSTED)  return;
2426 
2427             // Step 1:
2428             boolean fullPowerLookup = hasPrivateAccess();
2429             if (!fullPowerLookup ||
2430                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
2431                 ReflectUtil.checkPackageAccess(refc);
2432             }
2433 
2434             if (m == null) {  // findClass or accessClass
2435                 // Step 2b:
2436                 if (!fullPowerLookup) {
2437                     smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
2438                 }
2439                 return;
2440             }
2441 
2442             // Step 2a:
2443             if (m.isPublic()) return;
2444             if (!fullPowerLookup) {
2445                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
2446             }
2447 
2448             // Step 3:
2449             Class<?> defc = m.getDeclaringClass();
2450             if (!fullPowerLookup && defc != refc) {
2451                 ReflectUtil.checkPackageAccess(defc);
2452             }
2453         }
2454 
2455         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
2456             boolean wantStatic = (refKind == REF_invokeStatic);
2457             String message;
2458             if (m.isConstructor())
2459                 message = "expected a method, not a constructor";
2460             else if (!m.isMethod())
2461                 message = "expected a method";
2462             else if (wantStatic != m.isStatic())
2463                 message = wantStatic ? "expected a static method" : "expected a non-static method";
2464             else
2465                 { checkAccess(refKind, refc, m); return; }
2466             throw m.makeAccessException(message, this);
2467         }
2468 
2469         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
2470             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
2471             String message;
2472             if (wantStatic != m.isStatic())
2473                 message = wantStatic ? "expected a static field" : "expected a non-static field";
2474             else
2475                 { checkAccess(refKind, refc, m); return; }
2476             throw m.makeAccessException(message, this);
2477         }
2478 
2479         /** Check public/protected/private bits on the symbolic reference class and its member. */
2480         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
2481             assert(m.referenceKindIsConsistentWith(refKind) &&
2482                    MethodHandleNatives.refKindIsValid(refKind) &&
2483                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
2484             int allowedModes = this.allowedModes;
2485             if (allowedModes == TRUSTED)  return;
2486             int mods = m.getModifiers();
2487             if (Modifier.isProtected(mods) &&
2488                     refKind == REF_invokeVirtual &&
2489                     m.getDeclaringClass() == Object.class &&
2490                     m.getName().equals("clone") &&
2491                     refc.isArray()) {
2492                 // The JVM does this hack also.
2493                 // (See ClassVerifier::verify_invoke_instructions
2494                 // and LinkResolver::check_method_accessability.)
2495                 // Because the JVM does not allow separate methods on array types,
2496                 // there is no separate method for int[].clone.
2497                 // All arrays simply inherit Object.clone.
2498                 // But for access checking logic, we make Object.clone
2499                 // (normally protected) appear to be public.
2500                 // Later on, when the DirectMethodHandle is created,
2501                 // its leading argument will be restricted to the
2502                 // requested array type.
2503                 // N.B. The return type is not adjusted, because
2504                 // that is *not* the bytecode behavior.
2505                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
2506             }
2507             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
2508                 // cannot "new" a protected ctor in a different package
2509                 mods ^= Modifier.PROTECTED;
2510             }
2511             if (Modifier.isFinal(mods) &&
2512                     MethodHandleNatives.refKindIsSetter(refKind))
2513                 throw m.makeAccessException("unexpected set of a final field", this);
2514             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
2515             if ((requestedModes & allowedModes) != 0) {
2516                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
2517                                                     mods, lookupClass(), allowedModes))
2518                     return;
2519             } else {
2520                 // Protected members can also be checked as if they were package-private.
2521                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
2522                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
2523                     return;
2524             }
2525             throw m.makeAccessException(accessFailedMessage(refc, m), this);
2526         }
2527 
2528         String accessFailedMessage(Class<?> refc, MemberName m) {
2529             Class<?> defc = m.getDeclaringClass();
2530             int mods = m.getModifiers();
2531             // check the class first:
2532             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
2533                                (defc == refc ||
2534                                 Modifier.isPublic(refc.getModifiers())));
2535             if (!classOK && (allowedModes & PACKAGE) != 0) {
2536                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), FULL_POWER_MODES) &&
2537                            (defc == refc ||
2538                             VerifyAccess.isClassAccessible(refc, lookupClass(), FULL_POWER_MODES)));
2539             }
2540             if (!classOK)
2541                 return "class is not public";
2542             if (Modifier.isPublic(mods))
2543                 return "access to public member failed";  // (how?, module not readable?)
2544             if (Modifier.isPrivate(mods))
2545                 return "member is private";
2546             if (Modifier.isProtected(mods))
2547                 return "member is protected";
2548             return "member is private to package";
2549         }
2550 
2551         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
2552             int allowedModes = this.allowedModes;
2553             if (allowedModes == TRUSTED)  return;
2554             if (!hasPrivateAccess()
2555                 || (specialCaller != lookupClass()
2556                        // ensure non-abstract methods in superinterfaces can be special-invoked
2557                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
2558                 throw new MemberName(specialCaller).
2559                     makeAccessException("no private access for invokespecial", this);
2560         }
2561 
2562         private boolean restrictProtectedReceiver(MemberName method) {
2563             // The accessing class only has the right to use a protected member
2564             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
2565             if (!method.isProtected() || method.isStatic()
2566                 || allowedModes == TRUSTED
2567                 || method.getDeclaringClass() == lookupClass()
2568                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
2569                 return false;
2570             return true;
2571         }
2572         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
2573             assert(!method.isStatic());
2574             // receiver type of mh is too wide; narrow to caller
2575             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
2576                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
2577             }
2578             MethodType rawType = mh.type();
2579             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
2580             MethodType narrowType = rawType.changeParameterType(0, caller);
2581             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
2582             assert(mh.viewAsTypeChecks(narrowType, true));
2583             return mh.copyWith(narrowType, mh.form);
2584         }
2585 
2586         /** Check access and get the requested method. */
2587         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> boundCallerClass) throws IllegalAccessException {
2588             final boolean doRestrict    = true;
2589             final boolean checkSecurity = true;
2590             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, boundCallerClass);
2591         }
2592         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
2593         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Class<?> boundCallerClass) throws IllegalAccessException {
2594             final boolean doRestrict    = false;
2595             final boolean checkSecurity = true;
2596             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, boundCallerClass);
2597         }
2598         /** Check access and get the requested method, eliding security manager checks. */
2599         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> boundCallerClass) throws IllegalAccessException {
2600             final boolean doRestrict    = true;
2601             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
2602             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, boundCallerClass);
2603         }
2604         /** Common code for all methods; do not call directly except from immediately above. */
2605         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
2606                                                    boolean checkSecurity,
2607                                                    boolean doRestrict, Class<?> boundCallerClass) throws IllegalAccessException {
2608 
2609             checkMethod(refKind, refc, method);
2610             // Optionally check with the security manager; this isn't needed for unreflect* calls.
2611             if (checkSecurity)
2612                 checkSecurityManager(refc, method);
2613             assert(!method.isMethodHandleInvoke());
2614 
2615             if (refKind == REF_invokeSpecial &&
2616                 refc != lookupClass() &&
2617                 !refc.isInterface() &&
2618                 refc != lookupClass().getSuperclass() &&
2619                 refc.isAssignableFrom(lookupClass())) {
2620                 assert(!method.getName().equals("<init>"));  // not this code path
2621 
2622                 // Per JVMS 6.5, desc. of invokespecial instruction:
2623                 // If the method is in a superclass of the LC,
2624                 // and if our original search was above LC.super,
2625                 // repeat the search (symbolic lookup) from LC.super
2626                 // and continue with the direct superclass of that class,
2627                 // and so forth, until a match is found or no further superclasses exist.
2628                 // FIXME: MemberName.resolve should handle this instead.
2629                 Class<?> refcAsSuper = lookupClass();
2630                 MemberName m2;
2631                 do {
2632                     refcAsSuper = refcAsSuper.getSuperclass();
2633                     m2 = new MemberName(refcAsSuper,
2634                                         method.getName(),
2635                                         method.getMethodType(),
2636                                         REF_invokeSpecial);
2637                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
2638                 } while (m2 == null &&         // no method is found yet
2639                          refc != refcAsSuper); // search up to refc
2640                 if (m2 == null)  throw new InternalError(method.toString());
2641                 method = m2;
2642                 refc = refcAsSuper;
2643                 // redo basic checks
2644                 checkMethod(refKind, refc, method);
2645             }
2646 
2647             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
2648             MethodHandle mh = dmh;
2649             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
2650             if ((doRestrict && refKind == REF_invokeSpecial) ||
2651                     (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method))) {
2652                 mh = restrictReceiver(method, dmh, lookupClass());
2653             }
2654             mh = maybeBindCaller(method, mh, boundCallerClass);
2655             mh = mh.setVarargs(method);
2656             return mh;
2657         }
2658         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
2659                                              Class<?> boundCallerClass)
2660                                              throws IllegalAccessException {
2661             if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
2662                 return mh;
2663             Class<?> hostClass = lookupClass;
2664             if (!hasPrivateAccess())  // caller must have private access
2665                 hostClass = boundCallerClass;  // boundCallerClass came from a security manager style stack walk
2666             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
2667             // Note: caller will apply varargs after this step happens.
2668             return cbmh;
2669         }
2670         /** Check access and get the requested field. */
2671         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
2672             final boolean checkSecurity = true;
2673             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
2674         }
2675         /** Check access and get the requested field, eliding security manager checks. */
2676         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
2677             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
2678             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
2679         }
2680         /** Common code for all fields; do not call directly except from immediately above. */
2681         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
2682                                                   boolean checkSecurity) throws IllegalAccessException {
2683             checkField(refKind, refc, field);
2684             // Optionally check with the security manager; this isn't needed for unreflect* calls.
2685             if (checkSecurity)
2686                 checkSecurityManager(refc, field);
2687             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
2688             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
2689                                     restrictProtectedReceiver(field));
2690             if (doRestrict)
2691                 return restrictReceiver(field, dmh, lookupClass());
2692             return dmh;
2693         }
2694         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
2695                                             Class<?> refc, MemberName getField, MemberName putField)
2696                 throws IllegalAccessException {
2697             final boolean checkSecurity = true;
2698             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
2699         }
2700         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
2701                                                              Class<?> refc, MemberName getField, MemberName putField)
2702                 throws IllegalAccessException {
2703             final boolean checkSecurity = false;
2704             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
2705         }
2706         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
2707                                                   Class<?> refc, MemberName getField, MemberName putField,
2708                                                   boolean checkSecurity) throws IllegalAccessException {
2709             assert getField.isStatic() == putField.isStatic();
2710             assert getField.isGetter() && putField.isSetter();
2711             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
2712             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
2713 
2714             checkField(getRefKind, refc, getField);
2715             if (checkSecurity)
2716                 checkSecurityManager(refc, getField);
2717 
2718             if (!putField.isFinal()) {
2719                 // A VarHandle does not support updates to final fields, any
2720                 // such VarHandle to a final field will be read-only and
2721                 // therefore the following write-based accessibility checks are
2722                 // only required for non-final fields
2723                 checkField(putRefKind, refc, putField);
2724                 if (checkSecurity)
2725                     checkSecurityManager(refc, putField);
2726             }
2727 
2728             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
2729                                   restrictProtectedReceiver(getField));
2730             if (doRestrict) {
2731                 assert !getField.isStatic();
2732                 // receiver type of VarHandle is too wide; narrow to caller
2733                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
2734                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
2735                 }
2736                 refc = lookupClass();
2737             }
2738             return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED);
2739         }
2740         /** Check access and get the requested constructor. */
2741         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
2742             final boolean checkSecurity = true;
2743             return getDirectConstructorCommon(refc, ctor, checkSecurity);
2744         }
2745         /** Check access and get the requested constructor, eliding security manager checks. */
2746         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
2747             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
2748             return getDirectConstructorCommon(refc, ctor, checkSecurity);
2749         }
2750         /** Common code for all constructors; do not call directly except from immediately above. */
2751         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
2752                                                   boolean checkSecurity) throws IllegalAccessException {
2753             assert(ctor.isConstructor());
2754             checkAccess(REF_newInvokeSpecial, refc, ctor);
2755             // Optionally check with the security manager; this isn't needed for unreflect* calls.
2756             if (checkSecurity)
2757                 checkSecurityManager(refc, ctor);
2758             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
2759             return DirectMethodHandle.make(ctor).setVarargs(ctor);
2760         }
2761 
2762         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
2763          */
2764         /*non-public*/
2765         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException {
2766             if (!(type instanceof Class || type instanceof MethodType))
2767                 throw new InternalError("unresolved MemberName");
2768             MemberName member = new MemberName(refKind, defc, name, type);
2769             MethodHandle mh = LOOKASIDE_TABLE.get(member);
2770             if (mh != null) {
2771                 checkSymbolicClass(defc);
2772                 return mh;
2773             }
2774             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
2775                 // Treat MethodHandle.invoke and invokeExact specially.
2776                 mh = findVirtualForMH(member.getName(), member.getMethodType());
2777                 if (mh != null) {
2778                     return mh;
2779                 }
2780             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
2781                 // Treat signature-polymorphic methods on VarHandle specially.
2782                 mh = findVirtualForVH(member.getName(), member.getMethodType());
2783                 if (mh != null) {
2784                     return mh;
2785                 }
2786             }
2787             MemberName resolved = resolveOrFail(refKind, member);
2788             mh = getDirectMethodForConstant(refKind, defc, resolved);
2789             if (mh instanceof DirectMethodHandle
2790                     && canBeCached(refKind, defc, resolved)) {
2791                 MemberName key = mh.internalMemberName();
2792                 if (key != null) {
2793                     key = key.asNormalOriginal();
2794                 }
2795                 if (member.equals(key)) {  // better safe than sorry
2796                     LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
2797                 }
2798             }
2799             return mh;
2800         }
2801         private
2802         boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
2803             if (refKind == REF_invokeSpecial) {
2804                 return false;
2805             }
2806             if (!Modifier.isPublic(defc.getModifiers()) ||
2807                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
2808                     !member.isPublic() ||
2809                     member.isCallerSensitive()) {
2810                 return false;
2811             }
2812             ClassLoader loader = defc.getClassLoader();
2813             if (loader != null) {
2814                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
2815                 boolean found = false;
2816                 while (sysl != null) {
2817                     if (loader == sysl) { found = true; break; }
2818                     sysl = sysl.getParent();
2819                 }
2820                 if (!found) {
2821                     return false;
2822                 }
2823             }
2824             try {
2825                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
2826                     new MemberName(refKind, defc, member.getName(), member.getType()));
2827                 if (resolved2 == null) {
2828                     return false;
2829                 }
2830                 checkSecurityManager(defc, resolved2);
2831             } catch (SecurityException ex) {
2832                 return false;
2833             }
2834             return true;
2835         }
2836         private
2837         MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
2838                 throws ReflectiveOperationException {
2839             if (MethodHandleNatives.refKindIsField(refKind)) {
2840                 return getDirectFieldNoSecurityManager(refKind, defc, member);
2841             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
2842                 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
2843             } else if (refKind == REF_newInvokeSpecial) {
2844                 return getDirectConstructorNoSecurityManager(defc, member);
2845             }
2846             // oops
2847             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
2848         }
2849 
2850         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
2851 
2852         /**
2853          * Property of a class to be defined via the
2854          * {@link Lookup#defineClass(byte[], ClassProperty[]) Lookup.defineClass} method.
2855          *
2856          * @since 12
2857          * @see Lookup#defineClass(byte[], ClassProperty[])
2858          * @see Lookup#defineClassWithClassData(byte[], Object, ClassProperty[])
2859          */
2860         public enum ClassProperty {
2861             /**
2862              * A nestmate is a class that is in the same {@linkplain Class#getNestHost nest}
2863              * of a lookup class.  It has access to the private members of all
2864              * classes and interfaces in the same nest.
2865              *
2866              * @see Class#getNestHost()
2867              */
2868             NESTMATE(NESTMATE_CLASS),
2869 
2870             /**
2871              * A hidden class is a class that cannot be referenced by other
2872              * classes.  A Java Virtual Machine implementation may hide
2873              * the hidden frames from {@linkplain Throwable#getStackTrace()
2874              * stack traces}.
2875              *
2876              * @see Class#isHidden()
2877              * @see StackWalker.Option#SHOW_HIDDEN_FRAMES
2878              */
2879             HIDDEN(NONFINDABLE_CLASS),
2880 
2881             /**
2882              * A weak class is a class that may be unloaded even if
2883              * its defining class loader is
2884              * <a href="../ref/package.html#reachability">reachable</a>.
2885              * A weak class is {@linkplain #HIDDEN hidden}.
2886              *
2887              * @jls 12.7 Unloading of Classes and Interfaces
2888              */
2889             WEAK(WEAK_CLASS);
2890 
2891             /* the flag value is used by VM at define class time */
2892             final int flag;
2893             ClassProperty(int flag) {
2894                 this.flag = flag;
2895             }
2896         }
2897     }
2898 
2899     /**
2900      * Produces a method handle constructing arrays of a desired type,
2901      * as if by the {@code anewarray} bytecode.
2902      * The return type of the method handle will be the array type.
2903      * The type of its sole argument will be {@code int}, which specifies the size of the array.
2904      *
2905      * <p> If the returned method handle is invoked with a negative
2906      * array size, a {@code NegativeArraySizeException} will be thrown.
2907      *
2908      * @param arrayClass an array type
2909      * @return a method handle which can create arrays of the given type
2910      * @throws NullPointerException if the argument is {@code null}
2911      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
2912      * @see java.lang.reflect.Array#newInstance(Class, int)
2913      * @jvms 6.5 {@code anewarray} Instruction
2914      * @since 9
2915      */
2916     public static
2917     MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
2918         if (!arrayClass.isArray()) {
2919             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
2920         }
2921         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
2922                 bindTo(arrayClass.getComponentType());
2923         return ani.asType(ani.type().changeReturnType(arrayClass));
2924     }
2925 
2926     /**
2927      * Produces a method handle returning the length of an array,
2928      * as if by the {@code arraylength} bytecode.
2929      * The type of the method handle will have {@code int} as return type,
2930      * and its sole argument will be the array type.
2931      *
2932      * <p> If the returned method handle is invoked with a {@code null}
2933      * array reference, a {@code NullPointerException} will be thrown.
2934      *
2935      * @param arrayClass an array type
2936      * @return a method handle which can retrieve the length of an array of the given array type
2937      * @throws NullPointerException if the argument is {@code null}
2938      * @throws IllegalArgumentException if arrayClass is not an array type
2939      * @jvms 6.5 {@code arraylength} Instruction
2940      * @since 9
2941      */
2942     public static
2943     MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
2944         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
2945     }
2946 
2947     /**
2948      * Produces a method handle giving read access to elements of an array,
2949      * as if by the {@code aaload} bytecode.
2950      * The type of the method handle will have a return type of the array's
2951      * element type.  Its first argument will be the array type,
2952      * and the second will be {@code int}.
2953      *
2954      * <p> When the returned method handle is invoked,
2955      * the array reference and array index are checked.
2956      * A {@code NullPointerException} will be thrown if the array reference
2957      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
2958      * thrown if the index is negative or if it is greater than or equal to
2959      * the length of the array.
2960      *
2961      * @param arrayClass an array type
2962      * @return a method handle which can load values from the given array type
2963      * @throws NullPointerException if the argument is null
2964      * @throws  IllegalArgumentException if arrayClass is not an array type
2965      * @jvms 6.5 {@code aaload} Instruction
2966      */
2967     public static
2968     MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
2969         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
2970     }
2971 
2972     /**
2973      * Produces a method handle giving write access to elements of an array,
2974      * as if by the {@code astore} bytecode.
2975      * The type of the method handle will have a void return type.
2976      * Its last argument will be the array's element type.
2977      * The first and second arguments will be the array type and int.
2978      *
2979      * <p> When the returned method handle is invoked,
2980      * the array reference and array index are checked.
2981      * A {@code NullPointerException} will be thrown if the array reference
2982      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
2983      * thrown if the index is negative or if it is greater than or equal to
2984      * the length of the array.
2985      *
2986      * @param arrayClass the class of an array
2987      * @return a method handle which can store values into the array type
2988      * @throws NullPointerException if the argument is null
2989      * @throws IllegalArgumentException if arrayClass is not an array type
2990      * @jvms 6.5 {@code aastore} Instruction
2991      */
2992     public static
2993     MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
2994         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
2995     }
2996 
2997     /**
2998      * Produces a VarHandle giving access to elements of an array of type
2999      * {@code arrayClass}.  The VarHandle's variable type is the component type
3000      * of {@code arrayClass} and the list of coordinate types is
3001      * {@code (arrayClass, int)}, where the {@code int} coordinate type
3002      * corresponds to an argument that is an index into an array.
3003      * <p>
3004      * Certain access modes of the returned VarHandle are unsupported under
3005      * the following conditions:
3006      * <ul>
3007      * <li>if the component type is anything other than {@code byte},
3008      *     {@code short}, {@code char}, {@code int}, {@code long},
3009      *     {@code float}, or {@code double} then numeric atomic update access
3010      *     modes are unsupported.
3011      * <li>if the field type is anything other than {@code boolean},
3012      *     {@code byte}, {@code short}, {@code char}, {@code int} or
3013      *     {@code long} then bitwise atomic update access modes are
3014      *     unsupported.
3015      * </ul>
3016      * <p>
3017      * If the component type is {@code float} or {@code double} then numeric
3018      * and atomic update access modes compare values using their bitwise
3019      * representation (see {@link Float#floatToRawIntBits} and
3020      * {@link Double#doubleToRawLongBits}, respectively).
3021      *
3022      * <p> When the returned {@code VarHandle} is invoked,
3023      * the array reference and array index are checked.
3024      * A {@code NullPointerException} will be thrown if the array reference
3025      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
3026      * thrown if the index is negative or if it is greater than or equal to
3027      * the length of the array.
3028      *
3029      * @apiNote
3030      * Bitwise comparison of {@code float} values or {@code double} values,
3031      * as performed by the numeric and atomic update access modes, differ
3032      * from the primitive {@code ==} operator and the {@link Float#equals}
3033      * and {@link Double#equals} methods, specifically with respect to
3034      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3035      * Care should be taken when performing a compare and set or a compare
3036      * and exchange operation with such values since the operation may
3037      * unexpectedly fail.
3038      * There are many possible NaN values that are considered to be
3039      * {@code NaN} in Java, although no IEEE 754 floating-point operation
3040      * provided by Java can distinguish between them.  Operation failure can
3041      * occur if the expected or witness value is a NaN value and it is
3042      * transformed (perhaps in a platform specific manner) into another NaN
3043      * value, and thus has a different bitwise representation (see
3044      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3045      * details).
3046      * The values {@code -0.0} and {@code +0.0} have different bitwise
3047      * representations but are considered equal when using the primitive
3048      * {@code ==} operator.  Operation failure can occur if, for example, a
3049      * numeric algorithm computes an expected value to be say {@code -0.0}
3050      * and previously computed the witness value to be say {@code +0.0}.
3051      * @param arrayClass the class of an array, of type {@code T[]}
3052      * @return a VarHandle giving access to elements of an array
3053      * @throws NullPointerException if the arrayClass is null
3054      * @throws IllegalArgumentException if arrayClass is not an array type
3055      * @since 9
3056      */
3057     public static
3058     VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
3059         return VarHandles.makeArrayElementHandle(arrayClass);
3060     }
3061 
3062     /**
3063      * Produces a VarHandle giving access to elements of a {@code byte[]} array
3064      * viewed as if it were a different primitive array type, such as
3065      * {@code int[]} or {@code long[]}.
3066      * The VarHandle's variable type is the component type of
3067      * {@code viewArrayClass} and the list of coordinate types is
3068      * {@code (byte[], int)}, where the {@code int} coordinate type
3069      * corresponds to an argument that is an index into a {@code byte[]} array.
3070      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
3071      * array, composing bytes to or from a value of the component type of
3072      * {@code viewArrayClass} according to the given endianness.
3073      * <p>
3074      * The supported component types (variables types) are {@code short},
3075      * {@code char}, {@code int}, {@code long}, {@code float} and
3076      * {@code double}.
3077      * <p>
3078      * Access of bytes at a given index will result in an
3079      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
3080      * or greater than the {@code byte[]} array length minus the size (in bytes)
3081      * of {@code T}.
3082      * <p>
3083      * Access of bytes at an index may be aligned or misaligned for {@code T},
3084      * with respect to the underlying memory address, {@code A} say, associated
3085      * with the array and index.
3086      * If access is misaligned then access for anything other than the
3087      * {@code get} and {@code set} access modes will result in an
3088      * {@code IllegalStateException}.  In such cases atomic access is only
3089      * guaranteed with respect to the largest power of two that divides the GCD
3090      * of {@code A} and the size (in bytes) of {@code T}.
3091      * If access is aligned then following access modes are supported and are
3092      * guaranteed to support atomic access:
3093      * <ul>
3094      * <li>read write access modes for all {@code T}, with the exception of
3095      *     access modes {@code get} and {@code set} for {@code long} and
3096      *     {@code double} on 32-bit platforms.
3097      * <li>atomic update access modes for {@code int}, {@code long},
3098      *     {@code float} or {@code double}.
3099      *     (Future major platform releases of the JDK may support additional
3100      *     types for certain currently unsupported access modes.)
3101      * <li>numeric atomic update access modes for {@code int} and {@code long}.
3102      *     (Future major platform releases of the JDK may support additional
3103      *     numeric types for certain currently unsupported access modes.)
3104      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
3105      *     (Future major platform releases of the JDK may support additional
3106      *     numeric types for certain currently unsupported access modes.)
3107      * </ul>
3108      * <p>
3109      * Misaligned access, and therefore atomicity guarantees, may be determined
3110      * for {@code byte[]} arrays without operating on a specific array.  Given
3111      * an {@code index}, {@code T} and it's corresponding boxed type,
3112      * {@code T_BOX}, misalignment may be determined as follows:
3113      * <pre>{@code
3114      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
3115      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
3116      *     alignmentOffset(0, sizeOfT);
3117      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
3118      * boolean isMisaligned = misalignedAtIndex != 0;
3119      * }</pre>
3120      * <p>
3121      * If the variable type is {@code float} or {@code double} then atomic
3122      * update access modes compare values using their bitwise representation
3123      * (see {@link Float#floatToRawIntBits} and
3124      * {@link Double#doubleToRawLongBits}, respectively).
3125      * @param viewArrayClass the view array class, with a component type of
3126      * type {@code T}
3127      * @param byteOrder the endianness of the view array elements, as
3128      * stored in the underlying {@code byte} array
3129      * @return a VarHandle giving access to elements of a {@code byte[]} array
3130      * viewed as if elements corresponding to the components type of the view
3131      * array class
3132      * @throws NullPointerException if viewArrayClass or byteOrder is null
3133      * @throws IllegalArgumentException if viewArrayClass is not an array type
3134      * @throws UnsupportedOperationException if the component type of
3135      * viewArrayClass is not supported as a variable type
3136      * @since 9
3137      */
3138     public static
3139     VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
3140                                      ByteOrder byteOrder) throws IllegalArgumentException {
3141         Objects.requireNonNull(byteOrder);
3142         return VarHandles.byteArrayViewHandle(viewArrayClass,
3143                                               byteOrder == ByteOrder.BIG_ENDIAN);
3144     }
3145 
3146     /**
3147      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
3148      * viewed as if it were an array of elements of a different primitive
3149      * component type to that of {@code byte}, such as {@code int[]} or
3150      * {@code long[]}.
3151      * The VarHandle's variable type is the component type of
3152      * {@code viewArrayClass} and the list of coordinate types is
3153      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
3154      * corresponds to an argument that is an index into a {@code byte[]} array.
3155      * The returned VarHandle accesses bytes at an index in a
3156      * {@code ByteBuffer}, composing bytes to or from a value of the component
3157      * type of {@code viewArrayClass} according to the given endianness.
3158      * <p>
3159      * The supported component types (variables types) are {@code short},
3160      * {@code char}, {@code int}, {@code long}, {@code float} and
3161      * {@code double}.
3162      * <p>
3163      * Access will result in a {@code ReadOnlyBufferException} for anything
3164      * other than the read access modes if the {@code ByteBuffer} is read-only.
3165      * <p>
3166      * Access of bytes at a given index will result in an
3167      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
3168      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
3169      * {@code T}.
3170      * <p>
3171      * Access of bytes at an index may be aligned or misaligned for {@code T},
3172      * with respect to the underlying memory address, {@code A} say, associated
3173      * with the {@code ByteBuffer} and index.
3174      * If access is misaligned then access for anything other than the
3175      * {@code get} and {@code set} access modes will result in an
3176      * {@code IllegalStateException}.  In such cases atomic access is only
3177      * guaranteed with respect to the largest power of two that divides the GCD
3178      * of {@code A} and the size (in bytes) of {@code T}.
3179      * If access is aligned then following access modes are supported and are
3180      * guaranteed to support atomic access:
3181      * <ul>
3182      * <li>read write access modes for all {@code T}, with the exception of
3183      *     access modes {@code get} and {@code set} for {@code long} and
3184      *     {@code double} on 32-bit platforms.
3185      * <li>atomic update access modes for {@code int}, {@code long},
3186      *     {@code float} or {@code double}.
3187      *     (Future major platform releases of the JDK may support additional
3188      *     types for certain currently unsupported access modes.)
3189      * <li>numeric atomic update access modes for {@code int} and {@code long}.
3190      *     (Future major platform releases of the JDK may support additional
3191      *     numeric types for certain currently unsupported access modes.)
3192      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
3193      *     (Future major platform releases of the JDK may support additional
3194      *     numeric types for certain currently unsupported access modes.)
3195      * </ul>
3196      * <p>
3197      * Misaligned access, and therefore atomicity guarantees, may be determined
3198      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
3199      * {@code index}, {@code T} and it's corresponding boxed type,
3200      * {@code T_BOX}, as follows:
3201      * <pre>{@code
3202      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
3203      * ByteBuffer bb = ...
3204      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
3205      * boolean isMisaligned = misalignedAtIndex != 0;
3206      * }</pre>
3207      * <p>
3208      * If the variable type is {@code float} or {@code double} then atomic
3209      * update access modes compare values using their bitwise representation
3210      * (see {@link Float#floatToRawIntBits} and
3211      * {@link Double#doubleToRawLongBits}, respectively).
3212      * @param viewArrayClass the view array class, with a component type of
3213      * type {@code T}
3214      * @param byteOrder the endianness of the view array elements, as
3215      * stored in the underlying {@code ByteBuffer} (Note this overrides the
3216      * endianness of a {@code ByteBuffer})
3217      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
3218      * viewed as if elements corresponding to the components type of the view
3219      * array class
3220      * @throws NullPointerException if viewArrayClass or byteOrder is null
3221      * @throws IllegalArgumentException if viewArrayClass is not an array type
3222      * @throws UnsupportedOperationException if the component type of
3223      * viewArrayClass is not supported as a variable type
3224      * @since 9
3225      */
3226     public static
3227     VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
3228                                       ByteOrder byteOrder) throws IllegalArgumentException {
3229         Objects.requireNonNull(byteOrder);
3230         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
3231                                                    byteOrder == ByteOrder.BIG_ENDIAN);
3232     }
3233 
3234 
3235     /// method handle invocation (reflective style)
3236 
3237     /**
3238      * Produces a method handle which will invoke any method handle of the
3239      * given {@code type}, with a given number of trailing arguments replaced by
3240      * a single trailing {@code Object[]} array.
3241      * The resulting invoker will be a method handle with the following
3242      * arguments:
3243      * <ul>
3244      * <li>a single {@code MethodHandle} target
3245      * <li>zero or more leading values (counted by {@code leadingArgCount})
3246      * <li>an {@code Object[]} array containing trailing arguments
3247      * </ul>
3248      * <p>
3249      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
3250      * the indicated {@code type}.
3251      * That is, if the target is exactly of the given {@code type}, it will behave
3252      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
3253      * is used to convert the target to the required {@code type}.
3254      * <p>
3255      * The type of the returned invoker will not be the given {@code type}, but rather
3256      * will have all parameters except the first {@code leadingArgCount}
3257      * replaced by a single array of type {@code Object[]}, which will be
3258      * the final parameter.
3259      * <p>
3260      * Before invoking its target, the invoker will spread the final array, apply
3261      * reference casts as necessary, and unbox and widen primitive arguments.
3262      * If, when the invoker is called, the supplied array argument does
3263      * not have the correct number of elements, the invoker will throw
3264      * an {@link IllegalArgumentException} instead of invoking the target.
3265      * <p>
3266      * This method is equivalent to the following code (though it may be more efficient):
3267      * <blockquote><pre>{@code
3268 MethodHandle invoker = MethodHandles.invoker(type);
3269 int spreadArgCount = type.parameterCount() - leadingArgCount;
3270 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
3271 return invoker;
3272      * }</pre></blockquote>
3273      * This method throws no reflective or security exceptions.
3274      * @param type the desired target type
3275      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
3276      * @return a method handle suitable for invoking any method handle of the given type
3277      * @throws NullPointerException if {@code type} is null
3278      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
3279      *                  the range from 0 to {@code type.parameterCount()} inclusive,
3280      *                  or if the resulting method handle's type would have
3281      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
3282      */
3283     public static
3284     MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
3285         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
3286             throw newIllegalArgumentException("bad argument count", leadingArgCount);
3287         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
3288         return type.invokers().spreadInvoker(leadingArgCount);
3289     }
3290 
3291     /**
3292      * Produces a special <em>invoker method handle</em> which can be used to
3293      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
3294      * The resulting invoker will have a type which is
3295      * exactly equal to the desired type, except that it will accept
3296      * an additional leading argument of type {@code MethodHandle}.
3297      * <p>
3298      * This method is equivalent to the following code (though it may be more efficient):
3299      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
3300      *
3301      * <p style="font-size:smaller;">
3302      * <em>Discussion:</em>
3303      * Invoker method handles can be useful when working with variable method handles
3304      * of unknown types.
3305      * For example, to emulate an {@code invokeExact} call to a variable method
3306      * handle {@code M}, extract its type {@code T},
3307      * look up the invoker method {@code X} for {@code T},
3308      * and call the invoker method, as {@code X.invoke(T, A...)}.
3309      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
3310      * is unknown.)
3311      * If spreading, collecting, or other argument transformations are required,
3312      * they can be applied once to the invoker {@code X} and reused on many {@code M}
3313      * method handle values, as long as they are compatible with the type of {@code X}.
3314      * <p style="font-size:smaller;">
3315      * <em>(Note:  The invoker method is not available via the Core Reflection API.
3316      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
3317      * on the declared {@code invokeExact} or {@code invoke} method will raise an
3318      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
3319      * <p>
3320      * This method throws no reflective or security exceptions.
3321      * @param type the desired target type
3322      * @return a method handle suitable for invoking any method handle of the given type
3323      * @throws IllegalArgumentException if the resulting method handle's type would have
3324      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
3325      */
3326     public static
3327     MethodHandle exactInvoker(MethodType type) {
3328         return type.invokers().exactInvoker();
3329     }
3330 
3331     /**
3332      * Produces a special <em>invoker method handle</em> which can be used to
3333      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
3334      * The resulting invoker will have a type which is
3335      * exactly equal to the desired type, except that it will accept
3336      * an additional leading argument of type {@code MethodHandle}.
3337      * <p>
3338      * Before invoking its target, if the target differs from the expected type,
3339      * the invoker will apply reference casts as
3340      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
3341      * Similarly, the return value will be converted as necessary.
3342      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
3343      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
3344      * <p>
3345      * This method is equivalent to the following code (though it may be more efficient):
3346      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
3347      * <p style="font-size:smaller;">
3348      * <em>Discussion:</em>
3349      * A {@linkplain MethodType#genericMethodType general method type} is one which
3350      * mentions only {@code Object} arguments and return values.
3351      * An invoker for such a type is capable of calling any method handle
3352      * of the same arity as the general type.
3353      * <p style="font-size:smaller;">
3354      * <em>(Note:  The invoker method is not available via the Core Reflection API.
3355      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
3356      * on the declared {@code invokeExact} or {@code invoke} method will raise an
3357      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
3358      * <p>
3359      * This method throws no reflective or security exceptions.
3360      * @param type the desired target type
3361      * @return a method handle suitable for invoking any method handle convertible to the given type
3362      * @throws IllegalArgumentException if the resulting method handle's type would have
3363      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
3364      */
3365     public static
3366     MethodHandle invoker(MethodType type) {
3367         return type.invokers().genericInvoker();
3368     }
3369 
3370     /**
3371      * Produces a special <em>invoker method handle</em> which can be used to
3372      * invoke a signature-polymorphic access mode method on any VarHandle whose
3373      * associated access mode type is compatible with the given type.
3374      * The resulting invoker will have a type which is exactly equal to the
3375      * desired given type, except that it will accept an additional leading
3376      * argument of type {@code VarHandle}.
3377      *
3378      * @param accessMode the VarHandle access mode
3379      * @param type the desired target type
3380      * @return a method handle suitable for invoking an access mode method of
3381      *         any VarHandle whose access mode type is of the given type.
3382      * @since 9
3383      */
3384     static public
3385     MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
3386         return type.invokers().varHandleMethodExactInvoker(accessMode);
3387     }
3388 
3389     /**
3390      * Produces a special <em>invoker method handle</em> which can be used to
3391      * invoke a signature-polymorphic access mode method on any VarHandle whose
3392      * associated access mode type is compatible with the given type.
3393      * The resulting invoker will have a type which is exactly equal to the
3394      * desired given type, except that it will accept an additional leading
3395      * argument of type {@code VarHandle}.
3396      * <p>
3397      * Before invoking its target, if the access mode type differs from the
3398      * desired given type, the invoker will apply reference casts as necessary
3399      * and box, unbox, or widen primitive values, as if by
3400      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
3401      * converted as necessary.
3402      * <p>
3403      * This method is equivalent to the following code (though it may be more
3404      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
3405      *
3406      * @param accessMode the VarHandle access mode
3407      * @param type the desired target type
3408      * @return a method handle suitable for invoking an access mode method of
3409      *         any VarHandle whose access mode type is convertible to the given
3410      *         type.
3411      * @since 9
3412      */
3413     static public
3414     MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
3415         return type.invokers().varHandleMethodInvoker(accessMode);
3416     }
3417 
3418     static /*non-public*/
3419     MethodHandle basicInvoker(MethodType type) {
3420         return type.invokers().basicInvoker();
3421     }
3422 
3423      /// method handle modification (creation from other method handles)
3424 
3425     /**
3426      * Produces a method handle which adapts the type of the
3427      * given method handle to a new type by pairwise argument and return type conversion.
3428      * The original type and new type must have the same number of arguments.
3429      * The resulting method handle is guaranteed to report a type
3430      * which is equal to the desired new type.
3431      * <p>
3432      * If the original type and new type are equal, returns target.
3433      * <p>
3434      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
3435      * and some additional conversions are also applied if those conversions fail.
3436      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
3437      * if possible, before or instead of any conversions done by {@code asType}:
3438      * <ul>
3439      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
3440      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
3441      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
3442      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
3443      *     the boolean is converted to a byte value, 1 for true, 0 for false.
3444      *     (This treatment follows the usage of the bytecode verifier.)
3445      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
3446      *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
3447      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
3448      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
3449      *     then a Java casting conversion (JLS 5.5) is applied.
3450      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
3451      *     widening and/or narrowing.)
3452      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
3453      *     conversion will be applied at runtime, possibly followed
3454      *     by a Java casting conversion (JLS 5.5) on the primitive value,
3455      *     possibly followed by a conversion from byte to boolean by testing
3456      *     the low-order bit.
3457      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
3458      *     and if the reference is null at runtime, a zero value is introduced.
3459      * </ul>
3460      * @param target the method handle to invoke after arguments are retyped
3461      * @param newType the expected type of the new method handle
3462      * @return a method handle which delegates to the target after performing
3463      *           any necessary argument conversions, and arranges for any
3464      *           necessary return value conversions
3465      * @throws NullPointerException if either argument is null
3466      * @throws WrongMethodTypeException if the conversion cannot be made
3467      * @see MethodHandle#asType
3468      */
3469     public static
3470     MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
3471         explicitCastArgumentsChecks(target, newType);
3472         // use the asTypeCache when possible:
3473         MethodType oldType = target.type();
3474         if (oldType == newType)  return target;
3475         if (oldType.explicitCastEquivalentToAsType(newType)) {
3476             return target.asFixedArity().asType(newType);
3477         }
3478         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
3479     }
3480 
3481     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
3482         if (target.type().parameterCount() != newType.parameterCount()) {
3483             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
3484         }
3485     }
3486 
3487     /**
3488      * Produces a method handle which adapts the calling sequence of the
3489      * given method handle to a new type, by reordering the arguments.
3490      * The resulting method handle is guaranteed to report a type
3491      * which is equal to the desired new type.
3492      * <p>
3493      * The given array controls the reordering.
3494      * Call {@code #I} the number of incoming parameters (the value
3495      * {@code newType.parameterCount()}, and call {@code #O} the number
3496      * of outgoing parameters (the value {@code target.type().parameterCount()}).
3497      * Then the length of the reordering array must be {@code #O},
3498      * and each element must be a non-negative number less than {@code #I}.
3499      * For every {@code N} less than {@code #O}, the {@code N}-th
3500      * outgoing argument will be taken from the {@code I}-th incoming
3501      * argument, where {@code I} is {@code reorder[N]}.
3502      * <p>
3503      * No argument or return value conversions are applied.
3504      * The type of each incoming argument, as determined by {@code newType},
3505      * must be identical to the type of the corresponding outgoing parameter
3506      * or parameters in the target method handle.
3507      * The return type of {@code newType} must be identical to the return
3508      * type of the original target.
3509      * <p>
3510      * The reordering array need not specify an actual permutation.
3511      * An incoming argument will be duplicated if its index appears
3512      * more than once in the array, and an incoming argument will be dropped
3513      * if its index does not appear in the array.
3514      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
3515      * incoming arguments which are not mentioned in the reordering array
3516      * may be of any type, as determined only by {@code newType}.
3517      * <blockquote><pre>{@code
3518 import static java.lang.invoke.MethodHandles.*;
3519 import static java.lang.invoke.MethodType.*;
3520 ...
3521 MethodType intfn1 = methodType(int.class, int.class);
3522 MethodType intfn2 = methodType(int.class, int.class, int.class);
3523 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
3524 assert(sub.type().equals(intfn2));
3525 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
3526 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
3527 assert((int)rsub.invokeExact(1, 100) == 99);
3528 MethodHandle add = ... (int x, int y) -> (x+y) ...;
3529 assert(add.type().equals(intfn2));
3530 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
3531 assert(twice.type().equals(intfn1));
3532 assert((int)twice.invokeExact(21) == 42);
3533      * }</pre></blockquote>
3534      * <p>
3535      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3536      * variable-arity method handle}, even if the original target method handle was.
3537      * @param target the method handle to invoke after arguments are reordered
3538      * @param newType the expected type of the new method handle
3539      * @param reorder an index array which controls the reordering
3540      * @return a method handle which delegates to the target after it
3541      *           drops unused arguments and moves and/or duplicates the other arguments
3542      * @throws NullPointerException if any argument is null
3543      * @throws IllegalArgumentException if the index array length is not equal to
3544      *                  the arity of the target, or if any index array element
3545      *                  not a valid index for a parameter of {@code newType},
3546      *                  or if two corresponding parameter types in
3547      *                  {@code target.type()} and {@code newType} are not identical,
3548      */
3549     public static
3550     MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
3551         reorder = reorder.clone();  // get a private copy
3552         MethodType oldType = target.type();
3553         permuteArgumentChecks(reorder, newType, oldType);
3554         // first detect dropped arguments and handle them separately
3555         int[] originalReorder = reorder;
3556         BoundMethodHandle result = target.rebind();
3557         LambdaForm form = result.form;
3558         int newArity = newType.parameterCount();
3559         // Normalize the reordering into a real permutation,
3560         // by removing duplicates and adding dropped elements.
3561         // This somewhat improves lambda form caching, as well
3562         // as simplifying the transform by breaking it up into steps.
3563         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
3564             if (ddIdx > 0) {
3565                 // We found a duplicated entry at reorder[ddIdx].
3566                 // Example:  (x,y,z)->asList(x,y,z)
3567                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
3568                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
3569                 // The starred element corresponds to the argument
3570                 // deleted by the dupArgumentForm transform.
3571                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
3572                 boolean killFirst = false;
3573                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
3574                     // Set killFirst if the dup is larger than an intervening position.
3575                     // This will remove at least one inversion from the permutation.
3576                     if (dupVal > val) killFirst = true;
3577                 }
3578                 if (!killFirst) {
3579                     srcPos = dstPos;
3580                     dstPos = ddIdx;
3581                 }
3582                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
3583                 assert (reorder[srcPos] == reorder[dstPos]);
3584                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
3585                 // contract the reordering by removing the element at dstPos
3586                 int tailPos = dstPos + 1;
3587                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
3588                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
3589             } else {
3590                 int dropVal = ~ddIdx, insPos = 0;
3591                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
3592                     // Find first element of reorder larger than dropVal.
3593                     // This is where we will insert the dropVal.
3594                     insPos += 1;
3595                 }
3596                 Class<?> ptype = newType.parameterType(dropVal);
3597                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
3598                 oldType = oldType.insertParameterTypes(insPos, ptype);
3599                 // expand the reordering by inserting an element at insPos
3600                 int tailPos = insPos + 1;
3601                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
3602                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
3603                 reorder[insPos] = dropVal;
3604             }
3605             assert (permuteArgumentChecks(reorder, newType, oldType));
3606         }
3607         assert (reorder.length == newArity);  // a perfect permutation
3608         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
3609         form = form.editor().permuteArgumentsForm(1, reorder);
3610         if (newType == result.type() && form == result.internalForm())
3611             return result;
3612         return result.copyWith(newType, form);
3613     }
3614 
3615     /**
3616      * Return an indication of any duplicate or omission in reorder.
3617      * If the reorder contains a duplicate entry, return the index of the second occurrence.
3618      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
3619      * Otherwise, return zero.
3620      * If an element not in [0..newArity-1] is encountered, return reorder.length.
3621      */
3622     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
3623         final int BIT_LIMIT = 63;  // max number of bits in bit mask
3624         if (newArity < BIT_LIMIT) {
3625             long mask = 0;
3626             for (int i = 0; i < reorder.length; i++) {
3627                 int arg = reorder[i];
3628                 if (arg >= newArity) {
3629                     return reorder.length;
3630                 }
3631                 long bit = 1L << arg;
3632                 if ((mask & bit) != 0) {
3633                     return i;  // >0 indicates a dup
3634                 }
3635                 mask |= bit;
3636             }
3637             if (mask == (1L << newArity) - 1) {
3638                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
3639                 return 0;
3640             }
3641             // find first zero
3642             long zeroBit = Long.lowestOneBit(~mask);
3643             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
3644             assert(zeroPos <= newArity);
3645             if (zeroPos == newArity) {
3646                 return 0;
3647             }
3648             return ~zeroPos;
3649         } else {
3650             // same algorithm, different bit set
3651             BitSet mask = new BitSet(newArity);
3652             for (int i = 0; i < reorder.length; i++) {
3653                 int arg = reorder[i];
3654                 if (arg >= newArity) {
3655                     return reorder.length;
3656                 }
3657                 if (mask.get(arg)) {
3658                     return i;  // >0 indicates a dup
3659                 }
3660                 mask.set(arg);
3661             }
3662             int zeroPos = mask.nextClearBit(0);
3663             assert(zeroPos <= newArity);
3664             if (zeroPos == newArity) {
3665                 return 0;
3666             }
3667             return ~zeroPos;
3668         }
3669     }
3670 
3671     private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
3672         if (newType.returnType() != oldType.returnType())
3673             throw newIllegalArgumentException("return types do not match",
3674                     oldType, newType);
3675         if (reorder.length == oldType.parameterCount()) {
3676             int limit = newType.parameterCount();
3677             boolean bad = false;
3678             for (int j = 0; j < reorder.length; j++) {
3679                 int i = reorder[j];
3680                 if (i < 0 || i >= limit) {
3681                     bad = true; break;
3682                 }
3683                 Class<?> src = newType.parameterType(i);
3684                 Class<?> dst = oldType.parameterType(j);
3685                 if (src != dst)
3686                     throw newIllegalArgumentException("parameter types do not match after reorder",
3687                             oldType, newType);
3688             }
3689             if (!bad)  return true;
3690         }
3691         throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
3692     }
3693 
3694     /**
3695      * Produces a method handle of the requested return type which returns the given
3696      * constant value every time it is invoked.
3697      * <p>
3698      * Before the method handle is returned, the passed-in value is converted to the requested type.
3699      * If the requested type is primitive, widening primitive conversions are attempted,
3700      * else reference conversions are attempted.
3701      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
3702      * @param type the return type of the desired method handle
3703      * @param value the value to return
3704      * @return a method handle of the given return type and no arguments, which always returns the given value
3705      * @throws NullPointerException if the {@code type} argument is null
3706      * @throws ClassCastException if the value cannot be converted to the required return type
3707      * @throws IllegalArgumentException if the given type is {@code void.class}
3708      */
3709     public static
3710     MethodHandle constant(Class<?> type, Object value) {
3711         if (type.isPrimitive()) {
3712             if (type == void.class)
3713                 throw newIllegalArgumentException("void type");
3714             Wrapper w = Wrapper.forPrimitiveType(type);
3715             value = w.convert(value, type);
3716             if (w.zero().equals(value))
3717                 return zero(w, type);
3718             return insertArguments(identity(type), 0, value);
3719         } else {
3720             if (value == null)
3721                 return zero(Wrapper.OBJECT, type);
3722             return identity(type).bindTo(value);
3723         }
3724     }
3725 
3726     /**
3727      * Produces a method handle which returns its sole argument when invoked.
3728      * @param type the type of the sole parameter and return value of the desired method handle
3729      * @return a unary method handle which accepts and returns the given type
3730      * @throws NullPointerException if the argument is null
3731      * @throws IllegalArgumentException if the given type is {@code void.class}
3732      */
3733     public static
3734     MethodHandle identity(Class<?> type) {
3735         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
3736         int pos = btw.ordinal();
3737         MethodHandle ident = IDENTITY_MHS[pos];
3738         if (ident == null) {
3739             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
3740         }
3741         if (ident.type().returnType() == type)
3742             return ident;
3743         // something like identity(Foo.class); do not bother to intern these
3744         assert (btw == Wrapper.OBJECT);
3745         return makeIdentity(type);
3746     }
3747 
3748     /**
3749      * Produces a constant method handle of the requested return type which
3750      * returns the default value for that type every time it is invoked.
3751      * The resulting constant method handle will have no side effects.
3752      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
3753      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
3754      * since {@code explicitCastArguments} converts {@code null} to default values.
3755      * @param type the expected return type of the desired method handle
3756      * @return a constant method handle that takes no arguments
3757      *         and returns the default value of the given type (or void, if the type is void)
3758      * @throws NullPointerException if the argument is null
3759      * @see MethodHandles#constant
3760      * @see MethodHandles#empty
3761      * @see MethodHandles#explicitCastArguments
3762      * @since 9
3763      */
3764     public static MethodHandle zero(Class<?> type) {
3765         Objects.requireNonNull(type);
3766         return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
3767     }
3768 
3769     private static MethodHandle identityOrVoid(Class<?> type) {
3770         return type == void.class ? zero(type) : identity(type);
3771     }
3772 
3773     /**
3774      * Produces a method handle of the requested type which ignores any arguments, does nothing,
3775      * and returns a suitable default depending on the return type.
3776      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
3777      * <p>The returned method handle is equivalent to
3778      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
3779      *
3780      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
3781      * {@code guardWithTest(pred, target, empty(target.type())}.
3782      * @param type the type of the desired method handle
3783      * @return a constant method handle of the given type, which returns a default value of the given return type
3784      * @throws NullPointerException if the argument is null
3785      * @see MethodHandles#zero
3786      * @see MethodHandles#constant
3787      * @since 9
3788      */
3789     public static  MethodHandle empty(MethodType type) {
3790         Objects.requireNonNull(type);
3791         return dropArguments(zero(type.returnType()), 0, type.parameterList());
3792     }
3793 
3794     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
3795     private static MethodHandle makeIdentity(Class<?> ptype) {
3796         MethodType mtype = methodType(ptype, ptype);
3797         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
3798         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
3799     }
3800 
3801     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
3802         int pos = btw.ordinal();
3803         MethodHandle zero = ZERO_MHS[pos];
3804         if (zero == null) {
3805             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
3806         }
3807         if (zero.type().returnType() == rtype)
3808             return zero;
3809         assert(btw == Wrapper.OBJECT);
3810         return makeZero(rtype);
3811     }
3812     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
3813     private static MethodHandle makeZero(Class<?> rtype) {
3814         MethodType mtype = methodType(rtype);
3815         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
3816         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
3817     }
3818 
3819     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
3820         // Simulate a CAS, to avoid racy duplication of results.
3821         MethodHandle prev = cache[pos];
3822         if (prev != null) return prev;
3823         return cache[pos] = value;
3824     }
3825 
3826     /**
3827      * Provides a target method handle with one or more <em>bound arguments</em>
3828      * in advance of the method handle's invocation.
3829      * The formal parameters to the target corresponding to the bound
3830      * arguments are called <em>bound parameters</em>.
3831      * Returns a new method handle which saves away the bound arguments.
3832      * When it is invoked, it receives arguments for any non-bound parameters,
3833      * binds the saved arguments to their corresponding parameters,
3834      * and calls the original target.
3835      * <p>
3836      * The type of the new method handle will drop the types for the bound
3837      * parameters from the original target type, since the new method handle
3838      * will no longer require those arguments to be supplied by its callers.
3839      * <p>
3840      * Each given argument object must match the corresponding bound parameter type.
3841      * If a bound parameter type is a primitive, the argument object
3842      * must be a wrapper, and will be unboxed to produce the primitive value.
3843      * <p>
3844      * The {@code pos} argument selects which parameters are to be bound.
3845      * It may range between zero and <i>N-L</i> (inclusively),
3846      * where <i>N</i> is the arity of the target method handle
3847      * and <i>L</i> is the length of the values array.
3848      * <p>
3849      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3850      * variable-arity method handle}, even if the original target method handle was.
3851      * @param target the method handle to invoke after the argument is inserted
3852      * @param pos where to insert the argument (zero for the first)
3853      * @param values the series of arguments to insert
3854      * @return a method handle which inserts an additional argument,
3855      *         before calling the original method handle
3856      * @throws NullPointerException if the target or the {@code values} array is null
3857      * @throws IllegalArgumentException if (@code pos) is less than {@code 0} or greater than
3858      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
3859      *         is the length of the values array.
3860      * @throws ClassCastException if an argument does not match the corresponding bound parameter
3861      *         type.
3862      * @see MethodHandle#bindTo
3863      */
3864     public static
3865     MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
3866         int insCount = values.length;
3867         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
3868         if (insCount == 0)  return target;
3869         BoundMethodHandle result = target.rebind();
3870         for (int i = 0; i < insCount; i++) {
3871             Object value = values[i];
3872             Class<?> ptype = ptypes[pos+i];
3873             if (ptype.isPrimitive()) {
3874                 result = insertArgumentPrimitive(result, pos, ptype, value);
3875             } else {
3876                 value = ptype.cast(value);  // throw CCE if needed
3877                 result = result.bindArgumentL(pos, value);
3878             }
3879         }
3880         return result;
3881     }
3882 
3883     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
3884                                                              Class<?> ptype, Object value) {
3885         Wrapper w = Wrapper.forPrimitiveType(ptype);
3886         // perform unboxing and/or primitive conversion
3887         value = w.convert(value, ptype);
3888         switch (w) {
3889         case INT:     return result.bindArgumentI(pos, (int)value);
3890         case LONG:    return result.bindArgumentJ(pos, (long)value);
3891         case FLOAT:   return result.bindArgumentF(pos, (float)value);
3892         case DOUBLE:  return result.bindArgumentD(pos, (double)value);
3893         default:      return result.bindArgumentI(pos, ValueConversions.widenSubword(value));
3894         }
3895     }
3896 
3897     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
3898         MethodType oldType = target.type();
3899         int outargs = oldType.parameterCount();
3900         int inargs  = outargs - insCount;
3901         if (inargs < 0)
3902             throw newIllegalArgumentException("too many values to insert");
3903         if (pos < 0 || pos > inargs)
3904             throw newIllegalArgumentException("no argument type to append");
3905         return oldType.ptypes();
3906     }
3907 
3908     /**
3909      * Produces a method handle which will discard some dummy arguments
3910      * before calling some other specified <i>target</i> method handle.
3911      * The type of the new method handle will be the same as the target's type,
3912      * except it will also include the dummy argument types,
3913      * at some given position.
3914      * <p>
3915      * The {@code pos} argument may range between zero and <i>N</i>,
3916      * where <i>N</i> is the arity of the target.
3917      * If {@code pos} is zero, the dummy arguments will precede
3918      * the target's real arguments; if {@code pos} is <i>N</i>
3919      * they will come after.
3920      * <p>
3921      * <b>Example:</b>
3922      * <blockquote><pre>{@code
3923 import static java.lang.invoke.MethodHandles.*;
3924 import static java.lang.invoke.MethodType.*;
3925 ...
3926 MethodHandle cat = lookup().findVirtual(String.class,
3927   "concat", methodType(String.class, String.class));
3928 assertEquals("xy", (String) cat.invokeExact("x", "y"));
3929 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
3930 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
3931 assertEquals(bigType, d0.type());
3932 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
3933      * }</pre></blockquote>
3934      * <p>
3935      * This method is also equivalent to the following code:
3936      * <blockquote><pre>
3937      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
3938      * </pre></blockquote>
3939      * @param target the method handle to invoke after the arguments are dropped
3940      * @param valueTypes the type(s) of the argument(s) to drop
3941      * @param pos position of first argument to drop (zero for the leftmost)
3942      * @return a method handle which drops arguments of the given types,
3943      *         before calling the original method handle
3944      * @throws NullPointerException if the target is null,
3945      *                              or if the {@code valueTypes} list or any of its elements is null
3946      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
3947      *                  or if {@code pos} is negative or greater than the arity of the target,
3948      *                  or if the new method handle's type would have too many parameters
3949      */
3950     public static
3951     MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
3952         return dropArguments0(target, pos, copyTypes(valueTypes.toArray()));
3953     }
3954 
3955     private static List<Class<?>> copyTypes(Object[] array) {
3956         return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class));
3957     }
3958 
3959     private static
3960     MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) {
3961         MethodType oldType = target.type();  // get NPE
3962         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
3963         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
3964         if (dropped == 0)  return target;
3965         BoundMethodHandle result = target.rebind();
3966         LambdaForm lform = result.form;
3967         int insertFormArg = 1 + pos;
3968         for (Class<?> ptype : valueTypes) {
3969             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
3970         }
3971         result = result.copyWith(newType, lform);
3972         return result;
3973     }
3974 
3975     private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
3976         int dropped = valueTypes.size();
3977         MethodType.checkSlotCount(dropped);
3978         int outargs = oldType.parameterCount();
3979         int inargs  = outargs + dropped;
3980         if (pos < 0 || pos > outargs)
3981             throw newIllegalArgumentException("no argument type to remove"
3982                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
3983                     );
3984         return dropped;
3985     }
3986 
3987     /**
3988      * Produces a method handle which will discard some dummy arguments
3989      * before calling some other specified <i>target</i> method handle.
3990      * The type of the new method handle will be the same as the target's type,
3991      * except it will also include the dummy argument types,
3992      * at some given position.
3993      * <p>
3994      * The {@code pos} argument may range between zero and <i>N</i>,
3995      * where <i>N</i> is the arity of the target.
3996      * If {@code pos} is zero, the dummy arguments will precede
3997      * the target's real arguments; if {@code pos} is <i>N</i>
3998      * they will come after.
3999      * @apiNote
4000      * <blockquote><pre>{@code
4001 import static java.lang.invoke.MethodHandles.*;
4002 import static java.lang.invoke.MethodType.*;
4003 ...
4004 MethodHandle cat = lookup().findVirtual(String.class,
4005   "concat", methodType(String.class, String.class));
4006 assertEquals("xy", (String) cat.invokeExact("x", "y"));
4007 MethodHandle d0 = dropArguments(cat, 0, String.class);
4008 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
4009 MethodHandle d1 = dropArguments(cat, 1, String.class);
4010 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
4011 MethodHandle d2 = dropArguments(cat, 2, String.class);
4012 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
4013 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
4014 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
4015      * }</pre></blockquote>
4016      * <p>
4017      * This method is also equivalent to the following code:
4018      * <blockquote><pre>
4019      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
4020      * </pre></blockquote>
4021      * @param target the method handle to invoke after the arguments are dropped
4022      * @param valueTypes the type(s) of the argument(s) to drop
4023      * @param pos position of first argument to drop (zero for the leftmost)
4024      * @return a method handle which drops arguments of the given types,
4025      *         before calling the original method handle
4026      * @throws NullPointerException if the target is null,
4027      *                              or if the {@code valueTypes} array or any of its elements is null
4028      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
4029      *                  or if {@code pos} is negative or greater than the arity of the target,
4030      *                  or if the new method handle's type would have
4031      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
4032      */
4033     public static
4034     MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
4035         return dropArguments0(target, pos, copyTypes(valueTypes));
4036     }
4037 
4038     // private version which allows caller some freedom with error handling
4039     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
4040                                       boolean nullOnFailure) {
4041         newTypes = copyTypes(newTypes.toArray());
4042         List<Class<?>> oldTypes = target.type().parameterList();
4043         int match = oldTypes.size();
4044         if (skip != 0) {
4045             if (skip < 0 || skip > match) {
4046                 throw newIllegalArgumentException("illegal skip", skip, target);
4047             }
4048             oldTypes = oldTypes.subList(skip, match);
4049             match -= skip;
4050         }
4051         List<Class<?>> addTypes = newTypes;
4052         int add = addTypes.size();
4053         if (pos != 0) {
4054             if (pos < 0 || pos > add) {
4055                 throw newIllegalArgumentException("illegal pos", pos, newTypes);
4056             }
4057             addTypes = addTypes.subList(pos, add);
4058             add -= pos;
4059             assert(addTypes.size() == add);
4060         }
4061         // Do not add types which already match the existing arguments.
4062         if (match > add || !oldTypes.equals(addTypes.subList(0, match))) {
4063             if (nullOnFailure) {
4064                 return null;
4065             }
4066             throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes);
4067         }
4068         addTypes = addTypes.subList(match, add);
4069         add -= match;
4070         assert(addTypes.size() == add);
4071         // newTypes:     (   P*[pos], M*[match], A*[add] )
4072         // target: ( S*[skip],        M*[match]  )
4073         MethodHandle adapter = target;
4074         if (add > 0) {
4075             adapter = dropArguments0(adapter, skip+ match, addTypes);
4076         }
4077         // adapter: (S*[skip],        M*[match], A*[add] )
4078         if (pos > 0) {
4079             adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos));
4080         }
4081         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
4082         return adapter;
4083     }
4084 
4085     /**
4086      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
4087      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
4088      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
4089      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
4090      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
4091      * {@link #dropArguments(MethodHandle, int, Class[])}.
4092      * <p>
4093      * The resulting handle will have the same return type as the target handle.
4094      * <p>
4095      * In more formal terms, assume these two type lists:<ul>
4096      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
4097      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
4098      * {@code newTypes}.
4099      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
4100      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
4101      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
4102      * sub-list.
4103      * </ul>
4104      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
4105      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
4106      * {@link #dropArguments(MethodHandle, int, Class[])}.
4107      *
4108      * @apiNote
4109      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
4110      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
4111      * <blockquote><pre>{@code
4112 import static java.lang.invoke.MethodHandles.*;
4113 import static java.lang.invoke.MethodType.*;
4114 ...
4115 ...
4116 MethodHandle h0 = constant(boolean.class, true);
4117 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
4118 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
4119 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
4120 if (h1.type().parameterCount() < h2.type().parameterCount())
4121     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
4122 else
4123     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
4124 MethodHandle h3 = guardWithTest(h0, h1, h2);
4125 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
4126      * }</pre></blockquote>
4127      * @param target the method handle to adapt
4128      * @param skip number of targets parameters to disregard (they will be unchanged)
4129      * @param newTypes the list of types to match {@code target}'s parameter type list to
4130      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
4131      * @return a possibly adapted method handle
4132      * @throws NullPointerException if either argument is null
4133      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
4134      *         or if {@code skip} is negative or greater than the arity of the target,
4135      *         or if {@code pos} is negative or greater than the newTypes list size,
4136      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
4137      *         {@code pos}.
4138      * @since 9
4139      */
4140     public static
4141     MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
4142         Objects.requireNonNull(target);
4143         Objects.requireNonNull(newTypes);
4144         return dropArgumentsToMatch(target, skip, newTypes, pos, false);
4145     }
4146 
4147     /**
4148      * Adapts a target method handle by pre-processing
4149      * one or more of its arguments, each with its own unary filter function,
4150      * and then calling the target with each pre-processed argument
4151      * replaced by the result of its corresponding filter function.
4152      * <p>
4153      * The pre-processing is performed by one or more method handles,
4154      * specified in the elements of the {@code filters} array.
4155      * The first element of the filter array corresponds to the {@code pos}
4156      * argument of the target, and so on in sequence.
4157      * The filter functions are invoked in left to right order.
4158      * <p>
4159      * Null arguments in the array are treated as identity functions,
4160      * and the corresponding arguments left unchanged.
4161      * (If there are no non-null elements in the array, the original target is returned.)
4162      * Each filter is applied to the corresponding argument of the adapter.
4163      * <p>
4164      * If a filter {@code F} applies to the {@code N}th argument of
4165      * the target, then {@code F} must be a method handle which
4166      * takes exactly one argument.  The type of {@code F}'s sole argument
4167      * replaces the corresponding argument type of the target
4168      * in the resulting adapted method handle.
4169      * The return type of {@code F} must be identical to the corresponding
4170      * parameter type of the target.
4171      * <p>
4172      * It is an error if there are elements of {@code filters}
4173      * (null or not)
4174      * which do not correspond to argument positions in the target.
4175      * <p><b>Example:</b>
4176      * <blockquote><pre>{@code
4177 import static java.lang.invoke.MethodHandles.*;
4178 import static java.lang.invoke.MethodType.*;
4179 ...
4180 MethodHandle cat = lookup().findVirtual(String.class,
4181   "concat", methodType(String.class, String.class));
4182 MethodHandle upcase = lookup().findVirtual(String.class,
4183   "toUpperCase", methodType(String.class));
4184 assertEquals("xy", (String) cat.invokeExact("x", "y"));
4185 MethodHandle f0 = filterArguments(cat, 0, upcase);
4186 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
4187 MethodHandle f1 = filterArguments(cat, 1, upcase);
4188 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
4189 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
4190 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
4191      * }</pre></blockquote>
4192      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
4193      * denotes the return type of both the {@code target} and resulting adapter.
4194      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
4195      * of the parameters and arguments that precede and follow the filter position
4196      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
4197      * values of the filtered parameters and arguments; they also represent the
4198      * return types of the {@code filter[i]} handles. The latter accept arguments
4199      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
4200      * the resulting adapter.
4201      * <blockquote><pre>{@code
4202      * T target(P... p, A[i]... a[i], B... b);
4203      * A[i] filter[i](V[i]);
4204      * T adapter(P... p, V[i]... v[i], B... b) {
4205      *   return target(p..., filter[i](v[i])..., b...);
4206      * }
4207      * }</pre></blockquote>
4208      * <p>
4209      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4210      * variable-arity method handle}, even if the original target method handle was.
4211      *
4212      * @param target the method handle to invoke after arguments are filtered
4213      * @param pos the position of the first argument to filter
4214      * @param filters method handles to call initially on filtered arguments
4215      * @return method handle which incorporates the specified argument filtering logic
4216      * @throws NullPointerException if the target is null
4217      *                              or if the {@code filters} array is null
4218      * @throws IllegalArgumentException if a non-null element of {@code filters}
4219      *          does not match a corresponding argument type of target as described above,
4220      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
4221      *          or if the resulting method handle's type would have
4222      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4223      */
4224     public static
4225     MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
4226         // In method types arguments start at index 0, while the LF
4227         // editor have the MH receiver at position 0 - adjust appropriately.
4228         final int MH_RECEIVER_OFFSET = 1;
4229         filterArgumentsCheckArity(target, pos, filters);
4230         MethodHandle adapter = target;
4231 
4232         // keep track of currently matched filters, as to optimize repeated filters
4233         int index = 0;
4234         int[] positions = new int[filters.length];
4235         MethodHandle filter = null;
4236 
4237         // process filters in reverse order so that the invocation of
4238         // the resulting adapter will invoke the filters in left-to-right order
4239         for (int i = filters.length - 1; i >= 0; --i) {
4240             MethodHandle newFilter = filters[i];
4241             if (newFilter == null) continue;  // ignore null elements of filters
4242 
4243             // flush changes on update
4244             if (filter != newFilter) {
4245                 if (filter != null) {
4246                     if (index > 1) {
4247                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
4248                     } else {
4249                         adapter = filterArgument(adapter, positions[0] - 1, filter);
4250                     }
4251                 }
4252                 filter = newFilter;
4253                 index = 0;
4254             }
4255 
4256             filterArgumentChecks(target, pos + i, newFilter);
4257             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
4258         }
4259         if (index > 1) {
4260             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
4261         } else if (index == 1) {
4262             adapter = filterArgument(adapter, positions[0] - 1, filter);
4263         }
4264         return adapter;
4265     }
4266 
4267     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
4268         MethodType targetType = adapter.type();
4269         MethodType filterType = filter.type();
4270         BoundMethodHandle result = adapter.rebind();
4271         Class<?> newParamType = filterType.parameterType(0);
4272 
4273         Class<?>[] ptypes = targetType.ptypes().clone();
4274         for (int pos : positions) {
4275             ptypes[pos - 1] = newParamType;
4276         }
4277         MethodType newType = MethodType.makeImpl(targetType.rtype(), ptypes, true);
4278 
4279         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
4280         return result.copyWithExtendL(newType, lform, filter);
4281     }
4282 
4283     /*non-public*/ static
4284     MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
4285         filterArgumentChecks(target, pos, filter);
4286         MethodType targetType = target.type();
4287         MethodType filterType = filter.type();
4288         BoundMethodHandle result = target.rebind();
4289         Class<?> newParamType = filterType.parameterType(0);
4290         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
4291         MethodType newType = targetType.changeParameterType(pos, newParamType);
4292         result = result.copyWithExtendL(newType, lform, filter);
4293         return result;
4294     }
4295 
4296     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
4297         MethodType targetType = target.type();
4298         int maxPos = targetType.parameterCount();
4299         if (pos + filters.length > maxPos)
4300             throw newIllegalArgumentException("too many filters");
4301     }
4302 
4303     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
4304         MethodType targetType = target.type();
4305         MethodType filterType = filter.type();
4306         if (filterType.parameterCount() != 1
4307             || filterType.returnType() != targetType.parameterType(pos))
4308             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
4309     }
4310 
4311     /**
4312      * Adapts a target method handle by pre-processing
4313      * a sub-sequence of its arguments with a filter (another method handle).
4314      * The pre-processed arguments are replaced by the result (if any) of the
4315      * filter function.
4316      * The target is then called on the modified (usually shortened) argument list.
4317      * <p>
4318      * If the filter returns a value, the target must accept that value as
4319      * its argument in position {@code pos}, preceded and/or followed by
4320      * any arguments not passed to the filter.
4321      * If the filter returns void, the target must accept all arguments
4322      * not passed to the filter.
4323      * No arguments are reordered, and a result returned from the filter
4324      * replaces (in order) the whole subsequence of arguments originally
4325      * passed to the adapter.
4326      * <p>
4327      * The argument types (if any) of the filter
4328      * replace zero or one argument types of the target, at position {@code pos},
4329      * in the resulting adapted method handle.
4330      * The return type of the filter (if any) must be identical to the
4331      * argument type of the target at position {@code pos}, and that target argument
4332      * is supplied by the return value of the filter.
4333      * <p>
4334      * In all cases, {@code pos} must be greater than or equal to zero, and
4335      * {@code pos} must also be less than or equal to the target's arity.
4336      * <p><b>Example:</b>
4337      * <blockquote><pre>{@code
4338 import static java.lang.invoke.MethodHandles.*;
4339 import static java.lang.invoke.MethodType.*;
4340 ...
4341 MethodHandle deepToString = publicLookup()
4342   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
4343 
4344 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
4345 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
4346 
4347 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
4348 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
4349 
4350 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
4351 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
4352 assertEquals("[top, [up, down], strange]",
4353              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
4354 
4355 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
4356 assertEquals("[top, [up, down], [strange]]",
4357              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
4358 
4359 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
4360 assertEquals("[top, [[up, down, strange], charm], bottom]",
4361              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
4362      * }</pre></blockquote>
4363      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
4364      * represents the return type of the {@code target} and resulting adapter.
4365      * {@code V}/{@code v} stand for the return type and value of the
4366      * {@code filter}, which are also found in the signature and arguments of
4367      * the {@code target}, respectively, unless {@code V} is {@code void}.
4368      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
4369      * and values preceding and following the collection position, {@code pos},
4370      * in the {@code target}'s signature. They also turn up in the resulting
4371      * adapter's signature and arguments, where they surround
4372      * {@code B}/{@code b}, which represent the parameter types and arguments
4373      * to the {@code filter} (if any).
4374      * <blockquote><pre>{@code
4375      * T target(A...,V,C...);
4376      * V filter(B...);
4377      * T adapter(A... a,B... b,C... c) {
4378      *   V v = filter(b...);
4379      *   return target(a...,v,c...);
4380      * }
4381      * // and if the filter has no arguments:
4382      * T target2(A...,V,C...);
4383      * V filter2();
4384      * T adapter2(A... a,C... c) {
4385      *   V v = filter2();
4386      *   return target2(a...,v,c...);
4387      * }
4388      * // and if the filter has a void return:
4389      * T target3(A...,C...);
4390      * void filter3(B...);
4391      * T adapter3(A... a,B... b,C... c) {
4392      *   filter3(b...);
4393      *   return target3(a...,c...);
4394      * }
4395      * }</pre></blockquote>
4396      * <p>
4397      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
4398      * one which first "folds" the affected arguments, and then drops them, in separate
4399      * steps as follows:
4400      * <blockquote><pre>{@code
4401      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
4402      * mh = MethodHandles.foldArguments(mh, coll); //step 1
4403      * }</pre></blockquote>
4404      * If the target method handle consumes no arguments besides than the result
4405      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
4406      * is equivalent to {@code filterReturnValue(coll, mh)}.
4407      * If the filter method handle {@code coll} consumes one argument and produces
4408      * a non-void result, then {@code collectArguments(mh, N, coll)}
4409      * is equivalent to {@code filterArguments(mh, N, coll)}.
4410      * Other equivalences are possible but would require argument permutation.
4411      * <p>
4412      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4413      * variable-arity method handle}, even if the original target method handle was.
4414      *
4415      * @param target the method handle to invoke after filtering the subsequence of arguments
4416      * @param pos the position of the first adapter argument to pass to the filter,
4417      *            and/or the target argument which receives the result of the filter
4418      * @param filter method handle to call on the subsequence of arguments
4419      * @return method handle which incorporates the specified argument subsequence filtering logic
4420      * @throws NullPointerException if either argument is null
4421      * @throws IllegalArgumentException if the return type of {@code filter}
4422      *          is non-void and is not the same as the {@code pos} argument of the target,
4423      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
4424      *          or if the resulting method handle's type would have
4425      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4426      * @see MethodHandles#foldArguments
4427      * @see MethodHandles#filterArguments
4428      * @see MethodHandles#filterReturnValue
4429      */
4430     public static
4431     MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
4432         MethodType newType = collectArgumentsChecks(target, pos, filter);
4433         MethodType collectorType = filter.type();
4434         BoundMethodHandle result = target.rebind();
4435         LambdaForm lform;
4436         if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) {
4437             lform = result.editor().collectArgumentArrayForm(1 + pos, filter);
4438             if (lform != null) {
4439                 return result.copyWith(newType, lform);
4440             }
4441         }
4442         lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
4443         return result.copyWithExtendL(newType, lform, filter);
4444     }
4445 
4446     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
4447         MethodType targetType = target.type();
4448         MethodType filterType = filter.type();
4449         Class<?> rtype = filterType.returnType();
4450         List<Class<?>> filterArgs = filterType.parameterList();
4451         if (rtype == void.class) {
4452             return targetType.insertParameterTypes(pos, filterArgs);
4453         }
4454         if (rtype != targetType.parameterType(pos)) {
4455             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
4456         }
4457         return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
4458     }
4459 
4460     /**
4461      * Adapts a target method handle by post-processing
4462      * its return value (if any) with a filter (another method handle).
4463      * The result of the filter is returned from the adapter.
4464      * <p>
4465      * If the target returns a value, the filter must accept that value as
4466      * its only argument.
4467      * If the target returns void, the filter must accept no arguments.
4468      * <p>
4469      * The return type of the filter
4470      * replaces the return type of the target
4471      * in the resulting adapted method handle.
4472      * The argument type of the filter (if any) must be identical to the
4473      * return type of the target.
4474      * <p><b>Example:</b>
4475      * <blockquote><pre>{@code
4476 import static java.lang.invoke.MethodHandles.*;
4477 import static java.lang.invoke.MethodType.*;
4478 ...
4479 MethodHandle cat = lookup().findVirtual(String.class,
4480   "concat", methodType(String.class, String.class));
4481 MethodHandle length = lookup().findVirtual(String.class,
4482   "length", methodType(int.class));
4483 System.out.println((String) cat.invokeExact("x", "y")); // xy
4484 MethodHandle f0 = filterReturnValue(cat, length);
4485 System.out.println((int) f0.invokeExact("x", "y")); // 2
4486      * }</pre></blockquote>
4487      * <p>Here is pseudocode for the resulting adapter. In the code,
4488      * {@code T}/{@code t} represent the result type and value of the
4489      * {@code target}; {@code V}, the result type of the {@code filter}; and
4490      * {@code A}/{@code a}, the types and values of the parameters and arguments
4491      * of the {@code target} as well as the resulting adapter.
4492      * <blockquote><pre>{@code
4493      * T target(A...);
4494      * V filter(T);
4495      * V adapter(A... a) {
4496      *   T t = target(a...);
4497      *   return filter(t);
4498      * }
4499      * // and if the target has a void return:
4500      * void target2(A...);
4501      * V filter2();
4502      * V adapter2(A... a) {
4503      *   target2(a...);
4504      *   return filter2();
4505      * }
4506      * // and if the filter has a void return:
4507      * T target3(A...);
4508      * void filter3(V);
4509      * void adapter3(A... a) {
4510      *   T t = target3(a...);
4511      *   filter3(t);
4512      * }
4513      * }</pre></blockquote>
4514      * <p>
4515      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4516      * variable-arity method handle}, even if the original target method handle was.
4517      * @param target the method handle to invoke before filtering the return value
4518      * @param filter method handle to call on the return value
4519      * @return method handle which incorporates the specified return value filtering logic
4520      * @throws NullPointerException if either argument is null
4521      * @throws IllegalArgumentException if the argument list of {@code filter}
4522      *          does not match the return type of target as described above
4523      */
4524     public static
4525     MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
4526         MethodType targetType = target.type();
4527         MethodType filterType = filter.type();
4528         filterReturnValueChecks(targetType, filterType);
4529         BoundMethodHandle result = target.rebind();
4530         BasicType rtype = BasicType.basicType(filterType.returnType());
4531         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
4532         MethodType newType = targetType.changeReturnType(filterType.returnType());
4533         result = result.copyWithExtendL(newType, lform, filter);
4534         return result;
4535     }
4536 
4537     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
4538         Class<?> rtype = targetType.returnType();
4539         int filterValues = filterType.parameterCount();
4540         if (filterValues == 0
4541                 ? (rtype != void.class)
4542                 : (rtype != filterType.parameterType(0) || filterValues != 1))
4543             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
4544     }
4545 
4546     /**
4547      * Adapts a target method handle by pre-processing
4548      * some of its arguments, and then calling the target with
4549      * the result of the pre-processing, inserted into the original
4550      * sequence of arguments.
4551      * <p>
4552      * The pre-processing is performed by {@code combiner}, a second method handle.
4553      * Of the arguments passed to the adapter, the first {@code N} arguments
4554      * are copied to the combiner, which is then called.
4555      * (Here, {@code N} is defined as the parameter count of the combiner.)
4556      * After this, control passes to the target, with any result
4557      * from the combiner inserted before the original {@code N} incoming
4558      * arguments.
4559      * <p>
4560      * If the combiner returns a value, the first parameter type of the target
4561      * must be identical with the return type of the combiner, and the next
4562      * {@code N} parameter types of the target must exactly match the parameters
4563      * of the combiner.
4564      * <p>
4565      * If the combiner has a void return, no result will be inserted,
4566      * and the first {@code N} parameter types of the target
4567      * must exactly match the parameters of the combiner.
4568      * <p>
4569      * The resulting adapter is the same type as the target, except that the
4570      * first parameter type is dropped,
4571      * if it corresponds to the result of the combiner.
4572      * <p>
4573      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
4574      * that either the combiner or the target does not wish to receive.
4575      * If some of the incoming arguments are destined only for the combiner,
4576      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
4577      * arguments will not need to be live on the stack on entry to the
4578      * target.)
4579      * <p><b>Example:</b>
4580      * <blockquote><pre>{@code
4581 import static java.lang.invoke.MethodHandles.*;
4582 import static java.lang.invoke.MethodType.*;
4583 ...
4584 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
4585   "println", methodType(void.class, String.class))
4586     .bindTo(System.out);
4587 MethodHandle cat = lookup().findVirtual(String.class,
4588   "concat", methodType(String.class, String.class));
4589 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
4590 MethodHandle catTrace = foldArguments(cat, trace);
4591 // also prints "boo":
4592 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
4593      * }</pre></blockquote>
4594      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
4595      * represents the result type of the {@code target} and resulting adapter.
4596      * {@code V}/{@code v} represent the type and value of the parameter and argument
4597      * of {@code target} that precedes the folding position; {@code V} also is
4598      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
4599      * types and values of the {@code N} parameters and arguments at the folding
4600      * position. {@code B}/{@code b} represent the types and values of the
4601      * {@code target} parameters and arguments that follow the folded parameters
4602      * and arguments.
4603      * <blockquote><pre>{@code
4604      * // there are N arguments in A...
4605      * T target(V, A[N]..., B...);
4606      * V combiner(A...);
4607      * T adapter(A... a, B... b) {
4608      *   V v = combiner(a...);
4609      *   return target(v, a..., b...);
4610      * }
4611      * // and if the combiner has a void return:
4612      * T target2(A[N]..., B...);
4613      * void combiner2(A...);
4614      * T adapter2(A... a, B... b) {
4615      *   combiner2(a...);
4616      *   return target2(a..., b...);
4617      * }
4618      * }</pre></blockquote>
4619      * <p>
4620      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4621      * variable-arity method handle}, even if the original target method handle was.
4622      * @param target the method handle to invoke after arguments are combined
4623      * @param combiner method handle to call initially on the incoming arguments
4624      * @return method handle which incorporates the specified argument folding logic
4625      * @throws NullPointerException if either argument is null
4626      * @throws IllegalArgumentException if {@code combiner}'s return type
4627      *          is non-void and not the same as the first argument type of
4628      *          the target, or if the initial {@code N} argument types
4629      *          of the target
4630      *          (skipping one matching the {@code combiner}'s return type)
4631      *          are not identical with the argument types of {@code combiner}
4632      */
4633     public static
4634     MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
4635         return foldArguments(target, 0, combiner);
4636     }
4637 
4638     /**
4639      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
4640      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
4641      * before the folded arguments.
4642      * <p>
4643      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
4644      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
4645      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
4646      * 0.
4647      *
4648      * @apiNote Example:
4649      * <blockquote><pre>{@code
4650     import static java.lang.invoke.MethodHandles.*;
4651     import static java.lang.invoke.MethodType.*;
4652     ...
4653     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
4654     "println", methodType(void.class, String.class))
4655     .bindTo(System.out);
4656     MethodHandle cat = lookup().findVirtual(String.class,
4657     "concat", methodType(String.class, String.class));
4658     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
4659     MethodHandle catTrace = foldArguments(cat, 1, trace);
4660     // also prints "jum":
4661     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
4662      * }</pre></blockquote>
4663      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
4664      * represents the result type of the {@code target} and resulting adapter.
4665      * {@code V}/{@code v} represent the type and value of the parameter and argument
4666      * of {@code target} that precedes the folding position; {@code V} also is
4667      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
4668      * types and values of the {@code N} parameters and arguments at the folding
4669      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
4670      * and values of the {@code target} parameters and arguments that precede and
4671      * follow the folded parameters and arguments starting at {@code pos},
4672      * respectively.
4673      * <blockquote><pre>{@code
4674      * // there are N arguments in A...
4675      * T target(Z..., V, A[N]..., B...);
4676      * V combiner(A...);
4677      * T adapter(Z... z, A... a, B... b) {
4678      *   V v = combiner(a...);
4679      *   return target(z..., v, a..., b...);
4680      * }
4681      * // and if the combiner has a void return:
4682      * T target2(Z..., A[N]..., B...);
4683      * void combiner2(A...);
4684      * T adapter2(Z... z, A... a, B... b) {
4685      *   combiner2(a...);
4686      *   return target2(z..., a..., b...);
4687      * }
4688      * }</pre></blockquote>
4689      * <p>
4690      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4691      * variable-arity method handle}, even if the original target method handle was.
4692      *
4693      * @param target the method handle to invoke after arguments are combined
4694      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
4695      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
4696      * @param combiner method handle to call initially on the incoming arguments
4697      * @return method handle which incorporates the specified argument folding logic
4698      * @throws NullPointerException if either argument is null
4699      * @throws IllegalArgumentException if either of the following two conditions holds:
4700      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
4701      *              {@code pos} of the target signature;
4702      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
4703      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
4704      *
4705      * @see #foldArguments(MethodHandle, MethodHandle)
4706      * @since 9
4707      */
4708     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
4709         MethodType targetType = target.type();
4710         MethodType combinerType = combiner.type();
4711         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
4712         BoundMethodHandle result = target.rebind();
4713         boolean dropResult = rtype == void.class;
4714         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
4715         MethodType newType = targetType;
4716         if (!dropResult) {
4717             newType = newType.dropParameterTypes(pos, pos + 1);
4718         }
4719         result = result.copyWithExtendL(newType, lform, combiner);
4720         return result;
4721     }
4722 
4723     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
4724         int foldArgs   = combinerType.parameterCount();
4725         Class<?> rtype = combinerType.returnType();
4726         int foldVals = rtype == void.class ? 0 : 1;
4727         int afterInsertPos = foldPos + foldVals;
4728         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
4729         if (ok) {
4730             for (int i = 0; i < foldArgs; i++) {
4731                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
4732                     ok = false;
4733                     break;
4734                 }
4735             }
4736         }
4737         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
4738             ok = false;
4739         if (!ok)
4740             throw misMatchedTypes("target and combiner types", targetType, combinerType);
4741         return rtype;
4742     }
4743 
4744     /**
4745      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
4746      * of the pre-processing replacing the argument at the given position.
4747      *
4748      * @param target the method handle to invoke after arguments are combined
4749      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
4750      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
4751      * @param combiner method handle to call initially on the incoming arguments
4752      * @param argPositions indexes of the target to pick arguments sent to the combiner from
4753      * @return method handle which incorporates the specified argument folding logic
4754      * @throws NullPointerException if either argument is null
4755      * @throws IllegalArgumentException if either of the following two conditions holds:
4756      *          (1) {@code combiner}'s return type is not the same as the argument type at position
4757      *              {@code pos} of the target signature;
4758      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
4759      *              not identical with the argument types of {@code combiner}.
4760      */
4761     /*non-public*/ static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
4762         return argumentsWithCombiner(true, target, position, combiner, argPositions);
4763     }
4764 
4765     /**
4766      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
4767      * the pre-processing inserted into the original sequence of arguments at the given position.
4768      *
4769      * @param target the method handle to invoke after arguments are combined
4770      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
4771      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
4772      * @param combiner method handle to call initially on the incoming arguments
4773      * @param argPositions indexes of the target to pick arguments sent to the combiner from
4774      * @return method handle which incorporates the specified argument folding logic
4775      * @throws NullPointerException if either argument is null
4776      * @throws IllegalArgumentException if either of the following two conditions holds:
4777      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
4778      *              {@code pos} of the target signature;
4779      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
4780      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
4781      *              with the argument types of {@code combiner}.
4782      */
4783     /*non-public*/ static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
4784         return argumentsWithCombiner(false, target, position, combiner, argPositions);
4785     }
4786 
4787     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
4788         MethodType targetType = target.type();
4789         MethodType combinerType = combiner.type();
4790         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
4791         BoundMethodHandle result = target.rebind();
4792 
4793         MethodType newType = targetType;
4794         LambdaForm lform;
4795         if (filter) {
4796             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
4797         } else {
4798             boolean dropResult = rtype == void.class;
4799             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
4800             if (!dropResult) {
4801                 newType = newType.dropParameterTypes(position, position + 1);
4802             }
4803         }
4804         result = result.copyWithExtendL(newType, lform, combiner);
4805         return result;
4806     }
4807 
4808     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
4809         int combinerArgs = combinerType.parameterCount();
4810         if (argPos.length != combinerArgs) {
4811             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
4812         }
4813         Class<?> rtype = combinerType.returnType();
4814 
4815         for (int i = 0; i < combinerArgs; i++) {
4816             int arg = argPos[i];
4817             if (arg < 0 || arg > targetType.parameterCount()) {
4818                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
4819             }
4820             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
4821                 throw newIllegalArgumentException("target argument type at position " + arg
4822                         + " must match combiner argument type at index " + i + ": " + targetType
4823                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
4824             }
4825         }
4826         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
4827             throw misMatchedTypes("target and combiner types", targetType, combinerType);
4828         }
4829         return rtype;
4830     }
4831 
4832     /**
4833      * Makes a method handle which adapts a target method handle,
4834      * by guarding it with a test, a boolean-valued method handle.
4835      * If the guard fails, a fallback handle is called instead.
4836      * All three method handles must have the same corresponding
4837      * argument and return types, except that the return type
4838      * of the test must be boolean, and the test is allowed
4839      * to have fewer arguments than the other two method handles.
4840      * <p>
4841      * Here is pseudocode for the resulting adapter. In the code, {@code T}
4842      * represents the uniform result type of the three involved handles;
4843      * {@code A}/{@code a}, the types and values of the {@code target}
4844      * parameters and arguments that are consumed by the {@code test}; and
4845      * {@code B}/{@code b}, those types and values of the {@code target}
4846      * parameters and arguments that are not consumed by the {@code test}.
4847      * <blockquote><pre>{@code
4848      * boolean test(A...);
4849      * T target(A...,B...);
4850      * T fallback(A...,B...);
4851      * T adapter(A... a,B... b) {
4852      *   if (test(a...))
4853      *     return target(a..., b...);
4854      *   else
4855      *     return fallback(a..., b...);
4856      * }
4857      * }</pre></blockquote>
4858      * Note that the test arguments ({@code a...} in the pseudocode) cannot
4859      * be modified by execution of the test, and so are passed unchanged
4860      * from the caller to the target or fallback as appropriate.
4861      * @param test method handle used for test, must return boolean
4862      * @param target method handle to call if test passes
4863      * @param fallback method handle to call if test fails
4864      * @return method handle which incorporates the specified if/then/else logic
4865      * @throws NullPointerException if any argument is null
4866      * @throws IllegalArgumentException if {@code test} does not return boolean,
4867      *          or if all three method types do not match (with the return
4868      *          type of {@code test} changed to match that of the target).
4869      */
4870     public static
4871     MethodHandle guardWithTest(MethodHandle test,
4872                                MethodHandle target,
4873                                MethodHandle fallback) {
4874         MethodType gtype = test.type();
4875         MethodType ttype = target.type();
4876         MethodType ftype = fallback.type();
4877         if (!ttype.equals(ftype))
4878             throw misMatchedTypes("target and fallback types", ttype, ftype);
4879         if (gtype.returnType() != boolean.class)
4880             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
4881         List<Class<?>> targs = ttype.parameterList();
4882         test = dropArgumentsToMatch(test, 0, targs, 0, true);
4883         if (test == null) {
4884             throw misMatchedTypes("target and test types", ttype, gtype);
4885         }
4886         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
4887     }
4888 
4889     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
4890         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
4891     }
4892 
4893     /**
4894      * Makes a method handle which adapts a target method handle,
4895      * by running it inside an exception handler.
4896      * If the target returns normally, the adapter returns that value.
4897      * If an exception matching the specified type is thrown, the fallback
4898      * handle is called instead on the exception, plus the original arguments.
4899      * <p>
4900      * The target and handler must have the same corresponding
4901      * argument and return types, except that handler may omit trailing arguments
4902      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
4903      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
4904      * <p>
4905      * Here is pseudocode for the resulting adapter. In the code, {@code T}
4906      * represents the return type of the {@code target} and {@code handler},
4907      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
4908      * the types and values of arguments to the resulting handle consumed by
4909      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
4910      * resulting handle discarded by {@code handler}.
4911      * <blockquote><pre>{@code
4912      * T target(A..., B...);
4913      * T handler(ExType, A...);
4914      * T adapter(A... a, B... b) {
4915      *   try {
4916      *     return target(a..., b...);
4917      *   } catch (ExType ex) {
4918      *     return handler(ex, a...);
4919      *   }
4920      * }
4921      * }</pre></blockquote>
4922      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
4923      * be modified by execution of the target, and so are passed unchanged
4924      * from the caller to the handler, if the handler is invoked.
4925      * <p>
4926      * The target and handler must return the same type, even if the handler
4927      * always throws.  (This might happen, for instance, because the handler
4928      * is simulating a {@code finally} clause).
4929      * To create such a throwing handler, compose the handler creation logic
4930      * with {@link #throwException throwException},
4931      * in order to create a method handle of the correct return type.
4932      * @param target method handle to call
4933      * @param exType the type of exception which the handler will catch
4934      * @param handler method handle to call if a matching exception is thrown
4935      * @return method handle which incorporates the specified try/catch logic
4936      * @throws NullPointerException if any argument is null
4937      * @throws IllegalArgumentException if {@code handler} does not accept
4938      *          the given exception type, or if the method handle types do
4939      *          not match in their return types and their
4940      *          corresponding parameters
4941      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
4942      */
4943     public static
4944     MethodHandle catchException(MethodHandle target,
4945                                 Class<? extends Throwable> exType,
4946                                 MethodHandle handler) {
4947         MethodType ttype = target.type();
4948         MethodType htype = handler.type();
4949         if (!Throwable.class.isAssignableFrom(exType))
4950             throw new ClassCastException(exType.getName());
4951         if (htype.parameterCount() < 1 ||
4952             !htype.parameterType(0).isAssignableFrom(exType))
4953             throw newIllegalArgumentException("handler does not accept exception type "+exType);
4954         if (htype.returnType() != ttype.returnType())
4955             throw misMatchedTypes("target and handler return types", ttype, htype);
4956         handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
4957         if (handler == null) {
4958             throw misMatchedTypes("target and handler types", ttype, htype);
4959         }
4960         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
4961     }
4962 
4963     /**
4964      * Produces a method handle which will throw exceptions of the given {@code exType}.
4965      * The method handle will accept a single argument of {@code exType},
4966      * and immediately throw it as an exception.
4967      * The method type will nominally specify a return of {@code returnType}.
4968      * The return type may be anything convenient:  It doesn't matter to the
4969      * method handle's behavior, since it will never return normally.
4970      * @param returnType the return type of the desired method handle
4971      * @param exType the parameter type of the desired method handle
4972      * @return method handle which can throw the given exceptions
4973      * @throws NullPointerException if either argument is null
4974      */
4975     public static
4976     MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
4977         if (!Throwable.class.isAssignableFrom(exType))
4978             throw new ClassCastException(exType.getName());
4979         return MethodHandleImpl.throwException(methodType(returnType, exType));
4980     }
4981 
4982     /**
4983      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
4984      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
4985      * delivers the loop's result, which is the return value of the resulting handle.
4986      * <p>
4987      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
4988      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
4989      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
4990      * terms of method handles, each clause will specify up to four independent actions:<ul>
4991      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
4992      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
4993      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
4994      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
4995      * </ul>
4996      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
4997      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
4998      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
4999      * <p>
5000      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
5001      * this case. See below for a detailed description.
5002      * <p>
5003      * <em>Parameters optional everywhere:</em>
5004      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
5005      * As an exception, the init functions cannot take any {@code v} parameters,
5006      * because those values are not yet computed when the init functions are executed.
5007      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
5008      * In fact, any clause function may take no arguments at all.
5009      * <p>
5010      * <em>Loop parameters:</em>
5011      * A clause function may take all the iteration variable values it is entitled to, in which case
5012      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
5013      * with their types and values notated as {@code (A...)} and {@code (a...)}.
5014      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
5015      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
5016      * init function is automatically a loop parameter {@code a}.)
5017      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
5018      * These loop parameters act as loop-invariant values visible across the whole loop.
5019      * <p>
5020      * <em>Parameters visible everywhere:</em>
5021      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
5022      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
5023      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
5024      * Most clause functions will not need all of this information, but they will be formally connected to it
5025      * as if by {@link #dropArguments}.
5026      * <a id="astar"></a>
5027      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
5028      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
5029      * In that notation, the general form of an init function parameter list
5030      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
5031      * <p>
5032      * <em>Checking clause structure:</em>
5033      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
5034      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
5035      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
5036      * met by the inputs to the loop combinator.
5037      * <p>
5038      * <em>Effectively identical sequences:</em>
5039      * <a id="effid"></a>
5040      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
5041      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
5042      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
5043      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
5044      * that longest list.
5045      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
5046      * and the same is true if more sequences of the form {@code (V... A*)} are added.
5047      * <p>
5048      * <em>Step 0: Determine clause structure.</em><ol type="a">
5049      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
5050      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
5051      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
5052      * four. Padding takes place by appending elements to the array.
5053      * <li>Clauses with all {@code null}s are disregarded.
5054      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
5055      * </ol>
5056      * <p>
5057      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
5058      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
5059      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
5060      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
5061      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
5062      * iteration variable type.
5063      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
5064      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
5065      * </ol>
5066      * <p>
5067      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
5068      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
5069      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
5070      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
5071      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
5072      * (These types will be checked in step 2, along with all the clause function types.)
5073      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
5074      * <li>All of the collected parameter lists must be effectively identical.
5075      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
5076      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
5077      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
5078      * the "internal parameter list".
5079      * </ul>
5080      * <p>
5081      * <em>Step 1C: Determine loop return type.</em><ol type="a">
5082      * <li>Examine fini function return types, disregarding omitted fini functions.
5083      * <li>If there are no fini functions, the loop return type is {@code void}.
5084      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
5085      * type.
5086      * </ol>
5087      * <p>
5088      * <em>Step 1D: Check other types.</em><ol type="a">
5089      * <li>There must be at least one non-omitted pred function.
5090      * <li>Every non-omitted pred function must have a {@code boolean} return type.
5091      * </ol>
5092      * <p>
5093      * <em>Step 2: Determine parameter lists.</em><ol type="a">
5094      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
5095      * <li>The parameter list for init functions will be adjusted to the external parameter list.
5096      * (Note that their parameter lists are already effectively identical to this list.)
5097      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
5098      * effectively identical to the internal parameter list {@code (V... A...)}.
5099      * </ol>
5100      * <p>
5101      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
5102      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
5103      * type.
5104      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
5105      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
5106      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
5107      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
5108      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
5109      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
5110      * loop return type.
5111      * </ol>
5112      * <p>
5113      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
5114      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
5115      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
5116      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
5117      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
5118      * pad out the end of the list.
5119      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
5120      * </ol>
5121      * <p>
5122      * <em>Final observations.</em><ol type="a">
5123      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
5124      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
5125      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
5126      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
5127      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
5128      * <li>Each pair of init and step functions agrees in their return type {@code V}.
5129      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
5130      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
5131      * </ol>
5132      * <p>
5133      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
5134      * <ul>
5135      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
5136      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
5137      * (Only one {@code Pn} has to be non-{@code null}.)
5138      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
5139      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
5140      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
5141      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
5142      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
5143      * the resulting loop handle's parameter types {@code (A...)}.
5144      * </ul>
5145      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
5146      * which is natural if most of the loop computation happens in the steps.  For some loops,
5147      * the burden of computation might be heaviest in the pred functions, and so the pred functions
5148      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
5149      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
5150      * where the init functions will need the extra parameters.  For such reasons, the rules for
5151      * determining these parameters are as symmetric as possible, across all clause parts.
5152      * In general, the loop parameters function as common invariant values across the whole
5153      * loop, while the iteration variables function as common variant values, or (if there is
5154      * no step function) as internal loop invariant temporaries.
5155      * <p>
5156      * <em>Loop execution.</em><ol type="a">
5157      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
5158      * every clause function. These locals are loop invariant.
5159      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
5160      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
5161      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
5162      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
5163      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
5164      * (in argument order).
5165      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
5166      * returns {@code false}.
5167      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
5168      * sequence {@code (v...)} of loop variables.
5169      * The updated value is immediately visible to all subsequent function calls.
5170      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
5171      * (of type {@code R}) is returned from the loop as a whole.
5172      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
5173      * except by throwing an exception.
5174      * </ol>
5175      * <p>
5176      * <em>Usage tips.</em>
5177      * <ul>
5178      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
5179      * sometimes a step function only needs to observe the current value of its own variable.
5180      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
5181      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
5182      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
5183      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
5184      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
5185      * <li>If some of the clause functions are virtual methods on an instance, the instance
5186      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
5187      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
5188      * will be the first iteration variable value, and it will be easy to use virtual
5189      * methods as clause parts, since all of them will take a leading instance reference matching that value.
5190      * </ul>
5191      * <p>
5192      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
5193      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
5194      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
5195      * <blockquote><pre>{@code
5196      * V... init...(A...);
5197      * boolean pred...(V..., A...);
5198      * V... step...(V..., A...);
5199      * R fini...(V..., A...);
5200      * R loop(A... a) {
5201      *   V... v... = init...(a...);
5202      *   for (;;) {
5203      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
5204      *       v = s(v..., a...);
5205      *       if (!p(v..., a...)) {
5206      *         return f(v..., a...);
5207      *       }
5208      *     }
5209      *   }
5210      * }
5211      * }</pre></blockquote>
5212      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
5213      * to their full length, even though individual clause functions may neglect to take them all.
5214      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
5215      *
5216      * @apiNote Example:
5217      * <blockquote><pre>{@code
5218      * // iterative implementation of the factorial function as a loop handle
5219      * static int one(int k) { return 1; }
5220      * static int inc(int i, int acc, int k) { return i + 1; }
5221      * static int mult(int i, int acc, int k) { return i * acc; }
5222      * static boolean pred(int i, int acc, int k) { return i < k; }
5223      * static int fin(int i, int acc, int k) { return acc; }
5224      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
5225      * // null initializer for counter, should initialize to 0
5226      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
5227      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
5228      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
5229      * assertEquals(120, loop.invoke(5));
5230      * }</pre></blockquote>
5231      * The same example, dropping arguments and using combinators:
5232      * <blockquote><pre>{@code
5233      * // simplified implementation of the factorial function as a loop handle
5234      * static int inc(int i) { return i + 1; } // drop acc, k
5235      * static int mult(int i, int acc) { return i * acc; } //drop k
5236      * static boolean cmp(int i, int k) { return i < k; }
5237      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
5238      * // null initializer for counter, should initialize to 0
5239      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
5240      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
5241      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
5242      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
5243      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
5244      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
5245      * assertEquals(720, loop.invoke(6));
5246      * }</pre></blockquote>
5247      * A similar example, using a helper object to hold a loop parameter:
5248      * <blockquote><pre>{@code
5249      * // instance-based implementation of the factorial function as a loop handle
5250      * static class FacLoop {
5251      *   final int k;
5252      *   FacLoop(int k) { this.k = k; }
5253      *   int inc(int i) { return i + 1; }
5254      *   int mult(int i, int acc) { return i * acc; }
5255      *   boolean pred(int i) { return i < k; }
5256      *   int fin(int i, int acc) { return acc; }
5257      * }
5258      * // assume MH_FacLoop is a handle to the constructor
5259      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
5260      * // null initializer for counter, should initialize to 0
5261      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
5262      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
5263      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
5264      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
5265      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
5266      * assertEquals(5040, loop.invoke(7));
5267      * }</pre></blockquote>
5268      *
5269      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
5270      *
5271      * @return a method handle embodying the looping behavior as defined by the arguments.
5272      *
5273      * @throws IllegalArgumentException in case any of the constraints described above is violated.
5274      *
5275      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
5276      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
5277      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
5278      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
5279      * @since 9
5280      */
5281     public static MethodHandle loop(MethodHandle[]... clauses) {
5282         // Step 0: determine clause structure.
5283         loopChecks0(clauses);
5284 
5285         List<MethodHandle> init = new ArrayList<>();
5286         List<MethodHandle> step = new ArrayList<>();
5287         List<MethodHandle> pred = new ArrayList<>();
5288         List<MethodHandle> fini = new ArrayList<>();
5289 
5290         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
5291             init.add(clause[0]); // all clauses have at least length 1
5292             step.add(clause.length <= 1 ? null : clause[1]);
5293             pred.add(clause.length <= 2 ? null : clause[2]);
5294             fini.add(clause.length <= 3 ? null : clause[3]);
5295         });
5296 
5297         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
5298         final int nclauses = init.size();
5299 
5300         // Step 1A: determine iteration variables (V...).
5301         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
5302         for (int i = 0; i < nclauses; ++i) {
5303             MethodHandle in = init.get(i);
5304             MethodHandle st = step.get(i);
5305             if (in == null && st == null) {
5306                 iterationVariableTypes.add(void.class);
5307             } else if (in != null && st != null) {
5308                 loopChecks1a(i, in, st);
5309                 iterationVariableTypes.add(in.type().returnType());
5310             } else {
5311                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
5312             }
5313         }
5314         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).
5315                 collect(Collectors.toList());
5316 
5317         // Step 1B: determine loop parameters (A...).
5318         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
5319         loopChecks1b(init, commonSuffix);
5320 
5321         // Step 1C: determine loop return type.
5322         // Step 1D: check other types.
5323         final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type).
5324                 map(MethodType::returnType).findFirst().orElse(void.class);
5325         loopChecks1cd(pred, fini, loopReturnType);
5326 
5327         // Step 2: determine parameter lists.
5328         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
5329         commonParameterSequence.addAll(commonSuffix);
5330         loopChecks2(step, pred, fini, commonParameterSequence);
5331 
5332         // Step 3: fill in omitted functions.
5333         for (int i = 0; i < nclauses; ++i) {
5334             Class<?> t = iterationVariableTypes.get(i);
5335             if (init.get(i) == null) {
5336                 init.set(i, empty(methodType(t, commonSuffix)));
5337             }
5338             if (step.get(i) == null) {
5339                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
5340             }
5341             if (pred.get(i) == null) {
5342                 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence));
5343             }
5344             if (fini.get(i) == null) {
5345                 fini.set(i, empty(methodType(t, commonParameterSequence)));
5346             }
5347         }
5348 
5349         // Step 4: fill in missing parameter types.
5350         // Also convert all handles to fixed-arity handles.
5351         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
5352         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
5353         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
5354         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
5355 
5356         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
5357                 allMatch(pl -> pl.equals(commonSuffix));
5358         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
5359                 allMatch(pl -> pl.equals(commonParameterSequence));
5360 
5361         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
5362     }
5363 
5364     private static void loopChecks0(MethodHandle[][] clauses) {
5365         if (clauses == null || clauses.length == 0) {
5366             throw newIllegalArgumentException("null or no clauses passed");
5367         }
5368         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
5369             throw newIllegalArgumentException("null clauses are not allowed");
5370         }
5371         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
5372             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
5373         }
5374     }
5375 
5376     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
5377         if (in.type().returnType() != st.type().returnType()) {
5378             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
5379                     st.type().returnType());
5380         }
5381     }
5382 
5383     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
5384         final List<Class<?>> empty = List.of();
5385         final List<Class<?>> longest = mhs.filter(Objects::nonNull).
5386                 // take only those that can contribute to a common suffix because they are longer than the prefix
5387                         map(MethodHandle::type).
5388                         filter(t -> t.parameterCount() > skipSize).
5389                         map(MethodType::parameterList).
5390                         reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
5391         return longest.size() == 0 ? empty : longest.subList(skipSize, longest.size());
5392     }
5393 
5394     private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) {
5395         final List<Class<?>> empty = List.of();
5396         return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
5397     }
5398 
5399     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
5400         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
5401         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
5402         return longestParameterList(Arrays.asList(longest1, longest2));
5403     }
5404 
5405     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
5406         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
5407                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
5408             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
5409                     " (common suffix: " + commonSuffix + ")");
5410         }
5411     }
5412 
5413     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
5414         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
5415                 anyMatch(t -> t != loopReturnType)) {
5416             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
5417                     loopReturnType + ")");
5418         }
5419 
5420         if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
5421             throw newIllegalArgumentException("no predicate found", pred);
5422         }
5423         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
5424                 anyMatch(t -> t != boolean.class)) {
5425             throw newIllegalArgumentException("predicates must have boolean return type", pred);
5426         }
5427     }
5428 
5429     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
5430         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
5431                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
5432             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
5433                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
5434         }
5435     }
5436 
5437     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
5438         return hs.stream().map(h -> {
5439             int pc = h.type().parameterCount();
5440             int tpsize = targetParams.size();
5441             return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h;
5442         }).collect(Collectors.toList());
5443     }
5444 
5445     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
5446         return hs.stream().map(MethodHandle::asFixedArity).collect(Collectors.toList());
5447     }
5448 
5449     /**
5450      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
5451      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
5452      * <p>
5453      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
5454      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
5455      * evaluates to {@code true}).
5456      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
5457      * <p>
5458      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
5459      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
5460      * and updated with the value returned from its invocation. The result of loop execution will be
5461      * the final value of the additional loop-local variable (if present).
5462      * <p>
5463      * The following rules hold for these argument handles:<ul>
5464      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
5465      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
5466      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
5467      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
5468      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
5469      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
5470      * It will constrain the parameter lists of the other loop parts.
5471      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
5472      * list {@code (A...)} is called the <em>external parameter list</em>.
5473      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
5474      * additional state variable of the loop.
5475      * The body must both accept and return a value of this type {@code V}.
5476      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
5477      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
5478      * <a href="MethodHandles.html#effid">effectively identical</a>
5479      * to the external parameter list {@code (A...)}.
5480      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
5481      * {@linkplain #empty default value}.
5482      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
5483      * Its parameter list (either empty or of the form {@code (V A*)}) must be
5484      * effectively identical to the internal parameter list.
5485      * </ul>
5486      * <p>
5487      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
5488      * <li>The loop handle's result type is the result type {@code V} of the body.
5489      * <li>The loop handle's parameter types are the types {@code (A...)},
5490      * from the external parameter list.
5491      * </ul>
5492      * <p>
5493      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
5494      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
5495      * passed to the loop.
5496      * <blockquote><pre>{@code
5497      * V init(A...);
5498      * boolean pred(V, A...);
5499      * V body(V, A...);
5500      * V whileLoop(A... a...) {
5501      *   V v = init(a...);
5502      *   while (pred(v, a...)) {
5503      *     v = body(v, a...);
5504      *   }
5505      *   return v;
5506      * }
5507      * }</pre></blockquote>
5508      *
5509      * @apiNote Example:
5510      * <blockquote><pre>{@code
5511      * // implement the zip function for lists as a loop handle
5512      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
5513      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
5514      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
5515      *   zip.add(a.next());
5516      *   zip.add(b.next());
5517      *   return zip;
5518      * }
5519      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
5520      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
5521      * List<String> a = Arrays.asList("a", "b", "c", "d");
5522      * List<String> b = Arrays.asList("e", "f", "g", "h");
5523      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
5524      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
5525      * }</pre></blockquote>
5526      *
5527      *
5528      * @apiNote The implementation of this method can be expressed as follows:
5529      * <blockquote><pre>{@code
5530      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
5531      *     MethodHandle fini = (body.type().returnType() == void.class
5532      *                         ? null : identity(body.type().returnType()));
5533      *     MethodHandle[]
5534      *         checkExit = { null, null, pred, fini },
5535      *         varBody   = { init, body };
5536      *     return loop(checkExit, varBody);
5537      * }
5538      * }</pre></blockquote>
5539      *
5540      * @param init optional initializer, providing the initial value of the loop variable.
5541      *             May be {@code null}, implying a default initial value.  See above for other constraints.
5542      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
5543      *             above for other constraints.
5544      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
5545      *             See above for other constraints.
5546      *
5547      * @return a method handle implementing the {@code while} loop as described by the arguments.
5548      * @throws IllegalArgumentException if the rules for the arguments are violated.
5549      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
5550      *
5551      * @see #loop(MethodHandle[][])
5552      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
5553      * @since 9
5554      */
5555     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
5556         whileLoopChecks(init, pred, body);
5557         MethodHandle fini = identityOrVoid(body.type().returnType());
5558         MethodHandle[] checkExit = { null, null, pred, fini };
5559         MethodHandle[] varBody = { init, body };
5560         return loop(checkExit, varBody);
5561     }
5562 
5563     /**
5564      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
5565      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
5566      * <p>
5567      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
5568      * method will, in each iteration, first execute its body and then evaluate the predicate.
5569      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
5570      * <p>
5571      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
5572      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
5573      * and updated with the value returned from its invocation. The result of loop execution will be
5574      * the final value of the additional loop-local variable (if present).
5575      * <p>
5576      * The following rules hold for these argument handles:<ul>
5577      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
5578      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
5579      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
5580      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
5581      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
5582      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
5583      * It will constrain the parameter lists of the other loop parts.
5584      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
5585      * list {@code (A...)} is called the <em>external parameter list</em>.
5586      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
5587      * additional state variable of the loop.
5588      * The body must both accept and return a value of this type {@code V}.
5589      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
5590      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
5591      * <a href="MethodHandles.html#effid">effectively identical</a>
5592      * to the external parameter list {@code (A...)}.
5593      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
5594      * {@linkplain #empty default value}.
5595      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
5596      * Its parameter list (either empty or of the form {@code (V A*)}) must be
5597      * effectively identical to the internal parameter list.
5598      * </ul>
5599      * <p>
5600      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
5601      * <li>The loop handle's result type is the result type {@code V} of the body.
5602      * <li>The loop handle's parameter types are the types {@code (A...)},
5603      * from the external parameter list.
5604      * </ul>
5605      * <p>
5606      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
5607      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
5608      * passed to the loop.
5609      * <blockquote><pre>{@code
5610      * V init(A...);
5611      * boolean pred(V, A...);
5612      * V body(V, A...);
5613      * V doWhileLoop(A... a...) {
5614      *   V v = init(a...);
5615      *   do {
5616      *     v = body(v, a...);
5617      *   } while (pred(v, a...));
5618      *   return v;
5619      * }
5620      * }</pre></blockquote>
5621      *
5622      * @apiNote Example:
5623      * <blockquote><pre>{@code
5624      * // int i = 0; while (i < limit) { ++i; } return i; => limit
5625      * static int zero(int limit) { return 0; }
5626      * static int step(int i, int limit) { return i + 1; }
5627      * static boolean pred(int i, int limit) { return i < limit; }
5628      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
5629      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
5630      * assertEquals(23, loop.invoke(23));
5631      * }</pre></blockquote>
5632      *
5633      *
5634      * @apiNote The implementation of this method can be expressed as follows:
5635      * <blockquote><pre>{@code
5636      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
5637      *     MethodHandle fini = (body.type().returnType() == void.class
5638      *                         ? null : identity(body.type().returnType()));
5639      *     MethodHandle[] clause = { init, body, pred, fini };
5640      *     return loop(clause);
5641      * }
5642      * }</pre></blockquote>
5643      *
5644      * @param init optional initializer, providing the initial value of the loop variable.
5645      *             May be {@code null}, implying a default initial value.  See above for other constraints.
5646      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
5647      *             See above for other constraints.
5648      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
5649      *             above for other constraints.
5650      *
5651      * @return a method handle implementing the {@code while} loop as described by the arguments.
5652      * @throws IllegalArgumentException if the rules for the arguments are violated.
5653      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
5654      *
5655      * @see #loop(MethodHandle[][])
5656      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
5657      * @since 9
5658      */
5659     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
5660         whileLoopChecks(init, pred, body);
5661         MethodHandle fini = identityOrVoid(body.type().returnType());
5662         MethodHandle[] clause = {init, body, pred, fini };
5663         return loop(clause);
5664     }
5665 
5666     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
5667         Objects.requireNonNull(pred);
5668         Objects.requireNonNull(body);
5669         MethodType bodyType = body.type();
5670         Class<?> returnType = bodyType.returnType();
5671         List<Class<?>> innerList = bodyType.parameterList();
5672         List<Class<?>> outerList = innerList;
5673         if (returnType == void.class) {
5674             // OK
5675         } else if (innerList.size() == 0 || innerList.get(0) != returnType) {
5676             // leading V argument missing => error
5677             MethodType expected = bodyType.insertParameterTypes(0, returnType);
5678             throw misMatchedTypes("body function", bodyType, expected);
5679         } else {
5680             outerList = innerList.subList(1, innerList.size());
5681         }
5682         MethodType predType = pred.type();
5683         if (predType.returnType() != boolean.class ||
5684                 !predType.effectivelyIdenticalParameters(0, innerList)) {
5685             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
5686         }
5687         if (init != null) {
5688             MethodType initType = init.type();
5689             if (initType.returnType() != returnType ||
5690                     !initType.effectivelyIdenticalParameters(0, outerList)) {
5691                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
5692             }
5693         }
5694     }
5695 
5696     /**
5697      * Constructs a loop that runs a given number of iterations.
5698      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
5699      * <p>
5700      * The number of iterations is determined by the {@code iterations} handle evaluation result.
5701      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
5702      * It will be initialized to 0 and incremented by 1 in each iteration.
5703      * <p>
5704      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
5705      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
5706      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
5707      * <p>
5708      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
5709      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
5710      * iteration variable.
5711      * The result of the loop handle execution will be the final {@code V} value of that variable
5712      * (or {@code void} if there is no {@code V} variable).
5713      * <p>
5714      * The following rules hold for the argument handles:<ul>
5715      * <li>The {@code iterations} handle must not be {@code null}, and must return
5716      * the type {@code int}, referred to here as {@code I} in parameter type lists.
5717      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
5718      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
5719      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
5720      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
5721      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
5722      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
5723      * of types called the <em>internal parameter list</em>.
5724      * It will constrain the parameter lists of the other loop parts.
5725      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
5726      * with no additional {@code A} types, then the internal parameter list is extended by
5727      * the argument types {@code A...} of the {@code iterations} handle.
5728      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
5729      * list {@code (A...)} is called the <em>external parameter list</em>.
5730      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
5731      * additional state variable of the loop.
5732      * The body must both accept a leading parameter and return a value of this type {@code V}.
5733      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
5734      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
5735      * <a href="MethodHandles.html#effid">effectively identical</a>
5736      * to the external parameter list {@code (A...)}.
5737      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
5738      * {@linkplain #empty default value}.
5739      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
5740      * effectively identical to the external parameter list {@code (A...)}.
5741      * </ul>
5742      * <p>
5743      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
5744      * <li>The loop handle's result type is the result type {@code V} of the body.
5745      * <li>The loop handle's parameter types are the types {@code (A...)},
5746      * from the external parameter list.
5747      * </ul>
5748      * <p>
5749      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
5750      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
5751      * arguments passed to the loop.
5752      * <blockquote><pre>{@code
5753      * int iterations(A...);
5754      * V init(A...);
5755      * V body(V, int, A...);
5756      * V countedLoop(A... a...) {
5757      *   int end = iterations(a...);
5758      *   V v = init(a...);
5759      *   for (int i = 0; i < end; ++i) {
5760      *     v = body(v, i, a...);
5761      *   }
5762      *   return v;
5763      * }
5764      * }</pre></blockquote>
5765      *
5766      * @apiNote Example with a fully conformant body method:
5767      * <blockquote><pre>{@code
5768      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
5769      * // => a variation on a well known theme
5770      * static String step(String v, int counter, String init) { return "na " + v; }
5771      * // assume MH_step is a handle to the method above
5772      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
5773      * MethodHandle start = MethodHandles.identity(String.class);
5774      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
5775      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
5776      * }</pre></blockquote>
5777      *
5778      * @apiNote Example with the simplest possible body method type,
5779      * and passing the number of iterations to the loop invocation:
5780      * <blockquote><pre>{@code
5781      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
5782      * // => a variation on a well known theme
5783      * static String step(String v, int counter ) { return "na " + v; }
5784      * // assume MH_step is a handle to the method above
5785      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
5786      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
5787      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
5788      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
5789      * }</pre></blockquote>
5790      *
5791      * @apiNote Example that treats the number of iterations, string to append to, and string to append
5792      * as loop parameters:
5793      * <blockquote><pre>{@code
5794      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
5795      * // => a variation on a well known theme
5796      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
5797      * // assume MH_step is a handle to the method above
5798      * MethodHandle count = MethodHandles.identity(int.class);
5799      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
5800      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
5801      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
5802      * }</pre></blockquote>
5803      *
5804      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
5805      * to enforce a loop type:
5806      * <blockquote><pre>{@code
5807      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
5808      * // => a variation on a well known theme
5809      * static String step(String v, int counter, String pre) { return pre + " " + v; }
5810      * // assume MH_step is a handle to the method above
5811      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
5812      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
5813      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
5814      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
5815      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
5816      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
5817      * }</pre></blockquote>
5818      *
5819      * @apiNote The implementation of this method can be expressed as follows:
5820      * <blockquote><pre>{@code
5821      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
5822      *     return countedLoop(empty(iterations.type()), iterations, init, body);
5823      * }
5824      * }</pre></blockquote>
5825      *
5826      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
5827      *                   result type must be {@code int}. See above for other constraints.
5828      * @param init optional initializer, providing the initial value of the loop variable.
5829      *             May be {@code null}, implying a default initial value.  See above for other constraints.
5830      * @param body body of the loop, which may not be {@code null}.
5831      *             It controls the loop parameters and result type in the standard case (see above for details).
5832      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
5833      *             and may accept any number of additional types.
5834      *             See above for other constraints.
5835      *
5836      * @return a method handle representing the loop.
5837      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
5838      * @throws IllegalArgumentException if any argument violates the rules formulated above.
5839      *
5840      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
5841      * @since 9
5842      */
5843     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
5844         return countedLoop(empty(iterations.type()), iterations, init, body);
5845     }
5846 
5847     /**
5848      * Constructs a loop that counts over a range of numbers.
5849      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
5850      * <p>
5851      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
5852      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
5853      * values of the loop counter.
5854      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
5855      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
5856      * <p>
5857      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
5858      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
5859      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
5860      * <p>
5861      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
5862      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
5863      * iteration variable.
5864      * The result of the loop handle execution will be the final {@code V} value of that variable
5865      * (or {@code void} if there is no {@code V} variable).
5866      * <p>
5867      * The following rules hold for the argument handles:<ul>
5868      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
5869      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
5870      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
5871      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
5872      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
5873      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
5874      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
5875      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
5876      * of types called the <em>internal parameter list</em>.
5877      * It will constrain the parameter lists of the other loop parts.
5878      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
5879      * with no additional {@code A} types, then the internal parameter list is extended by
5880      * the argument types {@code A...} of the {@code end} handle.
5881      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
5882      * list {@code (A...)} is called the <em>external parameter list</em>.
5883      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
5884      * additional state variable of the loop.
5885      * The body must both accept a leading parameter and return a value of this type {@code V}.
5886      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
5887      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
5888      * <a href="MethodHandles.html#effid">effectively identical</a>
5889      * to the external parameter list {@code (A...)}.
5890      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
5891      * {@linkplain #empty default value}.
5892      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
5893      * effectively identical to the external parameter list {@code (A...)}.
5894      * <li>Likewise, the parameter list of {@code end} must be effectively identical
5895      * to the external parameter list.
5896      * </ul>
5897      * <p>
5898      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
5899      * <li>The loop handle's result type is the result type {@code V} of the body.
5900      * <li>The loop handle's parameter types are the types {@code (A...)},
5901      * from the external parameter list.
5902      * </ul>
5903      * <p>
5904      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
5905      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
5906      * arguments passed to the loop.
5907      * <blockquote><pre>{@code
5908      * int start(A...);
5909      * int end(A...);
5910      * V init(A...);
5911      * V body(V, int, A...);
5912      * V countedLoop(A... a...) {
5913      *   int e = end(a...);
5914      *   int s = start(a...);
5915      *   V v = init(a...);
5916      *   for (int i = s; i < e; ++i) {
5917      *     v = body(v, i, a...);
5918      *   }
5919      *   return v;
5920      * }
5921      * }</pre></blockquote>
5922      *
5923      * @apiNote The implementation of this method can be expressed as follows:
5924      * <blockquote><pre>{@code
5925      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
5926      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
5927      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
5928      *     // the following semantics:
5929      *     // MH_increment: (int limit, int counter) -> counter + 1
5930      *     // MH_predicate: (int limit, int counter) -> counter < limit
5931      *     Class<?> counterType = start.type().returnType();  // int
5932      *     Class<?> returnType = body.type().returnType();
5933      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
5934      *     if (returnType != void.class) {  // ignore the V variable
5935      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
5936      *         pred = dropArguments(pred, 1, returnType);  // ditto
5937      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
5938      *     }
5939      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
5940      *     MethodHandle[]
5941      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
5942      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
5943      *         indexVar   = { start, incr };           // i = start(); i = i + 1
5944      *     return loop(loopLimit, bodyClause, indexVar);
5945      * }
5946      * }</pre></blockquote>
5947      *
5948      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
5949      *              See above for other constraints.
5950      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
5951      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
5952      * @param init optional initializer, providing the initial value of the loop variable.
5953      *             May be {@code null}, implying a default initial value.  See above for other constraints.
5954      * @param body body of the loop, which may not be {@code null}.
5955      *             It controls the loop parameters and result type in the standard case (see above for details).
5956      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
5957      *             and may accept any number of additional types.
5958      *             See above for other constraints.
5959      *
5960      * @return a method handle representing the loop.
5961      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
5962      * @throws IllegalArgumentException if any argument violates the rules formulated above.
5963      *
5964      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
5965      * @since 9
5966      */
5967     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
5968         countedLoopChecks(start, end, init, body);
5969         Class<?> counterType = start.type().returnType();  // int, but who's counting?
5970         Class<?> limitType   = end.type().returnType();    // yes, int again
5971         Class<?> returnType  = body.type().returnType();
5972         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
5973         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
5974         MethodHandle retv = null;
5975         if (returnType != void.class) {
5976             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
5977             pred = dropArguments(pred, 1, returnType);  // ditto
5978             retv = dropArguments(identity(returnType), 0, counterType);
5979         }
5980         body = dropArguments(body, 0, counterType);  // ignore the limit variable
5981         MethodHandle[]
5982             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
5983             bodyClause = { init, body },            // v = init(); v = body(v, i)
5984             indexVar   = { start, incr };           // i = start(); i = i + 1
5985         return loop(loopLimit, bodyClause, indexVar);
5986     }
5987 
5988     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
5989         Objects.requireNonNull(start);
5990         Objects.requireNonNull(end);
5991         Objects.requireNonNull(body);
5992         Class<?> counterType = start.type().returnType();
5993         if (counterType != int.class) {
5994             MethodType expected = start.type().changeReturnType(int.class);
5995             throw misMatchedTypes("start function", start.type(), expected);
5996         } else if (end.type().returnType() != counterType) {
5997             MethodType expected = end.type().changeReturnType(counterType);
5998             throw misMatchedTypes("end function", end.type(), expected);
5999         }
6000         MethodType bodyType = body.type();
6001         Class<?> returnType = bodyType.returnType();
6002         List<Class<?>> innerList = bodyType.parameterList();
6003         // strip leading V value if present
6004         int vsize = (returnType == void.class ? 0 : 1);
6005         if (vsize != 0 && (innerList.size() == 0 || innerList.get(0) != returnType)) {
6006             // argument list has no "V" => error
6007             MethodType expected = bodyType.insertParameterTypes(0, returnType);
6008             throw misMatchedTypes("body function", bodyType, expected);
6009         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
6010             // missing I type => error
6011             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
6012             throw misMatchedTypes("body function", bodyType, expected);
6013         }
6014         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
6015         if (outerList.isEmpty()) {
6016             // special case; take lists from end handle
6017             outerList = end.type().parameterList();
6018             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
6019         }
6020         MethodType expected = methodType(counterType, outerList);
6021         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
6022             throw misMatchedTypes("start parameter types", start.type(), expected);
6023         }
6024         if (end.type() != start.type() &&
6025             !end.type().effectivelyIdenticalParameters(0, outerList)) {
6026             throw misMatchedTypes("end parameter types", end.type(), expected);
6027         }
6028         if (init != null) {
6029             MethodType initType = init.type();
6030             if (initType.returnType() != returnType ||
6031                 !initType.effectivelyIdenticalParameters(0, outerList)) {
6032                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
6033             }
6034         }
6035     }
6036 
6037     /**
6038      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
6039      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6040      * <p>
6041      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
6042      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
6043      * <p>
6044      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
6045      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
6046      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
6047      * <p>
6048      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
6049      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
6050      * iteration variable.
6051      * The result of the loop handle execution will be the final {@code V} value of that variable
6052      * (or {@code void} if there is no {@code V} variable).
6053      * <p>
6054      * The following rules hold for the argument handles:<ul>
6055      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6056      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
6057      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6058      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
6059      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
6060      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
6061      * of types called the <em>internal parameter list</em>.
6062      * It will constrain the parameter lists of the other loop parts.
6063      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
6064      * with no additional {@code A} types, then the internal parameter list is extended by
6065      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
6066      * single type {@code Iterable} is added and constitutes the {@code A...} list.
6067      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
6068      * list {@code (A...)} is called the <em>external parameter list</em>.
6069      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6070      * additional state variable of the loop.
6071      * The body must both accept a leading parameter and return a value of this type {@code V}.
6072      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6073      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6074      * <a href="MethodHandles.html#effid">effectively identical</a>
6075      * to the external parameter list {@code (A...)}.
6076      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6077      * {@linkplain #empty default value}.
6078      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
6079      * type {@code java.util.Iterator} or a subtype thereof.
6080      * The iterator it produces when the loop is executed will be assumed
6081      * to yield values which can be converted to type {@code T}.
6082      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
6083      * effectively identical to the external parameter list {@code (A...)}.
6084      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
6085      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
6086      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
6087      * handle parameter is adjusted to accept the leading {@code A} type, as if by
6088      * the {@link MethodHandle#asType asType} conversion method.
6089      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
6090      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
6091      * </ul>
6092      * <p>
6093      * The type {@code T} may be either a primitive or reference.
6094      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
6095      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
6096      * as if by the {@link MethodHandle#asType asType} conversion method.
6097      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
6098      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
6099      * <p>
6100      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6101      * <li>The loop handle's result type is the result type {@code V} of the body.
6102      * <li>The loop handle's parameter types are the types {@code (A...)},
6103      * from the external parameter list.
6104      * </ul>
6105      * <p>
6106      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6107      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
6108      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
6109      * <blockquote><pre>{@code
6110      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
6111      * V init(A...);
6112      * V body(V,T,A...);
6113      * V iteratedLoop(A... a...) {
6114      *   Iterator<T> it = iterator(a...);
6115      *   V v = init(a...);
6116      *   while (it.hasNext()) {
6117      *     T t = it.next();
6118      *     v = body(v, t, a...);
6119      *   }
6120      *   return v;
6121      * }
6122      * }</pre></blockquote>
6123      *
6124      * @apiNote Example:
6125      * <blockquote><pre>{@code
6126      * // get an iterator from a list
6127      * static List<String> reverseStep(List<String> r, String e) {
6128      *   r.add(0, e);
6129      *   return r;
6130      * }
6131      * static List<String> newArrayList() { return new ArrayList<>(); }
6132      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
6133      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
6134      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
6135      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
6136      * assertEquals(reversedList, (List<String>) loop.invoke(list));
6137      * }</pre></blockquote>
6138      *
6139      * @apiNote The implementation of this method can be expressed approximately as follows:
6140      * <blockquote><pre>{@code
6141      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
6142      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
6143      *     Class<?> returnType = body.type().returnType();
6144      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
6145      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
6146      *     MethodHandle retv = null, step = body, startIter = iterator;
6147      *     if (returnType != void.class) {
6148      *         // the simple thing first:  in (I V A...), drop the I to get V
6149      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
6150      *         // body type signature (V T A...), internal loop types (I V A...)
6151      *         step = swapArguments(body, 0, 1);  // swap V <-> T
6152      *     }
6153      *     if (startIter == null)  startIter = MH_getIter;
6154      *     MethodHandle[]
6155      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
6156      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
6157      *     return loop(iterVar, bodyClause);
6158      * }
6159      * }</pre></blockquote>
6160      *
6161      * @param iterator an optional handle to return the iterator to start the loop.
6162      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
6163      *                 See above for other constraints.
6164      * @param init optional initializer, providing the initial value of the loop variable.
6165      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6166      * @param body body of the loop, which may not be {@code null}.
6167      *             It controls the loop parameters and result type in the standard case (see above for details).
6168      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
6169      *             and may accept any number of additional types.
6170      *             See above for other constraints.
6171      *
6172      * @return a method handle embodying the iteration loop functionality.
6173      * @throws NullPointerException if the {@code body} handle is {@code null}.
6174      * @throws IllegalArgumentException if any argument violates the above requirements.
6175      *
6176      * @since 9
6177      */
6178     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
6179         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
6180         Class<?> returnType = body.type().returnType();
6181         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
6182         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
6183         MethodHandle startIter;
6184         MethodHandle nextVal;
6185         {
6186             MethodType iteratorType;
6187             if (iterator == null) {
6188                 // derive argument type from body, if available, else use Iterable
6189                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
6190                 iteratorType = startIter.type().changeParameterType(0, iterableType);
6191             } else {
6192                 // force return type to the internal iterator class
6193                 iteratorType = iterator.type().changeReturnType(Iterator.class);
6194                 startIter = iterator;
6195             }
6196             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
6197             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
6198 
6199             // perform the asType transforms under an exception transformer, as per spec.:
6200             try {
6201                 startIter = startIter.asType(iteratorType);
6202                 nextVal = nextRaw.asType(nextValType);
6203             } catch (WrongMethodTypeException ex) {
6204                 throw new IllegalArgumentException(ex);
6205             }
6206         }
6207 
6208         MethodHandle retv = null, step = body;
6209         if (returnType != void.class) {
6210             // the simple thing first:  in (I V A...), drop the I to get V
6211             retv = dropArguments(identity(returnType), 0, Iterator.class);
6212             // body type signature (V T A...), internal loop types (I V A...)
6213             step = swapArguments(body, 0, 1);  // swap V <-> T
6214         }
6215 
6216         MethodHandle[]
6217             iterVar    = { startIter, null, hasNext, retv },
6218             bodyClause = { init, filterArgument(step, 0, nextVal) };
6219         return loop(iterVar, bodyClause);
6220     }
6221 
6222     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
6223         Objects.requireNonNull(body);
6224         MethodType bodyType = body.type();
6225         Class<?> returnType = bodyType.returnType();
6226         List<Class<?>> internalParamList = bodyType.parameterList();
6227         // strip leading V value if present
6228         int vsize = (returnType == void.class ? 0 : 1);
6229         if (vsize != 0 && (internalParamList.size() == 0 || internalParamList.get(0) != returnType)) {
6230             // argument list has no "V" => error
6231             MethodType expected = bodyType.insertParameterTypes(0, returnType);
6232             throw misMatchedTypes("body function", bodyType, expected);
6233         } else if (internalParamList.size() <= vsize) {
6234             // missing T type => error
6235             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
6236             throw misMatchedTypes("body function", bodyType, expected);
6237         }
6238         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
6239         Class<?> iterableType = null;
6240         if (iterator != null) {
6241             // special case; if the body handle only declares V and T then
6242             // the external parameter list is obtained from iterator handle
6243             if (externalParamList.isEmpty()) {
6244                 externalParamList = iterator.type().parameterList();
6245             }
6246             MethodType itype = iterator.type();
6247             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
6248                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
6249             }
6250             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
6251                 MethodType expected = methodType(itype.returnType(), externalParamList);
6252                 throw misMatchedTypes("iterator parameters", itype, expected);
6253             }
6254         } else {
6255             if (externalParamList.isEmpty()) {
6256                 // special case; if the iterator handle is null and the body handle
6257                 // only declares V and T then the external parameter list consists
6258                 // of Iterable
6259                 externalParamList = Arrays.asList(Iterable.class);
6260                 iterableType = Iterable.class;
6261             } else {
6262                 // special case; if the iterator handle is null and the external
6263                 // parameter list is not empty then the first parameter must be
6264                 // assignable to Iterable
6265                 iterableType = externalParamList.get(0);
6266                 if (!Iterable.class.isAssignableFrom(iterableType)) {
6267                     throw newIllegalArgumentException(
6268                             "inferred first loop argument must inherit from Iterable: " + iterableType);
6269                 }
6270             }
6271         }
6272         if (init != null) {
6273             MethodType initType = init.type();
6274             if (initType.returnType() != returnType ||
6275                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
6276                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
6277             }
6278         }
6279         return iterableType;  // help the caller a bit
6280     }
6281 
6282     /*non-public*/ static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
6283         // there should be a better way to uncross my wires
6284         int arity = mh.type().parameterCount();
6285         int[] order = new int[arity];
6286         for (int k = 0; k < arity; k++)  order[k] = k;
6287         order[i] = j; order[j] = i;
6288         Class<?>[] types = mh.type().parameterArray();
6289         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
6290         MethodType swapType = methodType(mh.type().returnType(), types);
6291         return permuteArguments(mh, swapType, order);
6292     }
6293 
6294     /**
6295      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
6296      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
6297      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
6298      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
6299      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
6300      * {@code try-finally} handle.
6301      * <p>
6302      * The {@code cleanup} handle will be passed one or two additional leading arguments.
6303      * The first is the exception thrown during the
6304      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
6305      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
6306      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
6307      * The second argument is not present if the {@code target} handle has a {@code void} return type.
6308      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
6309      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
6310      * <p>
6311      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
6312      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
6313      * two extra leading parameters:<ul>
6314      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
6315      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
6316      * the result from the execution of the {@code target} handle.
6317      * This parameter is not present if the {@code target} returns {@code void}.
6318      * </ul>
6319      * <p>
6320      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
6321      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
6322      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
6323      * the cleanup.
6324      * <blockquote><pre>{@code
6325      * V target(A..., B...);
6326      * V cleanup(Throwable, V, A...);
6327      * V adapter(A... a, B... b) {
6328      *   V result = (zero value for V);
6329      *   Throwable throwable = null;
6330      *   try {
6331      *     result = target(a..., b...);
6332      *   } catch (Throwable t) {
6333      *     throwable = t;
6334      *     throw t;
6335      *   } finally {
6336      *     result = cleanup(throwable, result, a...);
6337      *   }
6338      *   return result;
6339      * }
6340      * }</pre></blockquote>
6341      * <p>
6342      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6343      * be modified by execution of the target, and so are passed unchanged
6344      * from the caller to the cleanup, if it is invoked.
6345      * <p>
6346      * The target and cleanup must return the same type, even if the cleanup
6347      * always throws.
6348      * To create such a throwing cleanup, compose the cleanup logic
6349      * with {@link #throwException throwException},
6350      * in order to create a method handle of the correct return type.
6351      * <p>
6352      * Note that {@code tryFinally} never converts exceptions into normal returns.
6353      * In rare cases where exceptions must be converted in that way, first wrap
6354      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
6355      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
6356      * <p>
6357      * It is recommended that the first parameter type of {@code cleanup} be
6358      * declared {@code Throwable} rather than a narrower subtype.  This ensures
6359      * {@code cleanup} will always be invoked with whatever exception that
6360      * {@code target} throws.  Declaring a narrower type may result in a
6361      * {@code ClassCastException} being thrown by the {@code try-finally}
6362      * handle if the type of the exception thrown by {@code target} is not
6363      * assignable to the first parameter type of {@code cleanup}.  Note that
6364      * various exception types of {@code VirtualMachineError},
6365      * {@code LinkageError}, and {@code RuntimeException} can in principle be
6366      * thrown by almost any kind of Java code, and a finally clause that
6367      * catches (say) only {@code IOException} would mask any of the others
6368      * behind a {@code ClassCastException}.
6369      *
6370      * @param target the handle whose execution is to be wrapped in a {@code try} block.
6371      * @param cleanup the handle that is invoked in the finally block.
6372      *
6373      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
6374      * @throws NullPointerException if any argument is null
6375      * @throws IllegalArgumentException if {@code cleanup} does not accept
6376      *          the required leading arguments, or if the method handle types do
6377      *          not match in their return types and their
6378      *          corresponding trailing parameters
6379      *
6380      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
6381      * @since 9
6382      */
6383     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
6384         List<Class<?>> targetParamTypes = target.type().parameterList();
6385         Class<?> rtype = target.type().returnType();
6386 
6387         tryFinallyChecks(target, cleanup);
6388 
6389         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
6390         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
6391         // target parameter list.
6392         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
6393 
6394         // Ensure that the intrinsic type checks the instance thrown by the
6395         // target against the first parameter of cleanup
6396         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
6397 
6398         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
6399         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
6400     }
6401 
6402     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
6403         Class<?> rtype = target.type().returnType();
6404         if (rtype != cleanup.type().returnType()) {
6405             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
6406         }
6407         MethodType cleanupType = cleanup.type();
6408         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
6409             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
6410         }
6411         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
6412             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
6413         }
6414         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
6415         // target parameter list.
6416         int cleanupArgIndex = rtype == void.class ? 1 : 2;
6417         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
6418             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
6419                     cleanup.type(), target.type());
6420         }
6421     }
6422 
6423 }