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