1 /*
   2  * Copyright (c) 2008, 2023, 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.SharedSecrets;
  29 import jdk.internal.misc.Unsafe;
  30 import jdk.internal.misc.VM;
  31 import jdk.internal.org.objectweb.asm.ClassReader;
  32 import jdk.internal.org.objectweb.asm.Opcodes;
  33 import jdk.internal.org.objectweb.asm.Type;
  34 import jdk.internal.reflect.CallerSensitive;
  35 import jdk.internal.reflect.CallerSensitiveAdapter;
  36 import jdk.internal.reflect.Reflection;
  37 import jdk.internal.util.ClassFileDumper;
  38 import jdk.internal.value.ValueClass;
  39 import jdk.internal.vm.annotation.ForceInline;
  40 import sun.invoke.util.ValueConversions;
  41 import sun.invoke.util.VerifyAccess;
  42 import sun.invoke.util.Wrapper;
  43 import sun.reflect.misc.ReflectUtil;
  44 import sun.security.util.SecurityConstants;
  45 
  46 import java.lang.constant.ConstantDescs;
  47 import java.lang.invoke.LambdaForm.BasicType;
  48 import java.lang.reflect.Constructor;
  49 import java.lang.reflect.Field;
  50 import java.lang.reflect.Member;
  51 import java.lang.reflect.Method;
  52 import java.lang.reflect.Modifier;
  53 import java.nio.ByteOrder;
  54 import java.security.ProtectionDomain;
  55 import java.util.ArrayList;
  56 import java.util.Arrays;
  57 import java.util.BitSet;
  58 import java.util.Comparator;
  59 import java.util.Iterator;
  60 import java.util.List;
  61 import java.util.Objects;
  62 import java.util.Set;
  63 import java.util.concurrent.ConcurrentHashMap;
  64 import java.util.stream.Stream;
  65 
  66 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
  67 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  68 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  69 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
  70 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  71 import static java.lang.invoke.MethodHandleStatics.newInternalError;
  72 import static java.lang.invoke.MethodType.methodType;
  73 
  74 /**
  75  * This class consists exclusively of static methods that operate on or return
  76  * method handles. They fall into several categories:
  77  * <ul>
  78  * <li>Lookup methods which help create method handles for methods and fields.
  79  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  80  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  81  * </ul>
  82  * A lookup, combinator, or factory method will fail and throw an
  83  * {@code IllegalArgumentException} if the created method handle's type
  84  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  85  *
  86  * @author John Rose, JSR 292 EG
  87  * @since 1.7
  88  */
  89 public class MethodHandles {
  90 
  91     private MethodHandles() { }  // do not instantiate
  92 
  93     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  94 
  95     // See IMPL_LOOKUP below.
  96 
  97     //// Method handle creation from ordinary methods.
  98 
  99     /**
 100      * Returns a {@link Lookup lookup object} with
 101      * full capabilities to emulate all supported bytecode behaviors of the caller.
 102      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
 103      * Factory methods on the lookup object can create
 104      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
 105      * for any member that the caller has access to via bytecodes,
 106      * including protected and private fields and methods.
 107      * This lookup object is created by the original lookup class
 108      * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
 109      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 110      * Do not store it in place where untrusted code can access it.
 111      * <p>
 112      * This method is caller sensitive, which means that it may return different
 113      * values to different callers.
 114      * In cases where {@code MethodHandles.lookup} is called from a context where
 115      * there is no caller frame on the stack (e.g. when called directly
 116      * from a JNI attached thread), {@code IllegalCallerException} is thrown.
 117      * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will
 118      * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()}
 119      * to obtain a low-privileged lookup instead.
 120      * @return a lookup object for the caller of this method, with
 121      * {@linkplain Lookup#ORIGINAL original} and
 122      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
 123      * @throws IllegalCallerException if there is no caller frame on the stack.
 124      */
 125     @CallerSensitive
 126     @ForceInline // to ensure Reflection.getCallerClass optimization
 127     public static Lookup lookup() {
 128         final Class<?> c = Reflection.getCallerClass();
 129         if (c == null) {
 130             throw new IllegalCallerException("no caller frame");
 131         }
 132         return new Lookup(c);
 133     }
 134 
 135     /**
 136      * This lookup method is the alternate implementation of
 137      * the lookup method with a leading caller class argument which is
 138      * non-caller-sensitive.  This method is only invoked by reflection
 139      * and method handle.
 140      */
 141     @CallerSensitiveAdapter
 142     private static Lookup lookup(Class<?> caller) {
 143         if (caller.getClassLoader() == null) {
 144             throw newInternalError("calling lookup() reflectively is not supported: "+caller);
 145         }
 146         return new Lookup(caller);
 147     }
 148 
 149     /**
 150      * Returns a {@link Lookup lookup object} which is trusted minimally.
 151      * The lookup has the {@code UNCONDITIONAL} mode.
 152      * It can only be used to create method handles to public members of
 153      * public classes in packages that are exported unconditionally.
 154      * <p>
 155      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 156      * of this lookup object will be {@link java.lang.Object}.
 157      *
 158      * @apiNote The use of Object is conventional, and because the lookup modes are
 159      * limited, there is no special access provided to the internals of Object, its package
 160      * or its module.  This public lookup object or other lookup object with
 161      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 162      * is not used to determine the lookup context.
 163      *
 164      * <p style="font-size:smaller;">
 165      * <em>Discussion:</em>
 166      * The lookup class can be changed to any other class {@code C} using an expression of the form
 167      * {@link Lookup#in publicLookup().in(C.class)}.
 168      * A public lookup object is always subject to
 169      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 170      * Also, it cannot access
 171      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 172      * @return a lookup object which is trusted minimally
 173      */
 174     public static Lookup publicLookup() {
 175         return Lookup.PUBLIC_LOOKUP;
 176     }
 177 
 178     /**
 179      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 180      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 181      * The returned lookup object can provide access to classes in modules and packages,
 182      * and members of those classes, outside the normal rules of Java access control,
 183      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 184      * <p>
 185      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 186      * allowed to do deep reflection on module {@code M2} and package of the target class
 187      * if and only if all of the following conditions are {@code true}:
 188      * <ul>
 189      * <li>If there is a security manager, its {@code checkPermission} method is
 190      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 191      * that must return normally.
 192      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 193      * full privilege access}.  Specifically:
 194      *   <ul>
 195      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 196      *         (This is because otherwise there would be no way to ensure the original lookup
 197      *         creator was a member of any particular module, and so any subsequent checks
 198      *         for readability and qualified exports would become ineffective.)
 199      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 200      *         (This is because an application intending to share intra-module access
 201      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 202      *         deep reflection to its own module.)
 203      *   </ul>
 204      * <li>The target class must be a proper class, not a primitive or array class.
 205      * (Thus, {@code M2} is well-defined.)
 206      * <li>If the caller module {@code M1} differs from
 207      * the target module {@code M2} then both of the following must be true:
 208      *   <ul>
 209      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 210      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 211      *         containing the target class to at least {@code M1}.</li>
 212      *   </ul>
 213      * </ul>
 214      * <p>
 215      * If any of the above checks is violated, this method fails with an
 216      * exception.
 217      * <p>
 218      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 219      * returns a {@code Lookup} on {@code targetClass} with
 220      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 221      * with {@code null} previous lookup class.
 222      * <p>
 223      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 224      * returns a {@code Lookup} on {@code targetClass} that records
 225      * the lookup class of the caller as the new previous lookup class with
 226      * {@code PRIVATE} access but no {@code MODULE} access.
 227      * <p>
 228      * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
 229      *
 230      * @apiNote The {@code Lookup} object returned by this method is allowed to
 231      * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
 232      * of {@code targetClass}. Extreme caution should be taken when opening a package
 233      * to another module as such defined classes have the same full privilege
 234      * access as other members in {@code targetClass}'s module.
 235      *
 236      * @param targetClass the target class
 237      * @param caller the caller lookup object
 238      * @return a lookup object for the target class, with private access
 239      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 240      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 241      * @throws SecurityException if denied by the security manager
 242      * @throws IllegalAccessException if any of the other access checks specified above fails
 243      * @since 9
 244      * @see Lookup#dropLookupMode
 245      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 246      */
 247     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 248         if (caller.allowedModes == Lookup.TRUSTED) {
 249             return new Lookup(targetClass);
 250         }
 251 
 252         @SuppressWarnings("removal")
 253         SecurityManager sm = System.getSecurityManager();
 254         if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 255         if (targetClass.isPrimitive())
 256             throw new IllegalArgumentException(targetClass + " is a primitive class");
 257         if (targetClass.isArray())
 258             throw new IllegalArgumentException(targetClass + " is an array class");
 259         // Ensure that we can reason accurately about private and module access.
 260         int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
 261         if ((caller.lookupModes() & requireAccess) != requireAccess)
 262             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 263 
 264         // previous lookup class is never set if it has MODULE access
 265         assert caller.previousLookupClass() == null;
 266 
 267         Class<?> callerClass = caller.lookupClass();
 268         Module callerModule = callerClass.getModule();  // M1
 269         Module targetModule = targetClass.getModule();  // M2
 270         Class<?> newPreviousClass = null;
 271         int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
 272 
 273         if (targetModule != callerModule) {
 274             if (!callerModule.canRead(targetModule))
 275                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 276             if (targetModule.isNamed()) {
 277                 String pn = targetClass.getPackageName();
 278                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 279                 if (!targetModule.isOpen(pn, callerModule))
 280                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 281             }
 282 
 283             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 284             newPreviousClass = callerClass;
 285             newModes &= ~Lookup.MODULE;
 286         }
 287         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 288     }
 289 
 290     /**
 291      * Returns the <em>class data</em> associated with the lookup class
 292      * of the given {@code caller} lookup object, or {@code null}.
 293      *
 294      * <p> A hidden class with class data can be created by calling
 295      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 296      * Lookup::defineHiddenClassWithClassData}.
 297      * This method will cause the static class initializer of the lookup
 298      * class of the given {@code caller} lookup object be executed if
 299      * it has not been initialized.
 300      *
 301      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 302      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 303      * {@code null} is returned if this method is called on the lookup object
 304      * on these classes.
 305      *
 306      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 307      * must have {@linkplain Lookup#ORIGINAL original access}
 308      * in order to retrieve the class data.
 309      *
 310      * @apiNote
 311      * This method can be called as a bootstrap method for a dynamically computed
 312      * constant.  A framework can create a hidden class with class data, for
 313      * example that can be {@code Class} or {@code MethodHandle} object.
 314      * The class data is accessible only to the lookup object
 315      * created by the original caller but inaccessible to other members
 316      * in the same nest.  If a framework passes security sensitive objects
 317      * to a hidden class via class data, it is recommended to load the value
 318      * of class data as a dynamically computed constant instead of storing
 319      * the class data in private static field(s) which are accessible to
 320      * other nestmates.
 321      *
 322      * @param <T> the type to cast the class data object to
 323      * @param caller the lookup context describing the class performing the
 324      * operation (normally stacked by the JVM)
 325      * @param name must be {@link ConstantDescs#DEFAULT_NAME}
 326      *             ({@code "_"})
 327      * @param type the type of the class data
 328      * @return the value of the class data if present in the lookup class;
 329      * otherwise {@code null}
 330      * @throws IllegalArgumentException if name is not {@code "_"}
 331      * @throws IllegalAccessException if the lookup context does not have
 332      * {@linkplain Lookup#ORIGINAL original} access
 333      * @throws ClassCastException if the class data cannot be converted to
 334      * the given {@code type}
 335      * @throws NullPointerException if {@code caller} or {@code type} argument
 336      * is {@code null}
 337      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 338      * @see MethodHandles#classDataAt(Lookup, String, Class, int)
 339      * @since 16
 340      * @jvms 5.5 Initialization
 341      */
 342      public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 343          Objects.requireNonNull(caller);
 344          Objects.requireNonNull(type);
 345          if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
 346              throw new IllegalArgumentException("name must be \"_\": " + name);
 347          }
 348 
 349          if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL)  {
 350              throw new IllegalAccessException(caller + " does not have ORIGINAL access");
 351          }
 352 
 353          Object classdata = classData(caller.lookupClass());
 354          if (classdata == null) return null;
 355 
 356          try {
 357              return BootstrapMethodInvoker.widenAndCast(classdata, type);
 358          } catch (RuntimeException|Error e) {
 359              throw e; // let CCE and other runtime exceptions through
 360          } catch (Throwable e) {
 361              throw new InternalError(e);
 362          }
 363     }
 364 
 365     /*
 366      * Returns the class data set by the VM in the Class::classData field.
 367      *
 368      * This is also invoked by LambdaForms as it cannot use condy via
 369      * MethodHandles::classData due to bootstrapping issue.
 370      */
 371     static Object classData(Class<?> c) {
 372         UNSAFE.ensureClassInitialized(c);
 373         return SharedSecrets.getJavaLangAccess().classData(c);
 374     }
 375 
 376     /**
 377      * Returns the element at the specified index in the
 378      * {@linkplain #classData(Lookup, String, Class) class data},
 379      * if the class data associated with the lookup class
 380      * of the given {@code caller} lookup object is a {@code List}.
 381      * If the class data is not present in this lookup class, this method
 382      * returns {@code null}.
 383      *
 384      * <p> A hidden class with class data can be created by calling
 385      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 386      * Lookup::defineHiddenClassWithClassData}.
 387      * This method will cause the static class initializer of the lookup
 388      * class of the given {@code caller} lookup object be executed if
 389      * it has not been initialized.
 390      *
 391      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 392      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 393      * {@code null} is returned if this method is called on the lookup object
 394      * on these classes.
 395      *
 396      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 397      * must have {@linkplain Lookup#ORIGINAL original access}
 398      * in order to retrieve the class data.
 399      *
 400      * @apiNote
 401      * This method can be called as a bootstrap method for a dynamically computed
 402      * constant.  A framework can create a hidden class with class data, for
 403      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 404      * one object and use this method to load one element at a specific index.
 405      * The class data is accessible only to the lookup object
 406      * created by the original caller but inaccessible to other members
 407      * in the same nest.  If a framework passes security sensitive objects
 408      * to a hidden class via class data, it is recommended to load the value
 409      * of class data as a dynamically computed constant instead of storing
 410      * the class data in private static field(s) which are accessible to other
 411      * nestmates.
 412      *
 413      * @param <T> the type to cast the result object to
 414      * @param caller the lookup context describing the class performing the
 415      * operation (normally stacked by the JVM)
 416      * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
 417      *             ({@code "_"})
 418      * @param type the type of the element at the given index in the class data
 419      * @param index index of the element in the class data
 420      * @return the element at the given index in the class data
 421      * if the class data is present; otherwise {@code null}
 422      * @throws IllegalArgumentException if name is not {@code "_"}
 423      * @throws IllegalAccessException if the lookup context does not have
 424      * {@linkplain Lookup#ORIGINAL original} access
 425      * @throws ClassCastException if the class data cannot be converted to {@code List}
 426      * or the element at the specified index cannot be converted to the given type
 427      * @throws IndexOutOfBoundsException if the index is out of range
 428      * @throws NullPointerException if {@code caller} or {@code type} argument is
 429      * {@code null}; or if unboxing operation fails because
 430      * the element at the given index is {@code null}
 431      *
 432      * @since 16
 433      * @see #classData(Lookup, String, Class)
 434      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 435      */
 436     public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
 437             throws IllegalAccessException
 438     {
 439         @SuppressWarnings("unchecked")
 440         List<Object> classdata = (List<Object>)classData(caller, name, List.class);
 441         if (classdata == null) return null;
 442 
 443         try {
 444             Object element = classdata.get(index);
 445             return BootstrapMethodInvoker.widenAndCast(element, type);
 446         } catch (RuntimeException|Error e) {
 447             throw e; // let specified exceptions and other runtime exceptions/errors through
 448         } catch (Throwable e) {
 449             throw new InternalError(e);
 450         }
 451     }
 452 
 453     /**
 454      * Performs an unchecked "crack" of a
 455      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 456      * The result is as if the user had obtained a lookup object capable enough
 457      * to crack the target method handle, called
 458      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 459      * on the target to obtain its symbolic reference, and then called
 460      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 461      * to resolve the symbolic reference to a member.
 462      * <p>
 463      * If there is a security manager, its {@code checkPermission} method
 464      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 465      * @param <T> the desired type of the result, either {@link Member} or a subtype
 466      * @param target a direct method handle to crack into symbolic reference components
 467      * @param expected a class object representing the desired result type {@code T}
 468      * @return a reference to the method, constructor, or field object
 469      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 470      * @throws    NullPointerException if either argument is {@code null}
 471      * @throws    IllegalArgumentException if the target is not a direct method handle
 472      * @throws    ClassCastException if the member is not of the expected type
 473      * @since 1.8
 474      */
 475     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 476         @SuppressWarnings("removal")
 477         SecurityManager smgr = System.getSecurityManager();
 478         if (smgr != null)  smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 479         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 480         return lookup.revealDirect(target).reflectAs(expected, lookup);
 481     }
 482 
 483     /**
 484      * A <em>lookup object</em> is a factory for creating method handles,
 485      * when the creation requires access checking.
 486      * Method handles do not perform
 487      * access checks when they are called, but rather when they are created.
 488      * Therefore, method handle access
 489      * restrictions must be enforced when a method handle is created.
 490      * The caller class against which those restrictions are enforced
 491      * is known as the {@linkplain #lookupClass() lookup class}.
 492      * <p>
 493      * A lookup class which needs to create method handles will call
 494      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 495      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 496      * determined, and securely stored in the {@code Lookup} object.
 497      * The lookup class (or its delegates) may then use factory methods
 498      * on the {@code Lookup} object to create method handles for access-checked members.
 499      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 500      * even private ones.
 501      *
 502      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 503      * The factory methods on a {@code Lookup} object correspond to all major
 504      * use cases for methods, constructors, and fields.
 505      * Each method handle created by a factory method is the functional
 506      * equivalent of a particular <em>bytecode behavior</em>.
 507      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 508      * the Java Virtual Machine Specification.)
 509      * Here is a summary of the correspondence between these factory methods and
 510      * the behavior of the resulting method handles:
 511      * <table class="striped">
 512      * <caption style="display:none">lookup method behaviors</caption>
 513      * <thead>
 514      * <tr>
 515      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 516      *     <th scope="col">member</th>
 517      *     <th scope="col">bytecode behavior</th>
 518      * </tr>
 519      * </thead>
 520      * <tbody>
 521      * <tr>
 522      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 523      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 524      * </tr>
 525      * <tr>
 526      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 527      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 528      * </tr>
 529      * <tr>
 530      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 531      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 532      * </tr>
 533      * <tr>
 534      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 535      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 536      * </tr>
 537      * <tr>
 538      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 539      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 540      * </tr>
 541      * <tr>
 542      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 543      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 544      * </tr>
 545      * <tr>
 546      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 547      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 548      * </tr>
 549      * <tr>
 550      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 551      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 552      * </tr>
 553      * <tr>
 554      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 555      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 556      * </tr>
 557      * <tr>
 558      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 559      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 560      * </tr>
 561      * <tr>
 562      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 563      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 564      * </tr>
 565      * <tr>
 566      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 567      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 568      * </tr>
 569      * <tr>
 570      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 571      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 572      * </tr>
 573      * <tr>
 574      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 575      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 576      * </tr>
 577      * </tbody>
 578      * </table>
 579      *
 580      * Here, the type {@code C} is the class or interface being searched for a member,
 581      * documented as a parameter named {@code refc} in the lookup methods.
 582      * The method type {@code MT} is composed from the return type {@code T}
 583      * and the sequence of argument types {@code A*}.
 584      * The constructor also has a sequence of argument types {@code A*} and
 585      * is deemed to return the newly-created object of type {@code C}.
 586      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 587      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 588      * if it is present, it is always the leading argument to the method handle invocation.
 589      * (In the case of some {@code protected} members, {@code this} may be
 590      * restricted in type to the lookup class; see below.)
 591      * The name {@code arg} stands for all the other method handle arguments.
 592      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 593      * stands for a null reference if the accessed method or field is static,
 594      * and {@code this} otherwise.
 595      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 596      * for reflective objects corresponding to the given members declared in type {@code C}.
 597      * <p>
 598      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 599      * as if by {@code ldc CONSTANT_Class}.
 600      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 601      * <p>
 602      * In cases where the given member is of variable arity (i.e., a method or constructor)
 603      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 604      * In all other cases, the returned method handle will be of fixed arity.
 605      * <p style="font-size:smaller;">
 606      * <em>Discussion:</em>
 607      * The equivalence between looked-up method handles and underlying
 608      * class members and bytecode behaviors
 609      * can break down in a few ways:
 610      * <ul style="font-size:smaller;">
 611      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 612      * the lookup can still succeed, even when there is no equivalent
 613      * Java expression or bytecoded constant.
 614      * <li>Likewise, if {@code T} or {@code MT}
 615      * is not symbolically accessible from the lookup class's loader,
 616      * the lookup can still succeed.
 617      * For example, lookups for {@code MethodHandle.invokeExact} and
 618      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 619      * <li>If there is a security manager installed, it can forbid the lookup
 620      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 621      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 622      * constant is not subject to security manager checks.
 623      * <li>If the looked-up method has a
 624      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 625      * the method handle creation may fail with an
 626      * {@code IllegalArgumentException}, due to the method handle type having
 627      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 628      * </ul>
 629      *
 630      * <h2><a id="access"></a>Access checking</h2>
 631      * Access checks are applied in the factory methods of {@code Lookup},
 632      * when a method handle is created.
 633      * This is a key difference from the Core Reflection API, since
 634      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 635      * performs access checking against every caller, on every call.
 636      * <p>
 637      * All access checks start from a {@code Lookup} object, which
 638      * compares its recorded lookup class against all requests to
 639      * create method handles.
 640      * A single {@code Lookup} object can be used to create any number
 641      * of access-checked method handles, all checked against a single
 642      * lookup class.
 643      * <p>
 644      * A {@code Lookup} object can be shared with other trusted code,
 645      * such as a metaobject protocol.
 646      * A shared {@code Lookup} object delegates the capability
 647      * to create method handles on private members of the lookup class.
 648      * Even if privileged code uses the {@code Lookup} object,
 649      * the access checking is confined to the privileges of the
 650      * original lookup class.
 651      * <p>
 652      * A lookup can fail, because
 653      * the containing class is not accessible to the lookup class, or
 654      * because the desired class member is missing, or because the
 655      * desired class member is not accessible to the lookup class, or
 656      * because the lookup object is not trusted enough to access the member.
 657      * In the case of a field setter function on a {@code final} field,
 658      * finality enforcement is treated as a kind of access control,
 659      * and the lookup will fail, except in special cases of
 660      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 661      * In any of these cases, a {@code ReflectiveOperationException} will be
 662      * thrown from the attempted lookup.  The exact class will be one of
 663      * the following:
 664      * <ul>
 665      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 666      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 667      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 668      * </ul>
 669      * <p>
 670      * In general, the conditions under which a method handle may be
 671      * looked up for a method {@code M} are no more restrictive than the conditions
 672      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 673      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 674      * a method handle lookup will generally raise a corresponding
 675      * checked exception, such as {@code NoSuchMethodException}.
 676      * And the effect of invoking the method handle resulting from the lookup
 677      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 678      * to executing the compiled, verified, and resolved call to {@code M}.
 679      * The same point is true of fields and constructors.
 680      * <p style="font-size:smaller;">
 681      * <em>Discussion:</em>
 682      * Access checks only apply to named and reflected methods,
 683      * constructors, and fields.
 684      * Other method handle creation methods, such as
 685      * {@link MethodHandle#asType MethodHandle.asType},
 686      * do not require any access checks, and are used
 687      * independently of any {@code Lookup} object.
 688      * <p>
 689      * If the desired member is {@code protected}, the usual JVM rules apply,
 690      * including the requirement that the lookup class must either be in the
 691      * same package as the desired member, or must inherit that member.
 692      * (See the Java Virtual Machine Specification, sections {@jvms
 693      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 694      * In addition, if the desired member is a non-static field or method
 695      * in a different package, the resulting method handle may only be applied
 696      * to objects of the lookup class or one of its subclasses.
 697      * This requirement is enforced by narrowing the type of the leading
 698      * {@code this} parameter from {@code C}
 699      * (which will necessarily be a superclass of the lookup class)
 700      * to the lookup class itself.
 701      * <p>
 702      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 703      * that the receiver argument must match both the resolved method <em>and</em>
 704      * the current class.  Again, this requirement is enforced by narrowing the
 705      * type of the leading parameter to the resulting method handle.
 706      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 707      * <p>
 708      * The JVM represents constructors and static initializer blocks as internal methods
 709      * with special names ({@value ConstantDescs#INIT_NAME}, and {@value
 710      * ConstantDescs#CLASS_INIT_NAME}).
 711      * The internal syntax of invocation instructions allows them to refer to such internal
 712      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 713      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 714      * <p>
 715      * If the relationship between nested types is expressed directly through the
 716      * {@code NestHost} and {@code NestMembers} attributes
 717      * (see the Java Virtual Machine Specification, sections {@jvms
 718      * 4.7.28} and {@jvms 4.7.29}),
 719      * then the associated {@code Lookup} object provides direct access to
 720      * the lookup class and all of its nestmates
 721      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 722      * Otherwise, access between nested classes is obtained by the Java compiler creating
 723      * a wrapper method to access a private method of another class in the same nest.
 724      * For example, a nested class {@code C.D}
 725      * can access private members within other related classes such as
 726      * {@code C}, {@code C.D.E}, or {@code C.B},
 727      * but the Java compiler may need to generate wrapper methods in
 728      * those related classes.  In such cases, a {@code Lookup} object on
 729      * {@code C.E} would be unable to access those private members.
 730      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 731      * which can transform a lookup on {@code C.E} into one on any of those other
 732      * classes, without special elevation of privilege.
 733      * <p>
 734      * The accesses permitted to a given lookup object may be limited,
 735      * according to its set of {@link #lookupModes lookupModes},
 736      * to a subset of members normally accessible to the lookup class.
 737      * For example, the {@link MethodHandles#publicLookup publicLookup}
 738      * method produces a lookup object which is only allowed to access
 739      * public members in public classes of exported packages.
 740      * The caller sensitive method {@link MethodHandles#lookup lookup}
 741      * produces a lookup object with full capabilities relative to
 742      * its caller class, to emulate all supported bytecode behaviors.
 743      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 744      * with fewer access modes than the original lookup object.
 745      *
 746      * <p style="font-size:smaller;">
 747      * <a id="privacc"></a>
 748      * <em>Discussion of private and module access:</em>
 749      * We say that a lookup has <em>private access</em>
 750      * if its {@linkplain #lookupModes lookup modes}
 751      * include the possibility of accessing {@code private} members
 752      * (which includes the private members of nestmates).
 753      * As documented in the relevant methods elsewhere,
 754      * only lookups with private access possess the following capabilities:
 755      * <ul style="font-size:smaller;">
 756      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 757      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 758      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 759      *     for classes accessible to the lookup class
 760      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 761      *     within the same package member
 762      * </ul>
 763      * <p style="font-size:smaller;">
 764      * Similarly, a lookup with module access ensures that the original lookup creator was
 765      * a member in the same module as the lookup class.
 766      * <p style="font-size:smaller;">
 767      * Private and module access are independently determined modes; a lookup may have
 768      * either or both or neither.  A lookup which possesses both access modes is said to
 769      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
 770      * <p style="font-size:smaller;">
 771      * A lookup with <em>original access</em> ensures that this lookup is created by
 772      * the original lookup class and the bootstrap method invoked by the VM.
 773      * Such a lookup with original access also has private and module access
 774      * which has the following additional capability:
 775      * <ul style="font-size:smaller;">
 776      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 777      *     such as {@code Class.forName}
 778      * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
 779      * class data} associated with the lookup class</li>
 780      * </ul>
 781      * <p style="font-size:smaller;">
 782      * Each of these permissions is a consequence of the fact that a lookup object
 783      * with private access can be securely traced back to an originating class,
 784      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 785      * can be reliably determined and emulated by method handles.
 786      *
 787      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 788      * When a lookup class in one module {@code M1} accesses a class in another module
 789      * {@code M2}, extra access checking is performed beyond the access mode bits.
 790      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 791      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 792      * and when the type is in a package of {@code M2} that is exported to
 793      * at least {@code M1}.
 794      * <p>
 795      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 796      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 797      * MethodHandles.privateLookupIn} methods.
 798      * Teleporting across modules will always record the original lookup class as
 799      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 800      * and drops {@link Lookup#MODULE MODULE} access.
 801      * If the target class is in the same module as the lookup class {@code C},
 802      * then the target class becomes the new lookup class
 803      * and there is no change to the previous lookup class.
 804      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 805      * {@code C} becomes the new previous lookup class
 806      * and the target class becomes the new lookup class.
 807      * In that case, if there was already a previous lookup class in {@code M0},
 808      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 809      * drops all privileges.
 810      * For example,
 811      * {@snippet lang="java" :
 812      * Lookup lookup = MethodHandles.lookup();   // in class C
 813      * Lookup lookup2 = lookup.in(D.class);
 814      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 815      * }
 816      * <p>
 817      * The {@link #lookup()} factory method produces a {@code Lookup} object
 818      * with {@code null} previous lookup class.
 819      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 820      * to class {@code D} without elevation of privileges.
 821      * If {@code C} and {@code D} are in the same module,
 822      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 823      * same previous lookup class as the original {@code lookup}, or
 824      * {@code null} if not present.
 825      * <p>
 826      * When a {@code Lookup} teleports from a class
 827      * in one nest to another nest, {@code PRIVATE} access is dropped.
 828      * When a {@code Lookup} teleports from a class in one package to
 829      * another package, {@code PACKAGE} access is dropped.
 830      * When a {@code Lookup} teleports from a class in one module to another module,
 831      * {@code MODULE} access is dropped.
 832      * Teleporting across modules drops the ability to access non-exported classes
 833      * in both the module of the new lookup class and the module of the old lookup class
 834      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 835      * A {@code Lookup} can teleport back and forth to a class in the module of
 836      * the lookup class and the module of the previous class lookup.
 837      * Teleporting across modules can only decrease access but cannot increase it.
 838      * Teleporting to some third module drops all accesses.
 839      * <p>
 840      * In the above example, if {@code C} and {@code D} are in different modules,
 841      * {@code lookup2} records {@code D} as its lookup class and
 842      * {@code C} as its previous lookup class and {@code lookup2} has only
 843      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 844      * {@code C}'s module and {@code D}'s module.
 845      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 846      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 847      * class {@code D} is recorded as its previous lookup class.
 848      * <p>
 849      * Teleporting across modules restricts access to the public types that
 850      * both the lookup class and the previous lookup class can equally access
 851      * (see below).
 852      * <p>
 853      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 854      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 855      * and produce a new {@code Lookup} with <a href="#privacc">private access</a>
 856      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 857      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 858      * to call {@code privateLookupIn}.
 859      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 860      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 861      * produces a new {@code Lookup} on {@code T} with full capabilities.
 862      * A {@code lookup} on {@code C} is also allowed
 863      * to do deep reflection on {@code T} in another module {@code M2} if
 864      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 865      * the package containing {@code T} to at least {@code M1}.
 866      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 867      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 868      * The resulting {@code Lookup} can be used to do member lookup or teleport
 869      * to another lookup class by calling {@link #in Lookup::in}.  But
 870      * it cannot be used to obtain another private {@code Lookup} by calling
 871      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 872      * because it has no {@code MODULE} access.
 873      * <p>
 874      * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to
 875      * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
 876      * of {@code T}. Extreme caution should be taken when opening a package
 877      * to another module as such defined classes have the same full privilege
 878      * access as other members in {@code M2}.
 879      *
 880      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 881      *
 882      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 883      * allows cross-module access. The access checking is performed with respect
 884      * to both the lookup class and the previous lookup class if present.
 885      * <p>
 886      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 887      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 888      * exported unconditionally}.
 889      * <p>
 890      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 891      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 892      * that are readable to {@code M1} and the type is in a package that is exported
 893      * at least to {@code M1}.
 894      * <p>
 895      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 896      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 897      * the intersection of all public types that are accessible to {@code M1}
 898      * with all public types that are accessible to {@code M0}. {@code M0}
 899      * reads {@code M1} and hence the set of accessible types includes:
 900      *
 901      * <ul>
 902      * <li>unconditional-exported packages from {@code M1}</li>
 903      * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li>
 904      * <li>
 905      *     unconditional-exported packages from a third module {@code M2}if both {@code M0}
 906      *     and {@code M1} read {@code M2}
 907      * </li>
 908      * <li>qualified-exported packages from {@code M1} to {@code M0}</li>
 909      * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li>
 910      * <li>
 911      *     qualified-exported packages from a third module {@code M2} to both {@code M0} and
 912      *     {@code M1} if both {@code M0} and {@code M1} read {@code M2}
 913      * </li>
 914      * </ul>
 915      *
 916      * <h2><a id="access-modes"></a>Access modes</h2>
 917      *
 918      * The table below shows the access modes of a {@code Lookup} produced by
 919      * any of the following factory or transformation methods:
 920      * <ul>
 921      * <li>{@link #lookup() MethodHandles::lookup}</li>
 922      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 923      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 924      * <li>{@link Lookup#in Lookup::in}</li>
 925      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 926      * </ul>
 927      *
 928      * <table class="striped">
 929      * <caption style="display:none">
 930      * Access mode summary
 931      * </caption>
 932      * <thead>
 933      * <tr>
 934      * <th scope="col">Lookup object</th>
 935      * <th style="text-align:center">original</th>
 936      * <th style="text-align:center">protected</th>
 937      * <th style="text-align:center">private</th>
 938      * <th style="text-align:center">package</th>
 939      * <th style="text-align:center">module</th>
 940      * <th style="text-align:center">public</th>
 941      * </tr>
 942      * </thead>
 943      * <tbody>
 944      * <tr>
 945      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 946      * <td style="text-align:center">ORI</td>
 947      * <td style="text-align:center">PRO</td>
 948      * <td style="text-align:center">PRI</td>
 949      * <td style="text-align:center">PAC</td>
 950      * <td style="text-align:center">MOD</td>
 951      * <td style="text-align:center">1R</td>
 952      * </tr>
 953      * <tr>
 954      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 955      * <td></td>
 956      * <td></td>
 957      * <td></td>
 958      * <td style="text-align:center">PAC</td>
 959      * <td style="text-align:center">MOD</td>
 960      * <td style="text-align:center">1R</td>
 961      * </tr>
 962      * <tr>
 963      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 964      * <td></td>
 965      * <td></td>
 966      * <td></td>
 967      * <td></td>
 968      * <td style="text-align:center">MOD</td>
 969      * <td style="text-align:center">1R</td>
 970      * </tr>
 971      * <tr>
 972      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 973      * <td></td>
 974      * <td></td>
 975      * <td></td>
 976      * <td></td>
 977      * <td></td>
 978      * <td style="text-align:center">2R</td>
 979      * </tr>
 980      * <tr>
 981      * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th>
 982      * <td></td>
 983      * <td></td>
 984      * <td></td>
 985      * <td></td>
 986      * <td></td>
 987      * <td style="text-align:center">2R</td>
 988      * </tr>
 989      * <tr>
 990      * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th>
 991      * <td></td>
 992      * <td style="text-align:center">PRO</td>
 993      * <td style="text-align:center">PRI</td>
 994      * <td style="text-align:center">PAC</td>
 995      * <td style="text-align:center">MOD</td>
 996      * <td style="text-align:center">1R</td>
 997      * </tr>
 998      * <tr>
 999      * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th>
1000      * <td></td>
1001      * <td style="text-align:center">PRO</td>
1002      * <td style="text-align:center">PRI</td>
1003      * <td style="text-align:center">PAC</td>
1004      * <td style="text-align:center">MOD</td>
1005      * <td style="text-align:center">1R</td>
1006      * </tr>
1007      * <tr>
1008      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th>
1009      * <td></td>
1010      * <td></td>
1011      * <td></td>
1012      * <td style="text-align:center">PAC</td>
1013      * <td style="text-align:center">MOD</td>
1014      * <td style="text-align:center">1R</td>
1015      * </tr>
1016      * <tr>
1017      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th>
1018      * <td></td>
1019      * <td></td>
1020      * <td></td>
1021      * <td></td>
1022      * <td style="text-align:center">MOD</td>
1023      * <td style="text-align:center">1R</td>
1024      * </tr>
1025      * <tr>
1026      * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th>
1027      * <td></td>
1028      * <td></td>
1029      * <td></td>
1030      * <td></td>
1031      * <td></td>
1032      * <td style="text-align:center">2R</td>
1033      * </tr>
1034      * <tr>
1035      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th>
1036      * <td></td>
1037      * <td></td>
1038      * <td style="text-align:center">PRI</td>
1039      * <td style="text-align:center">PAC</td>
1040      * <td style="text-align:center">MOD</td>
1041      * <td style="text-align:center">1R</td>
1042      * </tr>
1043      * <tr>
1044      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th>
1045      * <td></td>
1046      * <td></td>
1047      * <td></td>
1048      * <td style="text-align:center">PAC</td>
1049      * <td style="text-align:center">MOD</td>
1050      * <td style="text-align:center">1R</td>
1051      * </tr>
1052      * <tr>
1053      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th>
1054      * <td></td>
1055      * <td></td>
1056      * <td></td>
1057      * <td></td>
1058      * <td style="text-align:center">MOD</td>
1059      * <td style="text-align:center">1R</td>
1060      * </tr>
1061      * <tr>
1062      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th>
1063      * <td></td>
1064      * <td></td>
1065      * <td></td>
1066      * <td></td>
1067      * <td></td>
1068      * <td style="text-align:center">1R</td>
1069      * </tr>
1070      * <tr>
1071      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th>
1072      * <td></td>
1073      * <td></td>
1074      * <td></td>
1075      * <td></td>
1076      * <td></td>
1077      * <td style="text-align:center">none</td>
1078      * <tr>
1079      * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th>
1080      * <td></td>
1081      * <td style="text-align:center">PRO</td>
1082      * <td style="text-align:center">PRI</td>
1083      * <td style="text-align:center">PAC</td>
1084      * <td></td>
1085      * <td style="text-align:center">2R</td>
1086      * </tr>
1087      * <tr>
1088      * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th>
1089      * <td></td>
1090      * <td style="text-align:center">PRO</td>
1091      * <td style="text-align:center">PRI</td>
1092      * <td style="text-align:center">PAC</td>
1093      * <td></td>
1094      * <td style="text-align:center">2R</td>
1095      * </tr>
1096      * <tr>
1097      * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th>
1098      * <td></td>
1099      * <td></td>
1100      * <td></td>
1101      * <td></td>
1102      * <td></td>
1103      * <td style="text-align:center">IAE</td>
1104      * </tr>
1105      * <tr>
1106      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th>
1107      * <td></td>
1108      * <td></td>
1109      * <td></td>
1110      * <td style="text-align:center">PAC</td>
1111      * <td></td>
1112      * <td style="text-align:center">2R</td>
1113      * </tr>
1114      * <tr>
1115      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th>
1116      * <td></td>
1117      * <td></td>
1118      * <td></td>
1119      * <td></td>
1120      * <td></td>
1121      * <td style="text-align:center">2R</td>
1122      * </tr>
1123      * <tr>
1124      * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th>
1125      * <td></td>
1126      * <td></td>
1127      * <td></td>
1128      * <td></td>
1129      * <td></td>
1130      * <td style="text-align:center">2R</td>
1131      * </tr>
1132      * <tr>
1133      * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th>
1134      * <td></td>
1135      * <td></td>
1136      * <td></td>
1137      * <td></td>
1138      * <td></td>
1139      * <td style="text-align:center">none</td>
1140      * </tr>
1141      * <tr>
1142      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th>
1143      * <td></td>
1144      * <td></td>
1145      * <td style="text-align:center">PRI</td>
1146      * <td style="text-align:center">PAC</td>
1147      * <td></td>
1148      * <td style="text-align:center">2R</td>
1149      * </tr>
1150      * <tr>
1151      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th>
1152      * <td></td>
1153      * <td></td>
1154      * <td></td>
1155      * <td style="text-align:center">PAC</td>
1156      * <td></td>
1157      * <td style="text-align:center">2R</td>
1158      * </tr>
1159      * <tr>
1160      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th>
1161      * <td></td>
1162      * <td></td>
1163      * <td></td>
1164      * <td></td>
1165      * <td></td>
1166      * <td style="text-align:center">2R</td>
1167      * </tr>
1168      * <tr>
1169      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th>
1170      * <td></td>
1171      * <td></td>
1172      * <td></td>
1173      * <td></td>
1174      * <td></td>
1175      * <td style="text-align:center">2R</td>
1176      * </tr>
1177      * <tr>
1178      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th>
1179      * <td></td>
1180      * <td></td>
1181      * <td></td>
1182      * <td></td>
1183      * <td></td>
1184      * <td style="text-align:center">none</td>
1185      * </tr>
1186      * <tr>
1187      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th>
1188      * <td></td>
1189      * <td></td>
1190      * <td style="text-align:center">PRI</td>
1191      * <td style="text-align:center">PAC</td>
1192      * <td style="text-align:center">MOD</td>
1193      * <td style="text-align:center">1R</td>
1194      * </tr>
1195      * <tr>
1196      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th>
1197      * <td></td>
1198      * <td></td>
1199      * <td></td>
1200      * <td style="text-align:center">PAC</td>
1201      * <td style="text-align:center">MOD</td>
1202      * <td style="text-align:center">1R</td>
1203      * </tr>
1204      * <tr>
1205      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th>
1206      * <td></td>
1207      * <td></td>
1208      * <td></td>
1209      * <td></td>
1210      * <td style="text-align:center">MOD</td>
1211      * <td style="text-align:center">1R</td>
1212      * </tr>
1213      * <tr>
1214      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th>
1215      * <td></td>
1216      * <td></td>
1217      * <td></td>
1218      * <td></td>
1219      * <td></td>
1220      * <td style="text-align:center">1R</td>
1221      * </tr>
1222      * <tr>
1223      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th>
1224      * <td></td>
1225      * <td></td>
1226      * <td></td>
1227      * <td></td>
1228      * <td></td>
1229      * <td style="text-align:center">none</td>
1230      * </tr>
1231      * <tr>
1232      * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th>
1233      * <td></td>
1234      * <td></td>
1235      * <td></td>
1236      * <td></td>
1237      * <td></td>
1238      * <td style="text-align:center">U</td>
1239      * </tr>
1240      * <tr>
1241      * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th>
1242      * <td></td>
1243      * <td></td>
1244      * <td></td>
1245      * <td></td>
1246      * <td></td>
1247      * <td style="text-align:center">U</td>
1248      * </tr>
1249      * <tr>
1250      * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th>
1251      * <td></td>
1252      * <td></td>
1253      * <td></td>
1254      * <td></td>
1255      * <td></td>
1256      * <td style="text-align:center">U</td>
1257      * </tr>
1258      * <tr>
1259      * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th>
1260      * <td></td>
1261      * <td></td>
1262      * <td></td>
1263      * <td></td>
1264      * <td></td>
1265      * <td style="text-align:center">none</td>
1266      * </tr>
1267      * <tr>
1268      * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th>
1269      * <td></td>
1270      * <td></td>
1271      * <td></td>
1272      * <td></td>
1273      * <td></td>
1274      * <td style="text-align:center">IAE</td>
1275      * </tr>
1276      * <tr>
1277      * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th>
1278      * <td></td>
1279      * <td></td>
1280      * <td></td>
1281      * <td></td>
1282      * <td></td>
1283      * <td style="text-align:center">none</td>
1284      * </tr>
1285      * </tbody>
1286      * </table>
1287      *
1288      * <p>
1289      * Notes:
1290      * <ul>
1291      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1292      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1293      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1294      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1295      * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1296      *     {@code PRO} indicates {@link #PROTECTED} bit set,
1297      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1298      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1299      *     {@code MOD} indicates {@link #MODULE} bit set,
1300      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1301      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1302      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1303      * <li>Public access comes in three kinds:
1304      * <ul>
1305      * <li>unconditional ({@code U}): the lookup assumes readability.
1306      *     The lookup has {@code null} previous lookup class.
1307      * <li>one-module-reads ({@code 1R}): the module access checking is
1308      *     performed with respect to the lookup class.  The lookup has {@code null}
1309      *     previous lookup class.
1310      * <li>two-module-reads ({@code 2R}): the module access checking is
1311      *     performed with respect to the lookup class and the previous lookup class.
1312      *     The lookup has a non-null previous lookup class which is in a
1313      *     different module from the current lookup class.
1314      * </ul>
1315      * <li>Any attempt to reach a third module loses all access.</li>
1316      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1317      * all access modes are dropped.</li>
1318      * </ul>
1319      *
1320      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1321      * Although bytecode instructions can only refer to classes in
1322      * a related class loader, this API can search for methods in any
1323      * class, as long as a reference to its {@code Class} object is
1324      * available.  Such cross-loader references are also possible with the
1325      * Core Reflection API, and are impossible to bytecode instructions
1326      * such as {@code invokestatic} or {@code getfield}.
1327      * There is a {@linkplain java.lang.SecurityManager security manager API}
1328      * to allow applications to check such cross-loader references.
1329      * These checks apply to both the {@code MethodHandles.Lookup} API
1330      * and the Core Reflection API
1331      * (as found on {@link java.lang.Class Class}).
1332      * <p>
1333      * If a security manager is present, member and class lookups are subject to
1334      * additional checks.
1335      * From one to three calls are made to the security manager.
1336      * Any of these calls can refuse access by throwing a
1337      * {@link java.lang.SecurityException SecurityException}.
1338      * Define {@code smgr} as the security manager,
1339      * {@code lookc} as the lookup class of the current lookup object,
1340      * {@code refc} as the containing class in which the member
1341      * is being sought, and {@code defc} as the class in which the
1342      * member is actually defined.
1343      * (If a class or other type is being accessed,
1344      * the {@code refc} and {@code defc} values are the class itself.)
1345      * The value {@code lookc} is defined as <em>not present</em>
1346      * if the current lookup object does not have
1347      * {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1348      * The calls are made according to the following rules:
1349      * <ul>
1350      * <li><b>Step 1:</b>
1351      *     If {@code lookc} is not present, or if its class loader is not
1352      *     the same as or an ancestor of the class loader of {@code refc},
1353      *     then {@link SecurityManager#checkPackageAccess
1354      *     smgr.checkPackageAccess(refcPkg)} is called,
1355      *     where {@code refcPkg} is the package of {@code refc}.
1356      * <li><b>Step 2a:</b>
1357      *     If the retrieved member is not public and
1358      *     {@code lookc} is not present, then
1359      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1360      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
1361      * <li><b>Step 2b:</b>
1362      *     If the retrieved class has a {@code null} class loader,
1363      *     and {@code lookc} is not present, then
1364      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1365      *     with {@code RuntimePermission("getClassLoader")} is called.
1366      * <li><b>Step 3:</b>
1367      *     If the retrieved member is not public,
1368      *     and if {@code lookc} is not present,
1369      *     and if {@code defc} and {@code refc} are different,
1370      *     then {@link SecurityManager#checkPackageAccess
1371      *     smgr.checkPackageAccess(defcPkg)} is called,
1372      *     where {@code defcPkg} is the package of {@code defc}.
1373      * </ul>
1374      * Security checks are performed after other access checks have passed.
1375      * Therefore, the above rules presuppose a member or class that is public,
1376      * or else that is being accessed from a lookup class that has
1377      * rights to access the member or class.
1378      * <p>
1379      * If a security manager is present and the current lookup object does not have
1380      * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then
1381      * {@link #defineClass(byte[]) defineClass},
1382      * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass},
1383      * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...)
1384      * defineHiddenClassWithClassData}
1385      * calls {@link SecurityManager#checkPermission smgr.checkPermission}
1386      * with {@code RuntimePermission("defineClass")}.
1387      *
1388      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1389      * A small number of Java methods have a special property called caller sensitivity.
1390      * A <em>caller-sensitive</em> method can behave differently depending on the
1391      * identity of its immediate caller.
1392      * <p>
1393      * If a method handle for a caller-sensitive method is requested,
1394      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1395      * but they take account of the lookup class in a special way.
1396      * The resulting method handle behaves as if it were called
1397      * from an instruction contained in the lookup class,
1398      * so that the caller-sensitive method detects the lookup class.
1399      * (By contrast, the invoker of the method handle is disregarded.)
1400      * Thus, in the case of caller-sensitive methods,
1401      * different lookup classes may give rise to
1402      * differently behaving method handles.
1403      * <p>
1404      * In cases where the lookup object is
1405      * {@link MethodHandles#publicLookup() publicLookup()},
1406      * or some other lookup object without the
1407      * {@linkplain #ORIGINAL original access},
1408      * the lookup class is disregarded.
1409      * In such cases, no caller-sensitive method handle can be created,
1410      * access is forbidden, and the lookup fails with an
1411      * {@code IllegalAccessException}.
1412      * <p style="font-size:smaller;">
1413      * <em>Discussion:</em>
1414      * For example, the caller-sensitive method
1415      * {@link java.lang.Class#forName(String) Class.forName(x)}
1416      * can return varying classes or throw varying exceptions,
1417      * depending on the class loader of the class that calls it.
1418      * A public lookup of {@code Class.forName} will fail, because
1419      * there is no reasonable way to determine its bytecode behavior.
1420      * <p style="font-size:smaller;">
1421      * If an application caches method handles for broad sharing,
1422      * it should use {@code publicLookup()} to create them.
1423      * If there is a lookup of {@code Class.forName}, it will fail,
1424      * and the application must take appropriate action in that case.
1425      * It may be that a later lookup, perhaps during the invocation of a
1426      * bootstrap method, can incorporate the specific identity
1427      * of the caller, making the method accessible.
1428      * <p style="font-size:smaller;">
1429      * The function {@code MethodHandles.lookup} is caller sensitive
1430      * so that there can be a secure foundation for lookups.
1431      * Nearly all other methods in the JSR 292 API rely on lookup
1432      * objects to check access requests.
1433      */
1434     public static final
1435     class Lookup {
1436         /** The class on behalf of whom the lookup is being performed. */
1437         private final Class<?> lookupClass;
1438 
1439         /** previous lookup class */
1440         private final Class<?> prevLookupClass;
1441 
1442         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1443         private final int allowedModes;
1444 
1445         static {
1446             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1447         }
1448 
1449         /** A single-bit mask representing {@code public} access,
1450          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1451          *  The value, {@code 0x01}, happens to be the same as the value of the
1452          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1453          *  <p>
1454          *  A {@code Lookup} with this lookup mode performs cross-module access check
1455          *  with respect to the {@linkplain #lookupClass() lookup class} and
1456          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1457          */
1458         public static final int PUBLIC = Modifier.PUBLIC;
1459 
1460         /** A single-bit mask representing {@code private} access,
1461          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1462          *  The value, {@code 0x02}, happens to be the same as the value of the
1463          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1464          */
1465         public static final int PRIVATE = Modifier.PRIVATE;
1466 
1467         /** A single-bit mask representing {@code protected} access,
1468          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1469          *  The value, {@code 0x04}, happens to be the same as the value of the
1470          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1471          */
1472         public static final int PROTECTED = Modifier.PROTECTED;
1473 
1474         /** A single-bit mask representing {@code package} access (default access),
1475          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1476          *  The value is {@code 0x08}, which does not correspond meaningfully to
1477          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1478          */
1479         public static final int PACKAGE = Modifier.STATIC;
1480 
1481         /** A single-bit mask representing {@code module} access,
1482          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1483          *  The value is {@code 0x10}, which does not correspond meaningfully to
1484          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1485          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1486          *  with this lookup mode can access all public types in the module of the
1487          *  lookup class and public types in packages exported by other modules
1488          *  to the module of the lookup class.
1489          *  <p>
1490          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1491          *  previous lookup class} is always {@code null}.
1492          *
1493          *  @since 9
1494          */
1495         public static final int MODULE = PACKAGE << 1;
1496 
1497         /** A single-bit mask representing {@code unconditional} access
1498          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1499          *  The value is {@code 0x20}, which does not correspond meaningfully to
1500          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1501          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1502          *  java.lang.Module#canRead(java.lang.Module) readability}.
1503          *  This lookup mode can access all public members of public types
1504          *  of all modules when the type is in a package that is {@link
1505          *  java.lang.Module#isExported(String) exported unconditionally}.
1506          *
1507          *  <p>
1508          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1509          *  previous lookup class} is always {@code null}.
1510          *
1511          *  @since 9
1512          *  @see #publicLookup()
1513          */
1514         public static final int UNCONDITIONAL = PACKAGE << 2;
1515 
1516         /** A single-bit mask representing {@code original} access
1517          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1518          *  The value is {@code 0x40}, which does not correspond meaningfully to
1519          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1520          *
1521          *  <p>
1522          *  If this lookup mode is set, the {@code Lookup} object must be
1523          *  created by the original lookup class by calling
1524          *  {@link MethodHandles#lookup()} method or by a bootstrap method
1525          *  invoked by the VM.  The {@code Lookup} object with this lookup
1526          *  mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1527          *
1528          *  @since 16
1529          */
1530         public static final int ORIGINAL = PACKAGE << 3;
1531 
1532         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1533         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);   // with original access
1534         private static final int TRUSTED   = -1;
1535 
1536         /*
1537          * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1538          * Adjust 0 => PACKAGE
1539          */
1540         private static int fixmods(int mods) {
1541             mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1542             if (Modifier.isPublic(mods))
1543                 mods |= UNCONDITIONAL;
1544             return (mods != 0) ? mods : PACKAGE;
1545         }
1546 
1547         /** Tells which class is performing the lookup.  It is this class against
1548          *  which checks are performed for visibility and access permissions.
1549          *  <p>
1550          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1551          *  access checks are performed against both the lookup class and the previous lookup class.
1552          *  <p>
1553          *  The class implies a maximum level of access permission,
1554          *  but the permissions may be additionally limited by the bitmask
1555          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1556          *  can be accessed.
1557          *  @return the lookup class, on behalf of which this lookup object finds members
1558          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1559          */
1560         public Class<?> lookupClass() {
1561             return lookupClass;
1562         }
1563 
1564         /** Reports a lookup class in another module that this lookup object
1565          * was previously teleported from, or {@code null}.
1566          * <p>
1567          * A {@code Lookup} object produced by the factory methods, such as the
1568          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1569          * has {@code null} previous lookup class.
1570          * A {@code Lookup} object has a non-null previous lookup class
1571          * when this lookup was teleported from an old lookup class
1572          * in one module to a new lookup class in another module.
1573          *
1574          * @return the lookup class in another module that this lookup object was
1575          *         previously teleported from, or {@code null}
1576          * @since 14
1577          * @see #in(Class)
1578          * @see MethodHandles#privateLookupIn(Class, Lookup)
1579          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1580          */
1581         public Class<?> previousLookupClass() {
1582             return prevLookupClass;
1583         }
1584 
1585         // This is just for calling out to MethodHandleImpl.
1586         private Class<?> lookupClassOrNull() {
1587             return (allowedModes == TRUSTED) ? null : lookupClass;
1588         }
1589 
1590         /** Tells which access-protection classes of members this lookup object can produce.
1591          *  The result is a bit-mask of the bits
1592          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1593          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1594          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1595          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1596          *  {@linkplain #MODULE MODULE (0x10)},
1597          *  {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1598          *  and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1599          *  <p>
1600          *  A freshly-created lookup object
1601          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1602          *  all possible bits set, except {@code UNCONDITIONAL}.
1603          *  A lookup object on a new lookup class
1604          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1605          *  may have some mode bits set to zero.
1606          *  Mode bits can also be
1607          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1608          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1609          *  The purpose of this is to restrict access via the new lookup object,
1610          *  so that it can access only names which can be reached by the original
1611          *  lookup object, and also by the new lookup class.
1612          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1613          *  @see #in
1614          *  @see #dropLookupMode
1615          */
1616         public int lookupModes() {
1617             return allowedModes & ALL_MODES;
1618         }
1619 
1620         /** Embody the current class (the lookupClass) as a lookup class
1621          * for method handle creation.
1622          * Must be called by from a method in this package,
1623          * which in turn is called by a method not in this package.
1624          */
1625         Lookup(Class<?> lookupClass) {
1626             this(lookupClass, null, FULL_POWER_MODES);
1627         }
1628 
1629         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1630             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1631                     && prevLookupClass.getModule() != lookupClass.getModule());
1632             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1633             this.lookupClass = lookupClass;
1634             this.prevLookupClass = prevLookupClass;
1635             this.allowedModes = allowedModes;
1636         }
1637 
1638         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1639             // make sure we haven't accidentally picked up a privileged class:
1640             checkUnprivilegedlookupClass(lookupClass);
1641             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1642         }
1643 
1644         /**
1645          * Creates a lookup on the specified new lookup class.
1646          * The resulting object will report the specified
1647          * class as its own {@link #lookupClass() lookupClass}.
1648          *
1649          * <p>
1650          * However, the resulting {@code Lookup} object is guaranteed
1651          * to have no more access capabilities than the original.
1652          * In particular, access capabilities can be lost as follows:<ul>
1653          * <li>If the new lookup class is different from the old lookup class,
1654          * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1655          * <li>If the new lookup class is in a different module from the old one,
1656          * i.e. {@link #MODULE MODULE} access is lost.
1657          * <li>If the new lookup class is in a different package
1658          * than the old one, protected and default (package) members will not be accessible,
1659          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1660          * <li>If the new lookup class is not within the same package member
1661          * as the old one, private members will not be accessible, and protected members
1662          * will not be accessible by virtue of inheritance,
1663          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1664          * (Protected members may continue to be accessible because of package sharing.)
1665          * <li>If the new lookup class is not
1666          * {@linkplain #accessClass(Class) accessible} to this lookup,
1667          * then no members, not even public members, will be accessible
1668          * i.e. all access modes are lost.
1669          * <li>If the new lookup class, the old lookup class and the previous lookup class
1670          * are all in different modules i.e. teleporting to a third module,
1671          * all access modes are lost.
1672          * </ul>
1673          * <p>
1674          * The new previous lookup class is chosen as follows:
1675          * <ul>
1676          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1677          * the new previous lookup class is {@code null}.
1678          * <li>If the new lookup class is in the same module as the old lookup class,
1679          * the new previous lookup class is the old previous lookup class.
1680          * <li>If the new lookup class is in a different module from the old lookup class,
1681          * the new previous lookup class is the old lookup class.
1682          *</ul>
1683          * <p>
1684          * The resulting lookup's capabilities for loading classes
1685          * (used during {@link #findClass} invocations)
1686          * are determined by the lookup class' loader,
1687          * which may change due to this operation.
1688          *
1689          * @param requestedLookupClass the desired lookup class for the new lookup object
1690          * @return a lookup object which reports the desired lookup class, or the same object
1691          * if there is no change
1692          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1693          * @throws NullPointerException if the argument is null
1694          *
1695          * @see #accessClass(Class)
1696          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1697          */
1698         public Lookup in(Class<?> requestedLookupClass) {
1699             Objects.requireNonNull(requestedLookupClass);
1700             if (requestedLookupClass.isPrimitive())
1701                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1702             if (requestedLookupClass.isArray())
1703                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1704 
1705             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1706                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1707             if (requestedLookupClass == this.lookupClass)
1708                 return this;  // keep same capabilities
1709             int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1710             Module fromModule = this.lookupClass.getModule();
1711             Module targetModule = requestedLookupClass.getModule();
1712             Class<?> plc = this.previousLookupClass();
1713             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1714                 assert plc == null;
1715                 newModes = UNCONDITIONAL;
1716             } else if (fromModule != targetModule) {
1717                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1718                     // allow hopping back and forth between fromModule and plc's module
1719                     // but not the third module
1720                     newModes = 0;
1721                 }
1722                 // drop MODULE access
1723                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1724                 // teleport from this lookup class
1725                 plc = this.lookupClass;
1726             }
1727             if ((newModes & PACKAGE) != 0
1728                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1729                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1730             }
1731             // Allow nestmate lookups to be created without special privilege:
1732             if ((newModes & PRIVATE) != 0
1733                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1734                 newModes &= ~(PRIVATE|PROTECTED);
1735             }
1736             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1737                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1738                 // The requested class it not accessible from the lookup class.
1739                 // No permissions.
1740                 newModes = 0;
1741             }
1742             return newLookup(requestedLookupClass, plc, newModes);
1743         }
1744 
1745         /**
1746          * Creates a lookup on the same lookup class which this lookup object
1747          * finds members, but with a lookup mode that has lost the given lookup mode.
1748          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1749          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1750          * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1751          * {@link #UNCONDITIONAL UNCONDITIONAL}.
1752          *
1753          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1754          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1755          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1756          * lookup has no access.
1757          *
1758          * <p> If this lookup is not a public lookup, then the following applies
1759          * regardless of its {@linkplain #lookupModes() lookup modes}.
1760          * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1761          * dropped and so the resulting lookup mode will never have these access
1762          * capabilities. When dropping {@code PACKAGE}
1763          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1764          * access. When dropping {@code MODULE} then the resulting lookup will not
1765          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1766          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1767          *
1768          * @apiNote
1769          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1770          * delegate non-public access within the package of the lookup class without
1771          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1772          * A lookup with {@code MODULE} but not
1773          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1774          * the module of the lookup class without conferring package access.
1775          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1776          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1777          * to public classes accessible to both the module of the lookup class
1778          * and the module of the previous lookup class.
1779          *
1780          * @param modeToDrop the lookup mode to drop
1781          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1782          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1783          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1784          * or {@code UNCONDITIONAL}
1785          * @see MethodHandles#privateLookupIn
1786          * @since 9
1787          */
1788         public Lookup dropLookupMode(int modeToDrop) {
1789             int oldModes = lookupModes();
1790             int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1791             switch (modeToDrop) {
1792                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1793                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1794                 case PACKAGE: newModes &= ~(PRIVATE); break;
1795                 case PROTECTED:
1796                 case PRIVATE:
1797                 case ORIGINAL:
1798                 case UNCONDITIONAL: break;
1799                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1800             }
1801             if (newModes == oldModes) return this;  // return self if no change
1802             return newLookup(lookupClass(), previousLookupClass(), newModes);
1803         }
1804 
1805         /**
1806          * Creates and links a class or interface from {@code bytes}
1807          * with the same class loader and in the same runtime package and
1808          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1809          * {@linkplain #lookupClass() lookup class} as if calling
1810          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1811          * ClassLoader::defineClass}.
1812          *
1813          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1814          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1815          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1816          * that the lookup object was created by a caller in the runtime package (or derived
1817          * from a lookup originally created by suitably privileged code to a target class in
1818          * the runtime package). </p>
1819          *
1820          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1821          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1822          * same package as the lookup class. </p>
1823          *
1824          * <p> This method does not run the class initializer. The class initializer may
1825          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1826          * Specification</em>. </p>
1827          *
1828          * <p> If there is a security manager and this lookup does not have {@linkplain
1829          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1830          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1831          *
1832          * @param bytes the class bytes
1833          * @return the {@code Class} object for the class
1834          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1835          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1836          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1837          * than the lookup class or {@code bytes} is not a class or interface
1838          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1839          * @throws VerifyError if the newly created class cannot be verified
1840          * @throws LinkageError if the newly created class cannot be linked for any other reason
1841          * @throws SecurityException if a security manager is present and it
1842          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1843          * @throws NullPointerException if {@code bytes} is {@code null}
1844          * @since 9
1845          * @see Lookup#privateLookupIn
1846          * @see Lookup#dropLookupMode
1847          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1848          */
1849         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1850             ensureDefineClassPermission();
1851             if ((lookupModes() & PACKAGE) == 0)
1852                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1853             return makeClassDefiner(bytes.clone()).defineClass(false);
1854         }
1855 
1856         private void ensureDefineClassPermission() {
1857             if (allowedModes == TRUSTED)  return;
1858 
1859             if (!hasFullPrivilegeAccess()) {
1860                 @SuppressWarnings("removal")
1861                 SecurityManager sm = System.getSecurityManager();
1862                 if (sm != null)
1863                     sm.checkPermission(new RuntimePermission("defineClass"));
1864             }
1865         }
1866 
1867         /**
1868          * The set of class options that specify whether a hidden class created by
1869          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1870          * Lookup::defineHiddenClass} method is dynamically added as a new member
1871          * to the nest of a lookup class and/or whether a hidden class has
1872          * a strong relationship with the class loader marked as its defining loader.
1873          *
1874          * @since 15
1875          */
1876         public enum ClassOption {
1877             /**
1878              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1879              * of a lookup class as a nestmate.
1880              *
1881              * <p> A hidden nestmate class has access to the private members of all
1882              * classes and interfaces in the same nest.
1883              *
1884              * @see Class#getNestHost()
1885              */
1886             NESTMATE(NESTMATE_CLASS),
1887 
1888             /**
1889              * Specifies that a hidden class has a <em>strong</em>
1890              * relationship with the class loader marked as its defining loader,
1891              * as a normal class or interface has with its own defining loader.
1892              * This means that the hidden class may be unloaded if and only if
1893              * its defining loader is not reachable and thus may be reclaimed
1894              * by a garbage collector (JLS {@jls 12.7}).
1895              *
1896              * <p> By default, a hidden class or interface may be unloaded
1897              * even if the class loader that is marked as its defining loader is
1898              * <a href="../ref/package-summary.html#reachability">reachable</a>.
1899 
1900              *
1901              * @jls 12.7 Unloading of Classes and Interfaces
1902              */
1903             STRONG(STRONG_LOADER_LINK);
1904 
1905             /* the flag value is used by VM at define class time */
1906             private final int flag;
1907             ClassOption(int flag) {
1908                 this.flag = flag;
1909             }
1910 
1911             static int optionsToFlag(Set<ClassOption> options) {
1912                 int flags = 0;
1913                 for (ClassOption cp : options) {
1914                     flags |= cp.flag;
1915                 }
1916                 return flags;
1917             }
1918         }
1919 
1920         /**
1921          * Creates a <em>hidden</em> class or interface from {@code bytes},
1922          * returning a {@code Lookup} on the newly created class or interface.
1923          *
1924          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1925          * which either defines {@code C} directly or delegates to another class loader.
1926          * A class loader defines {@code C} directly by invoking
1927          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1928          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1929          * to derive {@code C} from a purported representation in {@code class} file format.
1930          * In situations where use of a class loader is undesirable, a class or interface
1931          * {@code C} can be created by this method instead. This method is capable of
1932          * defining {@code C}, and thereby creating it, without invoking
1933          * {@code ClassLoader::defineClass}.
1934          * Instead, this method defines {@code C} as if by arranging for
1935          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1936          * from a purported representation in {@code class} file format
1937          * using the following rules:
1938          *
1939          * <ol>
1940          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1941          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1942          * This level of access is needed to create {@code C} in the module
1943          * of the lookup class of this {@code Lookup}.</li>
1944          *
1945          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1946          * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1947          * The major and minor version may differ from the {@code class} file version
1948          * of the lookup class of this {@code Lookup}.</li>
1949          *
1950          * <li> The value of {@code this_class} must be a valid index in the
1951          * {@code constant_pool} table, and the entry at that index must be a valid
1952          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1953          * encoded in internal form that is specified by this structure. {@code N} must
1954          * denote a class or interface in the same package as the lookup class.</li>
1955          *
1956          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1957          * where {@code <suffix>} is an unqualified name.
1958          *
1959          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1960          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1961          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1962          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1963          * refers to the new {@code CONSTANT_Utf8_info} structure.
1964          *
1965          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1966          *
1967          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1968          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1969          * with the following adjustments:
1970          * <ul>
1971          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1972          * that includes a single {@code "."} character, even though this is not a valid
1973          * binary class or interface name in internal form.</li>
1974          *
1975          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1976          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1977          *
1978          * <li> {@code C} is considered to have the same runtime
1979          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1980          * and {@linkplain java.security.ProtectionDomain protection domain}
1981          * as the lookup class of this {@code Lookup}.
1982          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1983          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1984          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1985          * <ul>
1986          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1987          *      even though this is not a valid binary class or interface name.</li>
1988          * <li> {@link Class#descriptorString()} returns the string
1989          *      {@code "L" + N + "." + <suffix> + ";"},
1990          *      even though this is not a valid type descriptor name.</li>
1991          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
1992          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
1993          * </ul>
1994          * </ul>
1995          * </li>
1996          * </ol>
1997          *
1998          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1999          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
2000          * <ul>
2001          * <li> During verification, whenever it is necessary to load the class named
2002          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
2003          * made of any class loader.</li>
2004          *
2005          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
2006          * by {@code this_class}, the symbolic reference is considered to be resolved to
2007          * {@code C} and resolution always succeeds immediately.</li>
2008          * </ul>
2009          *
2010          * <p> If the {@code initialize} parameter is {@code true},
2011          * then {@code C} is initialized by the Java Virtual Machine.
2012          *
2013          * <p> The newly created class or interface {@code C} serves as the
2014          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
2015          * returned by this method. {@code C} is <em>hidden</em> in the sense that
2016          * no other class or interface can refer to {@code C} via a constant pool entry.
2017          * That is, a hidden class or interface cannot be named as a supertype, a field type,
2018          * a method parameter type, or a method return type by any other class.
2019          * This is because a hidden class or interface does not have a binary name, so
2020          * there is no internal form available to record in any class's constant pool.
2021          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
2022          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
2023          * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class)
2024          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
2025          * JVM Tool Interface</a>.
2026          *
2027          * <p> A class or interface created by
2028          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
2029          * a class loader} has a strong relationship with that class loader.
2030          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
2031          * that {@linkplain Class#getClassLoader() defined it}.
2032          * This means that a class created by a class loader may be unloaded if and
2033          * only if its defining loader is not reachable and thus may be reclaimed
2034          * by a garbage collector (JLS {@jls 12.7}).
2035          *
2036          * By default, however, a hidden class or interface may be unloaded even if
2037          * the class loader that is marked as its defining loader is
2038          * <a href="../ref/package-summary.html#reachability">reachable</a>.
2039          * This behavior is useful when a hidden class or interface serves multiple
2040          * classes defined by arbitrary class loaders.  In other cases, a hidden
2041          * class or interface may be linked to a single class (or a small number of classes)
2042          * with the same defining loader as the hidden class or interface.
2043          * In such cases, where the hidden class or interface must be coterminous
2044          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
2045          * option may be passed in {@code options}.
2046          * This arranges for a hidden class to have the same strong relationship
2047          * with the class loader marked as its defining loader,
2048          * as a normal class or interface has with its own defining loader.
2049          *
2050          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
2051          * may still prevent a hidden class or interface from being
2052          * unloaded by ensuring that the {@code Class} object is reachable.
2053          *
2054          * <p> The unloading characteristics are set for each hidden class when it is
2055          * defined, and cannot be changed later.  An advantage of allowing hidden classes
2056          * to be unloaded independently of the class loader marked as their defining loader
2057          * is that a very large number of hidden classes may be created by an application.
2058          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
2059          * just as if normal classes were created by class loaders.
2060          *
2061          * <p> Classes and interfaces in a nest are allowed to have mutual access to
2062          * their private members.  The nest relationship is determined by
2063          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
2064          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
2065          * By default, a hidden class belongs to a nest consisting only of itself
2066          * because a hidden class has no binary name.
2067          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
2068          * to create a hidden class or interface {@code C} as a member of a nest.
2069          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
2070          * in the {@code ClassFile} structure from which {@code C} was derived.
2071          * Instead, the following rules determine the nest host of {@code C}:
2072          * <ul>
2073          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
2074          *     been determined, then let {@code H} be the nest host of the lookup class.
2075          *     Otherwise, the nest host of the lookup class is determined using the
2076          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
2077          * <li>The nest host of {@code C} is determined to be {@code H},
2078          *     the nest host of the lookup class.</li>
2079          * </ul>
2080          *
2081          * <p> A hidden class or interface may be serializable, but this requires a custom
2082          * serialization mechanism in order to ensure that instances are properly serialized
2083          * and deserialized. The default serialization mechanism supports only classes and
2084          * interfaces that are discoverable by their class name.
2085          *
2086          * @param bytes the bytes that make up the class data,
2087          * in the format of a valid {@code class} file as defined by
2088          * <cite>The Java Virtual Machine Specification</cite>.
2089          * @param initialize if {@code true} the class will be initialized.
2090          * @param options {@linkplain ClassOption class options}
2091          * @return the {@code Lookup} object on the hidden class,
2092          * with {@linkplain #ORIGINAL original} and
2093          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2094          *
2095          * @throws IllegalAccessException if this {@code Lookup} does not have
2096          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2097          * @throws SecurityException if a security manager is present and it
2098          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2099          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2100          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2101          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2102          * than the lookup class or {@code bytes} is not a class or interface
2103          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2104          * @throws IncompatibleClassChangeError if the class or interface named as
2105          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2106          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2107          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2108          * {@code C} is {@code C} itself
2109          * @throws VerifyError if the newly created class cannot be verified
2110          * @throws LinkageError if the newly created class cannot be linked for any other reason
2111          * @throws NullPointerException if any parameter is {@code null}
2112          *
2113          * @since 15
2114          * @see Class#isHidden()
2115          * @jvms 4.2.1 Binary Class and Interface Names
2116          * @jvms 4.2.2 Unqualified Names
2117          * @jvms 4.7.28 The {@code NestHost} Attribute
2118          * @jvms 4.7.29 The {@code NestMembers} Attribute
2119          * @jvms 5.4.3.1 Class and Interface Resolution
2120          * @jvms 5.4.4 Access Control
2121          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2122          * @jvms 5.4 Linking
2123          * @jvms 5.5 Initialization
2124          * @jls 12.7 Unloading of Classes and Interfaces
2125          */
2126         @SuppressWarnings("doclint:reference") // cross-module links
2127         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2128                 throws IllegalAccessException
2129         {
2130             Objects.requireNonNull(bytes);
2131             Objects.requireNonNull(options);
2132 
2133             ensureDefineClassPermission();
2134             if (!hasFullPrivilegeAccess()) {
2135                 throw new IllegalAccessException(this + " does not have full privilege access");
2136             }
2137 
2138             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
2139         }
2140 
2141         /**
2142          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2143          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2144          * returning a {@code Lookup} on the newly created class or interface.
2145          *
2146          * <p> This method is equivalent to calling
2147          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2148          * as if the hidden class is injected with a private static final <i>unnamed</i>
2149          * field which is initialized with the given {@code classData} at
2150          * the first instruction of the class initializer.
2151          * The newly created class is linked by the Java Virtual Machine.
2152          *
2153          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2154          * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2155          * methods can be used to retrieve the {@code classData}.
2156          *
2157          * @apiNote
2158          * A framework can create a hidden class with class data with one or more
2159          * objects and load the class data as dynamically-computed constant(s)
2160          * via a bootstrap method.  {@link MethodHandles#classData(Lookup, String, Class)
2161          * Class data} is accessible only to the lookup object created by the newly
2162          * defined hidden class but inaccessible to other members in the same nest
2163          * (unlike private static fields that are accessible to nestmates).
2164          * Care should be taken w.r.t. mutability for example when passing
2165          * an array or other mutable structure through the class data.
2166          * Changing any value stored in the class data at runtime may lead to
2167          * unpredictable behavior.
2168          * If the class data is a {@code List}, it is good practice to make it
2169          * unmodifiable for example via {@link List#of List::of}.
2170          *
2171          * @param bytes     the class bytes
2172          * @param classData pre-initialized class data
2173          * @param initialize if {@code true} the class will be initialized.
2174          * @param options   {@linkplain ClassOption class options}
2175          * @return the {@code Lookup} object on the hidden class,
2176          * with {@linkplain #ORIGINAL original} and
2177          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2178          *
2179          * @throws IllegalAccessException if this {@code Lookup} does not have
2180          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2181          * @throws SecurityException if a security manager is present and it
2182          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2183          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2184          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2185          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2186          * than the lookup class or {@code bytes} is not a class or interface
2187          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2188          * @throws IncompatibleClassChangeError if the class or interface named as
2189          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2190          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2191          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2192          * {@code C} is {@code C} itself
2193          * @throws VerifyError if the newly created class cannot be verified
2194          * @throws LinkageError if the newly created class cannot be linked for any other reason
2195          * @throws NullPointerException if any parameter is {@code null}
2196          *
2197          * @since 16
2198          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2199          * @see Class#isHidden()
2200          * @see MethodHandles#classData(Lookup, String, Class)
2201          * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2202          * @jvms 4.2.1 Binary Class and Interface Names
2203          * @jvms 4.2.2 Unqualified Names
2204          * @jvms 4.7.28 The {@code NestHost} Attribute
2205          * @jvms 4.7.29 The {@code NestMembers} Attribute
2206          * @jvms 5.4.3.1 Class and Interface Resolution
2207          * @jvms 5.4.4 Access Control
2208          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2209          * @jvms 5.4 Linking
2210          * @jvms 5.5 Initialization
2211          * @jls 12.7 Unloading of Classes and Interface
2212          */
2213         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2214                 throws IllegalAccessException
2215         {
2216             Objects.requireNonNull(bytes);
2217             Objects.requireNonNull(classData);
2218             Objects.requireNonNull(options);
2219 
2220             ensureDefineClassPermission();
2221             if (!hasFullPrivilegeAccess()) {
2222                 throw new IllegalAccessException(this + " does not have full privilege access");
2223             }
2224 
2225             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2226                        .defineClassAsLookup(initialize, classData);
2227         }
2228 
2229         // A default dumper for writing class files passed to Lookup::defineClass
2230         // and Lookup::defineHiddenClass to disk for debugging purposes.  To enable,
2231         // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or
2232         //     -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true
2233         //
2234         // This default dumper does not dump hidden classes defined by LambdaMetafactory
2235         // and LambdaForms and method handle internals.  They are dumped via
2236         // different ClassFileDumpers.
2237         private static ClassFileDumper defaultDumper() {
2238             return DEFAULT_DUMPER;
2239         }
2240 
2241         private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance(
2242                 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES");
2243 
2244         static class ClassFile {
2245             final String name;  // internal name
2246             final int accessFlags;
2247             final byte[] bytes;
2248             ClassFile(String name, int accessFlags, byte[] bytes) {
2249                 this.name = name;
2250                 this.accessFlags = accessFlags;
2251                 this.bytes = bytes;
2252             }
2253 
2254             static ClassFile newInstanceNoCheck(String name, byte[] bytes) {
2255                 return new ClassFile(name, 0, bytes);
2256             }
2257 
2258             /**
2259              * This method checks the class file version and the structure of `this_class`.
2260              * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2261              * that is in the named package.
2262              *
2263              * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2264              * or the class is not in the given package name.
2265              */
2266             static ClassFile newInstance(byte[] bytes, String pkgName) {
2267                 var cf = readClassFile(bytes);
2268 
2269                 // check if it's in the named package
2270                 int index = cf.name.lastIndexOf('/');
2271                 String pn = (index == -1) ? "" : cf.name.substring(0, index).replace('/', '.');
2272                 if (!pn.equals(pkgName)) {
2273                     throw newIllegalArgumentException(cf.name + " not in same package as lookup class");
2274                 }
2275                 return cf;
2276             }
2277 
2278             private static ClassFile readClassFile(byte[] bytes) {
2279                 int magic = readInt(bytes, 0);
2280                 if (magic != 0xCAFEBABE) {
2281                     throw new ClassFormatError("Incompatible magic value: " + magic);
2282                 }
2283                 int minor = readUnsignedShort(bytes, 4);
2284                 int major = readUnsignedShort(bytes, 6);
2285                 if (!VM.isSupportedClassFileVersion(major, minor)) {
2286                     throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2287                 }
2288 
2289                 String name;
2290                 int accessFlags;
2291                 try {
2292                     ClassReader reader = new ClassReader(bytes);
2293                     // ClassReader does not check if `this_class` is CONSTANT_Class_info
2294                     // workaround to read `this_class` using readConst and validate the value
2295                     int thisClass = reader.readUnsignedShort(reader.header + 2);
2296                     Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]);
2297                     if (!(constant instanceof Type type)) {
2298                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2299                     }
2300                     if (!type.getDescriptor().startsWith("L")) {
2301                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2302                     }
2303                     name = type.getInternalName();
2304                     accessFlags = reader.readUnsignedShort(reader.header);
2305                 } catch (RuntimeException e) {
2306                     // ASM exceptions are poorly specified
2307                     ClassFormatError cfe = new ClassFormatError();
2308                     cfe.initCause(e);
2309                     throw cfe;
2310                 }
2311                 // must be a class or interface
2312                 if ((accessFlags & Opcodes.ACC_MODULE) != 0) {
2313                     throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2314                 }
2315                 return new ClassFile(name, accessFlags, bytes);
2316             }
2317 
2318             private static int readInt(byte[] bytes, int offset) {
2319                 if ((offset+4) > bytes.length) {
2320                     throw new ClassFormatError("Invalid ClassFile structure");
2321                 }
2322                 return ((bytes[offset] & 0xFF) << 24)
2323                         | ((bytes[offset + 1] & 0xFF) << 16)
2324                         | ((bytes[offset + 2] & 0xFF) << 8)
2325                         | (bytes[offset + 3] & 0xFF);
2326             }
2327 
2328             private static int readUnsignedShort(byte[] bytes, int offset) {
2329                 if ((offset+2) > bytes.length) {
2330                     throw new ClassFormatError("Invalid ClassFile structure");
2331                 }
2332                 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2333             }
2334         }
2335 
2336         /*
2337          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2338          * from the given bytes.
2339          *
2340          * Caller should make a defensive copy of the arguments if needed
2341          * before calling this factory method.
2342          *
2343          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2344          * {@code bytes} denotes a class in a different package than the lookup class
2345          */
2346         private ClassDefiner makeClassDefiner(byte[] bytes) {
2347             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2348             return new ClassDefiner(this, cf, STRONG_LOADER_LINK, defaultDumper());
2349         }
2350 
2351         /**
2352          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2353          * from the given bytes.  No package name check on the given bytes.
2354          *
2355          * @param name    internal name
2356          * @param bytes   class bytes
2357          * @param dumper  dumper to write the given bytes to the dumper's output directory
2358          * @return ClassDefiner that defines a normal class of the given bytes.
2359          */
2360         ClassDefiner makeClassDefiner(String name, byte[] bytes, ClassFileDumper dumper) {
2361             // skip package name validation
2362             ClassFile cf = ClassFile.newInstanceNoCheck(name, bytes);
2363             return new ClassDefiner(this, cf, STRONG_LOADER_LINK, dumper);
2364         }
2365 
2366         /**
2367          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2368          * from the given bytes.  The name must be in the same package as the lookup class.
2369          *
2370          * Caller should make a defensive copy of the arguments if needed
2371          * before calling this factory method.
2372          *
2373          * @param bytes   class bytes
2374          * @param dumper dumper to write the given bytes to the dumper's output directory
2375          * @return ClassDefiner that defines a hidden class of the given bytes.
2376          *
2377          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2378          * {@code bytes} denotes a class in a different package than the lookup class
2379          */
2380         ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) {
2381             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2382             return makeHiddenClassDefiner(cf, Set.of(), false, dumper);
2383         }
2384 
2385         /**
2386          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2387          * from the given bytes and options.
2388          * The name must be in the same package as the lookup class.
2389          *
2390          * Caller should make a defensive copy of the arguments if needed
2391          * before calling this factory method.
2392          *
2393          * @param bytes   class bytes
2394          * @param options class options
2395          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2396          * @return ClassDefiner that defines a hidden class of the given bytes and options
2397          *
2398          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2399          * {@code bytes} denotes a class in a different package than the lookup class
2400          */
2401         private ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2402                                                     Set<ClassOption> options,
2403                                                     boolean accessVmAnnotations) {
2404             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2405             return makeHiddenClassDefiner(cf, options, accessVmAnnotations, defaultDumper());
2406         }
2407 
2408         /**
2409          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2410          * from the given bytes and the given options.  No package name check on the given bytes.
2411          *
2412          * @param name    internal name that specifies the prefix of the hidden class
2413          * @param bytes   class bytes
2414          * @param options class options
2415          * @param dumper  dumper to write the given bytes to the dumper's output directory
2416          * @return ClassDefiner that defines a hidden class of the given bytes and options.
2417          */
2418         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options, ClassFileDumper dumper) {
2419             Objects.requireNonNull(dumper);
2420             // skip name and access flags validation
2421             return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false, dumper);
2422         }
2423 
2424         /**
2425          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2426          * from the given class file and options.
2427          *
2428          * @param cf ClassFile
2429          * @param options class options
2430          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2431          * @param dumper dumper to write the given bytes to the dumper's output directory
2432          */
2433         private ClassDefiner makeHiddenClassDefiner(ClassFile cf,
2434                                                     Set<ClassOption> options,
2435                                                     boolean accessVmAnnotations,
2436                                                     ClassFileDumper dumper) {
2437             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2438             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2439                 // jdk.internal.vm.annotations are permitted for classes
2440                 // defined to boot loader and platform loader
2441                 flags |= ACCESS_VM_ANNOTATIONS;
2442             }
2443 
2444             return new ClassDefiner(this, cf, flags, dumper);
2445         }
2446 
2447         static class ClassDefiner {
2448             private final Lookup lookup;
2449             private final String name;  // internal name
2450             private final byte[] bytes;
2451             private final int classFlags;
2452             private final ClassFileDumper dumper;
2453 
2454             private ClassDefiner(Lookup lookup, ClassFile cf, int flags, ClassFileDumper dumper) {
2455                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2456                 this.lookup = lookup;
2457                 this.bytes = cf.bytes;
2458                 this.name = cf.name;
2459                 this.classFlags = flags;
2460                 this.dumper = dumper;
2461             }
2462 
2463             String internalName() {
2464                 return name;
2465             }
2466 
2467             Class<?> defineClass(boolean initialize) {
2468                 return defineClass(initialize, null);
2469             }
2470 
2471             Lookup defineClassAsLookup(boolean initialize) {
2472                 Class<?> c = defineClass(initialize, null);
2473                 return new Lookup(c, null, FULL_POWER_MODES);
2474             }
2475 
2476             /**
2477              * Defines the class of the given bytes and the given classData.
2478              * If {@code initialize} parameter is true, then the class will be initialized.
2479              *
2480              * @param initialize true if the class to be initialized
2481              * @param classData classData or null
2482              * @return the class
2483              *
2484              * @throws LinkageError linkage error
2485              */
2486             Class<?> defineClass(boolean initialize, Object classData) {
2487                 Class<?> lookupClass = lookup.lookupClass();
2488                 ClassLoader loader = lookupClass.getClassLoader();
2489                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2490                 Class<?> c = null;
2491                 try {
2492                     c = SharedSecrets.getJavaLangAccess()
2493                             .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2494                     assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2495                     return c;
2496                 } finally {
2497                     // dump the classfile for debugging
2498                     if (dumper.isEnabled()) {
2499                         String name = internalName();
2500                         if (c != null) {
2501                             dumper.dumpClass(name, c, bytes);
2502                         } else {
2503                             dumper.dumpFailedClass(name, bytes);
2504                         }
2505                     }
2506                 }
2507             }
2508 
2509             /**
2510              * Defines the class of the given bytes and the given classData.
2511              * If {@code initialize} parameter is true, then the class will be initialized.
2512              *
2513              * @param initialize true if the class to be initialized
2514              * @param classData classData or null
2515              * @return a Lookup for the defined class
2516              *
2517              * @throws LinkageError linkage error
2518              */
2519             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2520                 Class<?> c = defineClass(initialize, classData);
2521                 return new Lookup(c, null, FULL_POWER_MODES);
2522             }
2523 
2524             private boolean isNestmate() {
2525                 return (classFlags & NESTMATE_CLASS) != 0;
2526             }
2527         }
2528 
2529         private ProtectionDomain lookupClassProtectionDomain() {
2530             ProtectionDomain pd = cachedProtectionDomain;
2531             if (pd == null) {
2532                 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2533             }
2534             return pd;
2535         }
2536 
2537         // cached protection domain
2538         private volatile ProtectionDomain cachedProtectionDomain;
2539 
2540         // Make sure outer class is initialized first.
2541         static { IMPL_NAMES.getClass(); }
2542 
2543         /** Package-private version of lookup which is trusted. */
2544         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2545 
2546         /** Version of lookup which is trusted minimally.
2547          *  It can only be used to create method handles to publicly accessible
2548          *  members in packages that are exported unconditionally.
2549          */
2550         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2551 
2552         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2553             String name = lookupClass.getName();
2554             if (name.startsWith("java.lang.invoke."))
2555                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2556         }
2557 
2558         /**
2559          * Displays the name of the class from which lookups are to be made,
2560          * followed by "/" and the name of the {@linkplain #previousLookupClass()
2561          * previous lookup class} if present.
2562          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2563          * If there are restrictions on the access permitted to this lookup,
2564          * this is indicated by adding a suffix to the class name, consisting
2565          * of a slash and a keyword.  The keyword represents the strongest
2566          * allowed access, and is chosen as follows:
2567          * <ul>
2568          * <li>If no access is allowed, the suffix is "/noaccess".
2569          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2570          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2571          * <li>If only public and module access are allowed, the suffix is "/module".
2572          * <li>If public and package access are allowed, the suffix is "/package".
2573          * <li>If public, package, and private access are allowed, the suffix is "/private".
2574          * </ul>
2575          * If none of the above cases apply, it is the case that
2576          * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2577          * (public, module, package, private, and protected) is allowed.
2578          * In this case, no suffix is added.
2579          * This is true only of an object obtained originally from
2580          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2581          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2582          * always have restricted access, and will display a suffix.
2583          * <p>
2584          * (It may seem strange that protected access should be
2585          * stronger than private access.  Viewed independently from
2586          * package access, protected access is the first to be lost,
2587          * because it requires a direct subclass relationship between
2588          * caller and callee.)
2589          * @see #in
2590          */
2591         @Override
2592         public String toString() {
2593             String cname = lookupClass.getName();
2594             if (prevLookupClass != null)
2595                 cname += "/" + prevLookupClass.getName();
2596             switch (allowedModes) {
2597             case 0:  // no privileges
2598                 return cname + "/noaccess";
2599             case UNCONDITIONAL:
2600                 return cname + "/publicLookup";
2601             case PUBLIC:
2602                 return cname + "/public";
2603             case PUBLIC|MODULE:
2604                 return cname + "/module";
2605             case PUBLIC|PACKAGE:
2606             case PUBLIC|MODULE|PACKAGE:
2607                 return cname + "/package";
2608             case PUBLIC|PACKAGE|PRIVATE:
2609             case PUBLIC|MODULE|PACKAGE|PRIVATE:
2610                     return cname + "/private";
2611             case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2612             case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2613             case FULL_POWER_MODES:
2614                     return cname;
2615             case TRUSTED:
2616                 return "/trusted";  // internal only; not exported
2617             default:  // Should not happen, but it's a bitfield...
2618                 cname = cname + "/" + Integer.toHexString(allowedModes);
2619                 assert(false) : cname;
2620                 return cname;
2621             }
2622         }
2623 
2624         /**
2625          * Produces a method handle for a static method.
2626          * The type of the method handle will be that of the method.
2627          * (Since static methods do not take receivers, there is no
2628          * additional receiver argument inserted into the method handle type,
2629          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2630          * The method and all its argument types must be accessible to the lookup object.
2631          * <p>
2632          * The returned method handle will have
2633          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2634          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2635          * <p>
2636          * If the returned method handle is invoked, the method's class will
2637          * be initialized, if it has not already been initialized.
2638          * <p><b>Example:</b>
2639          * {@snippet lang="java" :
2640 import static java.lang.invoke.MethodHandles.*;
2641 import static java.lang.invoke.MethodType.*;
2642 ...
2643 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2644   "asList", methodType(List.class, Object[].class));
2645 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2646          * }
2647          * @param refc the class from which the method is accessed
2648          * @param name the name of the method
2649          * @param type the type of the method
2650          * @return the desired method handle
2651          * @throws NoSuchMethodException if the method does not exist
2652          * @throws IllegalAccessException if access checking fails,
2653          *                                or if the method is not {@code static},
2654          *                                or if the method's variable arity modifier bit
2655          *                                is set and {@code asVarargsCollector} fails
2656          * @throws    SecurityException if a security manager is present and it
2657          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2658          * @throws NullPointerException if any argument is null
2659          */
2660         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2661             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2662             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2663         }
2664 
2665         /**
2666          * Produces a method handle for a virtual method.
2667          * The type of the method handle will be that of the method,
2668          * with the receiver type (usually {@code refc}) prepended.
2669          * The method and all its argument types must be accessible to the lookup object.
2670          * <p>
2671          * When called, the handle will treat the first argument as a receiver
2672          * and, for non-private methods, dispatch on the receiver's type to determine which method
2673          * implementation to enter.
2674          * For private methods the named method in {@code refc} will be invoked on the receiver.
2675          * (The dispatching action is identical with that performed by an
2676          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2677          * <p>
2678          * The first argument will be of type {@code refc} if the lookup
2679          * class has full privileges to access the member.  Otherwise
2680          * the member must be {@code protected} and the first argument
2681          * will be restricted in type to the lookup class.
2682          * <p>
2683          * The returned method handle will have
2684          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2685          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2686          * <p>
2687          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2688          * instructions and method handles produced by {@code findVirtual},
2689          * if the class is {@code MethodHandle} and the name string is
2690          * {@code invokeExact} or {@code invoke}, the resulting
2691          * method handle is equivalent to one produced by
2692          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2693          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2694          * with the same {@code type} argument.
2695          * <p>
2696          * If the class is {@code VarHandle} and the name string corresponds to
2697          * the name of a signature-polymorphic access mode method, the resulting
2698          * method handle is equivalent to one produced by
2699          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2700          * the access mode corresponding to the name string and with the same
2701          * {@code type} arguments.
2702          * <p>
2703          * <b>Example:</b>
2704          * {@snippet lang="java" :
2705 import static java.lang.invoke.MethodHandles.*;
2706 import static java.lang.invoke.MethodType.*;
2707 ...
2708 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2709   "concat", methodType(String.class, String.class));
2710 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2711   "hashCode", methodType(int.class));
2712 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2713   "hashCode", methodType(int.class));
2714 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2715 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2716 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2717 // interface method:
2718 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2719   "subSequence", methodType(CharSequence.class, int.class, int.class));
2720 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2721 // constructor "internal method" must be accessed differently:
2722 MethodType MT_newString = methodType(void.class); //()V for new String()
2723 try { assertEquals("impossible", lookup()
2724         .findVirtual(String.class, "<init>", MT_newString));
2725  } catch (NoSuchMethodException ex) { } // OK
2726 MethodHandle MH_newString = publicLookup()
2727   .findConstructor(String.class, MT_newString);
2728 assertEquals("", (String) MH_newString.invokeExact());
2729          * }
2730          *
2731          * @param refc the class or interface from which the method is accessed
2732          * @param name the name of the method
2733          * @param type the type of the method, with the receiver argument omitted
2734          * @return the desired method handle
2735          * @throws NoSuchMethodException if the method does not exist
2736          * @throws IllegalAccessException if access checking fails,
2737          *                                or if the method is {@code static},
2738          *                                or if the method's variable arity modifier bit
2739          *                                is set and {@code asVarargsCollector} fails
2740          * @throws    SecurityException if a security manager is present and it
2741          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2742          * @throws NullPointerException if any argument is null
2743          */
2744         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2745             if (refc == MethodHandle.class) {
2746                 MethodHandle mh = findVirtualForMH(name, type);
2747                 if (mh != null)  return mh;
2748             } else if (refc == VarHandle.class) {
2749                 MethodHandle mh = findVirtualForVH(name, type);
2750                 if (mh != null)  return mh;
2751             }
2752             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2753             MemberName method = resolveOrFail(refKind, refc, name, type);
2754             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2755         }
2756         private MethodHandle findVirtualForMH(String name, MethodType type) {
2757             // these names require special lookups because of the implicit MethodType argument
2758             if ("invoke".equals(name))
2759                 return invoker(type);
2760             if ("invokeExact".equals(name))
2761                 return exactInvoker(type);
2762             assert(!MemberName.isMethodHandleInvokeName(name));
2763             return null;
2764         }
2765         private MethodHandle findVirtualForVH(String name, MethodType type) {
2766             try {
2767                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2768             } catch (IllegalArgumentException e) {
2769                 return null;
2770             }
2771         }
2772 
2773         /**
2774          * Produces a method handle which creates an object and initializes it, using
2775          * the constructor of the specified type.
2776          * The parameter types of the method handle will be those of the constructor,
2777          * while the return type will be a reference to the constructor's class.
2778          * The constructor and all its argument types must be accessible to the lookup object.
2779          * <p>
2780          * The requested type must have a return type of {@code void}.
2781          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2782          * <p>
2783          * The returned method handle will have
2784          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2785          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2786          * <p>
2787          * If the returned method handle is invoked, the constructor's class will
2788          * be initialized, if it has not already been initialized.
2789          * <p><b>Example:</b>
2790          * {@snippet lang="java" :
2791 import static java.lang.invoke.MethodHandles.*;
2792 import static java.lang.invoke.MethodType.*;
2793 ...
2794 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2795   ArrayList.class, methodType(void.class, Collection.class));
2796 Collection orig = Arrays.asList("x", "y");
2797 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2798 assert(orig != copy);
2799 assertEquals(orig, copy);
2800 // a variable-arity constructor:
2801 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2802   ProcessBuilder.class, methodType(void.class, String[].class));
2803 ProcessBuilder pb = (ProcessBuilder)
2804   MH_newProcessBuilder.invoke("x", "y", "z");
2805 assertEquals("[x, y, z]", pb.command().toString());
2806          * }
2807          *
2808          *
2809          * @param refc the class or interface from which the method is accessed
2810          * @param type the type of the method, with the receiver argument omitted, and a void return type
2811          * @return the desired method handle
2812          * @throws NoSuchMethodException if the constructor does not exist
2813          * @throws IllegalAccessException if access checking fails
2814          *                                or if the method's variable arity modifier bit
2815          *                                is set and {@code asVarargsCollector} fails
2816          * @throws    SecurityException if a security manager is present and it
2817          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2818          * @throws NullPointerException if any argument is null
2819          */
2820         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2821             if (refc.isArray()) {
2822                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2823             }
2824             if (type.returnType() != void.class) {
2825                 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName());
2826             }
2827             String name = ConstantDescs.INIT_NAME;
2828             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2829             return getDirectConstructor(refc, ctor);
2830         }
2831 
2832         /**
2833          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2834          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2835          * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2836          * and then determines whether the class is accessible to this lookup object.
2837          * <p>
2838          * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}.
2839          * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences
2840          * of {@code '['} and followed by the element type as encoded in the
2841          * {@linkplain Class##nameFormat table} specified in {@link Class#getName}.
2842          * <p>
2843          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2844          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2845          *
2846          * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class
2847          *                   or the string representing an array class
2848          * @return the requested class.
2849          * @throws SecurityException if a security manager is present and it
2850          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2851          * @throws LinkageError if the linkage fails
2852          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2853          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2854          * modes.
2855          * @throws NullPointerException if {@code targetName} is null
2856          * @since 9
2857          * @jvms 5.4.3.1 Class and Interface Resolution
2858          */
2859         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2860             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2861             return accessClass(targetClass);
2862         }
2863 
2864         /**
2865          * Ensures that {@code targetClass} has been initialized. The class
2866          * to be initialized must be {@linkplain #accessClass accessible}
2867          * to this {@code Lookup} object.  This method causes {@code targetClass}
2868          * to be initialized if it has not been already initialized,
2869          * as specified in JVMS {@jvms 5.5}.
2870          *
2871          * <p>
2872          * This method returns when {@code targetClass} is fully initialized, or
2873          * when {@code targetClass} is being initialized by the current thread.
2874          *
2875          * @param <T> the type of the class to be initialized
2876          * @param targetClass the class to be initialized
2877          * @return {@code targetClass} that has been initialized, or that is being
2878          *         initialized by the current thread.
2879          *
2880          * @throws  IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2881          *          or array class
2882          * @throws  IllegalAccessException if {@code targetClass} is not
2883          *          {@linkplain #accessClass accessible} to this lookup
2884          * @throws  ExceptionInInitializerError if the class initialization provoked
2885          *          by this method fails
2886          * @throws  SecurityException if a security manager is present and it
2887          *          <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2888          * @since 15
2889          * @jvms 5.5 Initialization
2890          */
2891         public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException {
2892             if (targetClass.isPrimitive())
2893                 throw new IllegalArgumentException(targetClass + " is a primitive class");
2894             if (targetClass.isArray())
2895                 throw new IllegalArgumentException(targetClass + " is an array class");
2896 
2897             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2898                 throw makeAccessException(targetClass);
2899             }
2900             checkSecurityManager(targetClass);
2901 
2902             // ensure class initialization
2903             Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2904             return targetClass;
2905         }
2906 
2907         /*
2908          * Returns IllegalAccessException due to access violation to the given targetClass.
2909          *
2910          * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2911          * which verifies access to a class rather a member.
2912          */
2913         private IllegalAccessException makeAccessException(Class<?> targetClass) {
2914             String message = "access violation: "+ targetClass;
2915             if (this == MethodHandles.publicLookup()) {
2916                 message += ", from public Lookup";
2917             } else {
2918                 Module m = lookupClass().getModule();
2919                 message += ", from " + lookupClass() + " (" + m + ")";
2920                 if (prevLookupClass != null) {
2921                     message += ", previous lookup " +
2922                             prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2923                 }
2924             }
2925             return new IllegalAccessException(message);
2926         }
2927 
2928         /**
2929          * Determines if a class can be accessed from the lookup context defined by
2930          * this {@code Lookup} object. The static initializer of the class is not run.
2931          * If {@code targetClass} is an array class, {@code targetClass} is accessible
2932          * if the element type of the array class is accessible.  Otherwise,
2933          * {@code targetClass} is determined as accessible as follows.
2934          *
2935          * <p>
2936          * If {@code targetClass} is in the same module as the lookup class,
2937          * the lookup class is {@code LC} in module {@code M1} and
2938          * the previous lookup class is in module {@code M0} or
2939          * {@code null} if not present,
2940          * {@code targetClass} is accessible if and only if one of the following is true:
2941          * <ul>
2942          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2943          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2944          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2945          *     in the same runtime package of {@code LC}.</li>
2946          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2947          *     a public type in {@code M1}.</li>
2948          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2949          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2950          *     if the previous lookup class is present; otherwise, {@code targetClass}
2951          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2952          * </ul>
2953          *
2954          * <p>
2955          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2956          * can access public types in all modules when the type is in a package
2957          * that is exported unconditionally.
2958          * <p>
2959          * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2960          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2961          * is inaccessible.
2962          * <p>
2963          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2964          * {@code M1} is the module containing {@code lookupClass} and
2965          * {@code M2} is the module containing {@code targetClass},
2966          * then {@code targetClass} is accessible if and only if
2967          * <ul>
2968          * <li>{@code M1} reads {@code M2}, and
2969          * <li>{@code targetClass} is public and in a package exported by
2970          *     {@code M2} at least to {@code M1}.
2971          * </ul>
2972          * <p>
2973          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2974          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2975          * containing the previous lookup class, then {@code targetClass} is accessible
2976          * if and only if one of the following is true:
2977          * <ul>
2978          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2979          *     {@linkplain Module#reads reads} {@code M0} and the type is
2980          *     in a package that is exported to at least {@code M1}.
2981          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2982          *     {@linkplain Module#reads reads} {@code M1} and the type is
2983          *     in a package that is exported to at least {@code M0}.
2984          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2985          *     and {@code M1} reads {@code M2} and the type is in a package
2986          *     that is exported to at least both {@code M0} and {@code M2}.
2987          * </ul>
2988          * <p>
2989          * Otherwise, {@code targetClass} is not accessible.
2990          *
2991          * @param <T> the type of the class to be access-checked
2992          * @param targetClass the class to be access-checked
2993          * @return {@code targetClass} that has been access-checked
2994          * @throws IllegalAccessException if the class is not accessible from the lookup class
2995          * and previous lookup class, if present, using the allowed access modes.
2996          * @throws SecurityException if a security manager is present and it
2997          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2998          * @throws NullPointerException if {@code targetClass} is {@code null}
2999          * @since 9
3000          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
3001          */
3002         public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException {
3003             if (!isClassAccessible(targetClass)) {
3004                 throw makeAccessException(targetClass);
3005             }
3006             checkSecurityManager(targetClass);
3007             return targetClass;
3008         }
3009 
3010         /**
3011          * Produces an early-bound method handle for a virtual method.
3012          * It will bypass checks for overriding methods on the receiver,
3013          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3014          * instruction from within the explicitly specified {@code specialCaller}.
3015          * The type of the method handle will be that of the method,
3016          * with a suitably restricted receiver type prepended.
3017          * (The receiver type will be {@code specialCaller} or a subtype.)
3018          * The method and all its argument types must be accessible
3019          * to the lookup object.
3020          * <p>
3021          * Before method resolution,
3022          * if the explicitly specified caller class is not identical with the
3023          * lookup class, or if this lookup object does not have
3024          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3025          * privileges, the access fails.
3026          * <p>
3027          * The returned method handle will have
3028          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3029          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3030          * <p style="font-size:smaller;">
3031          * <em>(Note:  JVM internal methods named {@value ConstantDescs#INIT_NAME}
3032          * are not visible to this API,
3033          * even though the {@code invokespecial} instruction can refer to them
3034          * in special circumstances.  Use {@link #findConstructor findConstructor}
3035          * to access instance initialization methods in a safe manner.)</em>
3036          * <p><b>Example:</b>
3037          * {@snippet lang="java" :
3038 import static java.lang.invoke.MethodHandles.*;
3039 import static java.lang.invoke.MethodType.*;
3040 ...
3041 static class Listie extends ArrayList {
3042   public String toString() { return "[wee Listie]"; }
3043   static Lookup lookup() { return MethodHandles.lookup(); }
3044 }
3045 ...
3046 // no access to constructor via invokeSpecial:
3047 MethodHandle MH_newListie = Listie.lookup()
3048   .findConstructor(Listie.class, methodType(void.class));
3049 Listie l = (Listie) MH_newListie.invokeExact();
3050 try { assertEquals("impossible", Listie.lookup().findSpecial(
3051         Listie.class, "<init>", methodType(void.class), Listie.class));
3052  } catch (NoSuchMethodException ex) { } // OK
3053 // access to super and self methods via invokeSpecial:
3054 MethodHandle MH_super = Listie.lookup().findSpecial(
3055   ArrayList.class, "toString" , methodType(String.class), Listie.class);
3056 MethodHandle MH_this = Listie.lookup().findSpecial(
3057   Listie.class, "toString" , methodType(String.class), Listie.class);
3058 MethodHandle MH_duper = Listie.lookup().findSpecial(
3059   Object.class, "toString" , methodType(String.class), Listie.class);
3060 assertEquals("[]", (String) MH_super.invokeExact(l));
3061 assertEquals(""+l, (String) MH_this.invokeExact(l));
3062 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
3063 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
3064         String.class, "toString", methodType(String.class), Listie.class));
3065  } catch (IllegalAccessException ex) { } // OK
3066 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
3067 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
3068          * }
3069          *
3070          * @param refc the class or interface from which the method is accessed
3071          * @param name the name of the method (which must not be "&lt;init&gt;")
3072          * @param type the type of the method, with the receiver argument omitted
3073          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
3074          * @return the desired method handle
3075          * @throws NoSuchMethodException if the method does not exist
3076          * @throws IllegalAccessException if access checking fails,
3077          *                                or if the method is {@code static},
3078          *                                or if the method's variable arity modifier bit
3079          *                                is set and {@code asVarargsCollector} fails
3080          * @throws    SecurityException if a security manager is present and it
3081          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3082          * @throws NullPointerException if any argument is null
3083          */
3084         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
3085                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
3086             checkSpecialCaller(specialCaller, refc);
3087             Lookup specialLookup = this.in(specialCaller);
3088             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
3089             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
3090         }
3091 
3092         /**
3093          * Produces a method handle giving read access to a non-static field.
3094          * The type of the method handle will have a return type of the field's
3095          * value type.
3096          * The method handle's single argument will be the instance containing
3097          * the field.
3098          * Access checking is performed immediately on behalf of the lookup class.
3099          * @param refc the class or interface from which the method is accessed
3100          * @param name the field's name
3101          * @param type the field's type
3102          * @return a method handle which can load values from the field
3103          * @throws NoSuchFieldException if the field does not exist
3104          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3105          * @throws    SecurityException if a security manager is present and it
3106          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3107          * @throws NullPointerException if any argument is null
3108          * @see #findVarHandle(Class, String, Class)
3109          */
3110         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3111             MemberName field = resolveOrFail(REF_getField, refc, name, type);
3112             return getDirectField(REF_getField, refc, field);
3113         }
3114 
3115         /**
3116          * Produces a method handle giving write access to a non-static field.
3117          * The type of the method handle will have a void return type.
3118          * The method handle will take two arguments, the instance containing
3119          * the field, and the value to be stored.
3120          * The second argument will be of the field's value type.
3121          * Access checking is performed immediately on behalf of the lookup class.
3122          * @param refc the class or interface from which the method is accessed
3123          * @param name the field's name
3124          * @param type the field's type
3125          * @return a method handle which can store values into the field
3126          * @throws NoSuchFieldException if the field does not exist
3127          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3128          *                                or {@code final}
3129          * @throws    SecurityException if a security manager is present and it
3130          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3131          * @throws NullPointerException if any argument is null
3132          * @see #findVarHandle(Class, String, Class)
3133          */
3134         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3135             MemberName field = resolveOrFail(REF_putField, refc, name, type);
3136             return getDirectField(REF_putField, refc, field);
3137         }
3138 
3139         /**
3140          * Produces a VarHandle giving access to a non-static field {@code name}
3141          * of type {@code type} declared in a class of type {@code recv}.
3142          * The VarHandle's variable type is {@code type} and it has one
3143          * coordinate type, {@code recv}.
3144          * <p>
3145          * Access checking is performed immediately on behalf of the lookup
3146          * class.
3147          * <p>
3148          * Certain access modes of the returned VarHandle are unsupported under
3149          * the following conditions:
3150          * <ul>
3151          * <li>if the field is declared {@code final}, then the write, atomic
3152          *     update, numeric atomic update, and bitwise atomic update access
3153          *     modes are unsupported.
3154          * <li>if the field type is anything other than {@code byte},
3155          *     {@code short}, {@code char}, {@code int}, {@code long},
3156          *     {@code float}, or {@code double} then numeric atomic update
3157          *     access modes are unsupported.
3158          * <li>if the field type is anything other than {@code boolean},
3159          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3160          *     {@code long} then bitwise atomic update access modes are
3161          *     unsupported.
3162          * </ul>
3163          * <p>
3164          * If the field is declared {@code volatile} then the returned VarHandle
3165          * will override access to the field (effectively ignore the
3166          * {@code volatile} declaration) in accordance to its specified
3167          * access modes.
3168          * <p>
3169          * If the field type is {@code float} or {@code double} then numeric
3170          * and atomic update access modes compare values using their bitwise
3171          * representation (see {@link Float#floatToRawIntBits} and
3172          * {@link Double#doubleToRawLongBits}, respectively).
3173          * @apiNote
3174          * Bitwise comparison of {@code float} values or {@code double} values,
3175          * as performed by the numeric and atomic update access modes, differ
3176          * from the primitive {@code ==} operator and the {@link Float#equals}
3177          * and {@link Double#equals} methods, specifically with respect to
3178          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3179          * Care should be taken when performing a compare and set or a compare
3180          * and exchange operation with such values since the operation may
3181          * unexpectedly fail.
3182          * There are many possible NaN values that are considered to be
3183          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3184          * provided by Java can distinguish between them.  Operation failure can
3185          * occur if the expected or witness value is a NaN value and it is
3186          * transformed (perhaps in a platform specific manner) into another NaN
3187          * value, and thus has a different bitwise representation (see
3188          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3189          * details).
3190          * The values {@code -0.0} and {@code +0.0} have different bitwise
3191          * representations but are considered equal when using the primitive
3192          * {@code ==} operator.  Operation failure can occur if, for example, a
3193          * numeric algorithm computes an expected value to be say {@code -0.0}
3194          * and previously computed the witness value to be say {@code +0.0}.
3195          * @param recv the receiver class, of type {@code R}, that declares the
3196          * non-static field
3197          * @param name the field's name
3198          * @param type the field's type, of type {@code T}
3199          * @return a VarHandle giving access to non-static fields.
3200          * @throws NoSuchFieldException if the field does not exist
3201          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3202          * @throws    SecurityException if a security manager is present and it
3203          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3204          * @throws NullPointerException if any argument is null
3205          * @since 9
3206          */
3207         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3208             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3209             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3210             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3211         }
3212 
3213         /**
3214          * Produces a method handle giving read access to a static field.
3215          * The type of the method handle will have a return type of the field's
3216          * value type.
3217          * The method handle will take no arguments.
3218          * Access checking is performed immediately on behalf of the lookup class.
3219          * <p>
3220          * If the returned method handle is invoked, the field's class will
3221          * be initialized, if it has not already been initialized.
3222          * @param refc the class or interface from which the method is accessed
3223          * @param name the field's name
3224          * @param type the field's type
3225          * @return a method handle which can load values from the field
3226          * @throws NoSuchFieldException if the field does not exist
3227          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3228          * @throws    SecurityException if a security manager is present and it
3229          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3230          * @throws NullPointerException if any argument is null
3231          */
3232         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3233             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3234             return getDirectField(REF_getStatic, refc, field);
3235         }
3236 
3237         /**
3238          * Produces a method handle giving write access to a static field.
3239          * The type of the method handle will have a void return type.
3240          * The method handle will take a single
3241          * argument, of the field's value type, the value to be stored.
3242          * Access checking is performed immediately on behalf of the lookup class.
3243          * <p>
3244          * If the returned method handle is invoked, the field's class will
3245          * be initialized, if it has not already been initialized.
3246          * @param refc the class or interface from which the method is accessed
3247          * @param name the field's name
3248          * @param type the field's type
3249          * @return a method handle which can store values into the field
3250          * @throws NoSuchFieldException if the field does not exist
3251          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3252          *                                or is {@code final}
3253          * @throws    SecurityException if a security manager is present and it
3254          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3255          * @throws NullPointerException if any argument is null
3256          */
3257         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3258             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3259             return getDirectField(REF_putStatic, refc, field);
3260         }
3261 
3262         /**
3263          * Produces a VarHandle giving access to a static field {@code name} of
3264          * type {@code type} declared in a class of type {@code decl}.
3265          * The VarHandle's variable type is {@code type} and it has no
3266          * coordinate types.
3267          * <p>
3268          * Access checking is performed immediately on behalf of the lookup
3269          * class.
3270          * <p>
3271          * If the returned VarHandle is operated on, the declaring class will be
3272          * initialized, if it has not already been initialized.
3273          * <p>
3274          * Certain access modes of the returned VarHandle are unsupported under
3275          * the following conditions:
3276          * <ul>
3277          * <li>if the field is declared {@code final}, then the write, atomic
3278          *     update, numeric atomic update, and bitwise atomic update access
3279          *     modes are unsupported.
3280          * <li>if the field type is anything other than {@code byte},
3281          *     {@code short}, {@code char}, {@code int}, {@code long},
3282          *     {@code float}, or {@code double}, then numeric atomic update
3283          *     access modes are unsupported.
3284          * <li>if the field type is anything other than {@code boolean},
3285          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3286          *     {@code long} then bitwise atomic update access modes are
3287          *     unsupported.
3288          * </ul>
3289          * <p>
3290          * If the field is declared {@code volatile} then the returned VarHandle
3291          * will override access to the field (effectively ignore the
3292          * {@code volatile} declaration) in accordance to its specified
3293          * access modes.
3294          * <p>
3295          * If the field type is {@code float} or {@code double} then numeric
3296          * and atomic update access modes compare values using their bitwise
3297          * representation (see {@link Float#floatToRawIntBits} and
3298          * {@link Double#doubleToRawLongBits}, respectively).
3299          * @apiNote
3300          * Bitwise comparison of {@code float} values or {@code double} values,
3301          * as performed by the numeric and atomic update access modes, differ
3302          * from the primitive {@code ==} operator and the {@link Float#equals}
3303          * and {@link Double#equals} methods, specifically with respect to
3304          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3305          * Care should be taken when performing a compare and set or a compare
3306          * and exchange operation with such values since the operation may
3307          * unexpectedly fail.
3308          * There are many possible NaN values that are considered to be
3309          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3310          * provided by Java can distinguish between them.  Operation failure can
3311          * occur if the expected or witness value is a NaN value and it is
3312          * transformed (perhaps in a platform specific manner) into another NaN
3313          * value, and thus has a different bitwise representation (see
3314          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3315          * details).
3316          * The values {@code -0.0} and {@code +0.0} have different bitwise
3317          * representations but are considered equal when using the primitive
3318          * {@code ==} operator.  Operation failure can occur if, for example, a
3319          * numeric algorithm computes an expected value to be say {@code -0.0}
3320          * and previously computed the witness value to be say {@code +0.0}.
3321          * @param decl the class that declares the static field
3322          * @param name the field's name
3323          * @param type the field's type, of type {@code T}
3324          * @return a VarHandle giving access to a static field
3325          * @throws NoSuchFieldException if the field does not exist
3326          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3327          * @throws    SecurityException if a security manager is present and it
3328          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3329          * @throws NullPointerException if any argument is null
3330          * @since 9
3331          */
3332         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3333             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3334             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3335             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3336         }
3337 
3338         /**
3339          * Produces an early-bound method handle for a non-static method.
3340          * The receiver must have a supertype {@code defc} in which a method
3341          * of the given name and type is accessible to the lookup class.
3342          * The method and all its argument types must be accessible to the lookup object.
3343          * The type of the method handle will be that of the method,
3344          * without any insertion of an additional receiver parameter.
3345          * The given receiver will be bound into the method handle,
3346          * so that every call to the method handle will invoke the
3347          * requested method on the given receiver.
3348          * <p>
3349          * The returned method handle will have
3350          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3351          * the method's variable arity modifier bit ({@code 0x0080}) is set
3352          * <em>and</em> the trailing array argument is not the only argument.
3353          * (If the trailing array argument is the only argument,
3354          * the given receiver value will be bound to it.)
3355          * <p>
3356          * This is almost equivalent to the following code, with some differences noted below:
3357          * {@snippet lang="java" :
3358 import static java.lang.invoke.MethodHandles.*;
3359 import static java.lang.invoke.MethodType.*;
3360 ...
3361 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3362 MethodHandle mh1 = mh0.bindTo(receiver);
3363 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3364 return mh1;
3365          * }
3366          * where {@code defc} is either {@code receiver.getClass()} or a super
3367          * type of that class, in which the requested method is accessible
3368          * to the lookup class.
3369          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3370          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3371          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3372          * the receiver is restricted by {@code findVirtual} to the lookup class.)
3373          * @param receiver the object from which the method is accessed
3374          * @param name the name of the method
3375          * @param type the type of the method, with the receiver argument omitted
3376          * @return the desired method handle
3377          * @throws NoSuchMethodException if the method does not exist
3378          * @throws IllegalAccessException if access checking fails
3379          *                                or if the method's variable arity modifier bit
3380          *                                is set and {@code asVarargsCollector} fails
3381          * @throws    SecurityException if a security manager is present and it
3382          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3383          * @throws NullPointerException if any argument is null
3384          * @see MethodHandle#bindTo
3385          * @see #findVirtual
3386          */
3387         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3388             Class<? extends Object> refc = receiver.getClass(); // may get NPE
3389             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3390             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3391             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3392                 throw new IllegalAccessException("The restricted defining class " +
3393                                                  mh.type().leadingReferenceParameter().getName() +
3394                                                  " is not assignable from receiver class " +
3395                                                  receiver.getClass().getName());
3396             }
3397             return mh.bindArgumentL(0, receiver).setVarargs(method);
3398         }
3399 
3400         /**
3401          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3402          * to <i>m</i>, if the lookup class has permission.
3403          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3404          * If <i>m</i> is virtual, overriding is respected on every call.
3405          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3406          * The type of the method handle will be that of the method,
3407          * with the receiver type prepended (but only if it is non-static).
3408          * If the method's {@code accessible} flag is not set,
3409          * access checking is performed immediately on behalf of the lookup class.
3410          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3411          * <p>
3412          * The returned method handle will have
3413          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3414          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3415          * <p>
3416          * If <i>m</i> is static, and
3417          * if the returned method handle is invoked, the method's class will
3418          * be initialized, if it has not already been initialized.
3419          * @param m the reflected method
3420          * @return a method handle which can invoke the reflected method
3421          * @throws IllegalAccessException if access checking fails
3422          *                                or if the method's variable arity modifier bit
3423          *                                is set and {@code asVarargsCollector} fails
3424          * @throws NullPointerException if the argument is null
3425          */
3426         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3427             if (m.getDeclaringClass() == MethodHandle.class) {
3428                 MethodHandle mh = unreflectForMH(m);
3429                 if (mh != null)  return mh;
3430             }
3431             if (m.getDeclaringClass() == VarHandle.class) {
3432                 MethodHandle mh = unreflectForVH(m);
3433                 if (mh != null)  return mh;
3434             }
3435             MemberName method = new MemberName(m);
3436             byte refKind = method.getReferenceKind();
3437             if (refKind == REF_invokeSpecial)
3438                 refKind = REF_invokeVirtual;
3439             assert(method.isMethod());
3440             @SuppressWarnings("deprecation")
3441             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3442             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3443         }
3444         private MethodHandle unreflectForMH(Method m) {
3445             // these names require special lookups because they throw UnsupportedOperationException
3446             if (MemberName.isMethodHandleInvokeName(m.getName()))
3447                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3448             return null;
3449         }
3450         private MethodHandle unreflectForVH(Method m) {
3451             // these names require special lookups because they throw UnsupportedOperationException
3452             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3453                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3454             return null;
3455         }
3456 
3457         /**
3458          * Produces a method handle for a reflected method.
3459          * It will bypass checks for overriding methods on the receiver,
3460          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3461          * instruction from within the explicitly specified {@code specialCaller}.
3462          * The type of the method handle will be that of the method,
3463          * with a suitably restricted receiver type prepended.
3464          * (The receiver type will be {@code specialCaller} or a subtype.)
3465          * If the method's {@code accessible} flag is not set,
3466          * access checking is performed immediately on behalf of the lookup class,
3467          * as if {@code invokespecial} instruction were being linked.
3468          * <p>
3469          * Before method resolution,
3470          * if the explicitly specified caller class is not identical with the
3471          * lookup class, or if this lookup object does not have
3472          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3473          * privileges, the access fails.
3474          * <p>
3475          * The returned method handle will have
3476          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3477          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3478          * @param m the reflected method
3479          * @param specialCaller the class nominally calling the method
3480          * @return a method handle which can invoke the reflected method
3481          * @throws IllegalAccessException if access checking fails,
3482          *                                or if the method is {@code static},
3483          *                                or if the method's variable arity modifier bit
3484          *                                is set and {@code asVarargsCollector} fails
3485          * @throws NullPointerException if any argument is null
3486          */
3487         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3488             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3489             Lookup specialLookup = this.in(specialCaller);
3490             MemberName method = new MemberName(m, true);
3491             assert(method.isMethod());
3492             // ignore m.isAccessible:  this is a new kind of access
3493             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3494         }
3495 
3496         /**
3497          * Produces a method handle for a reflected constructor.
3498          * The type of the method handle will be that of the constructor,
3499          * with the return type changed to the declaring class.
3500          * The method handle will perform a {@code newInstance} operation,
3501          * creating a new instance of the constructor's class on the
3502          * arguments passed to the method handle.
3503          * <p>
3504          * If the constructor's {@code accessible} flag is not set,
3505          * access checking is performed immediately on behalf of the lookup class.
3506          * <p>
3507          * The returned method handle will have
3508          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3509          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3510          * <p>
3511          * If the returned method handle is invoked, the constructor's class will
3512          * be initialized, if it has not already been initialized.
3513          * @param c the reflected constructor
3514          * @return a method handle which can invoke the reflected constructor
3515          * @throws IllegalAccessException if access checking fails
3516          *                                or if the method's variable arity modifier bit
3517          *                                is set and {@code asVarargsCollector} fails
3518          * @throws NullPointerException if the argument is null
3519          */
3520         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3521             MemberName ctor = new MemberName(c);
3522             assert(ctor.isObjectConstructor());
3523             @SuppressWarnings("deprecation")
3524             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3525             return lookup.getDirectConstructorNoSecurityManager(c.getDeclaringClass(), ctor);
3526         }
3527 
3528         /*
3529          * Produces a method handle that is capable of creating instances of the given class
3530          * and instantiated by the given constructor.  No security manager check.
3531          *
3532          * This method should only be used by ReflectionFactory::newConstructorForSerialization.
3533          */
3534         /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException {
3535             MemberName ctor = new MemberName(c);
3536             assert(ctor.isObjectConstructor() && constructorInSuperclass(decl, c));
3537             checkAccess(REF_newInvokeSpecial, decl, ctor);
3538             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
3539             return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor);
3540         }
3541 
3542         private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) {
3543             if (decl == ctor.getDeclaringClass())
3544                 return true;
3545 
3546             Class<?> cl = decl;
3547             while ((cl = cl.getSuperclass()) != null) {
3548                 if (cl == ctor.getDeclaringClass()) {
3549                     return true;
3550                 }
3551             }
3552             return false;
3553         }
3554 
3555         /**
3556          * Produces a method handle giving read access to a reflected field.
3557          * The type of the method handle will have a return type of the field's
3558          * value type.
3559          * If the field is {@code static}, the method handle will take no arguments.
3560          * Otherwise, its single argument will be the instance containing
3561          * the field.
3562          * If the {@code Field} object's {@code accessible} flag is not set,
3563          * access checking is performed immediately on behalf of the lookup class.
3564          * <p>
3565          * If the field is static, and
3566          * if the returned method handle is invoked, the field's class will
3567          * be initialized, if it has not already been initialized.
3568          * @param f the reflected field
3569          * @return a method handle which can load values from the reflected field
3570          * @throws IllegalAccessException if access checking fails
3571          * @throws NullPointerException if the argument is null
3572          */
3573         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3574             return unreflectField(f, false);
3575         }
3576 
3577         /**
3578          * Produces a method handle giving write access to a reflected field.
3579          * The type of the method handle will have a void return type.
3580          * If the field is {@code static}, the method handle will take a single
3581          * argument, of the field's value type, the value to be stored.
3582          * Otherwise, the two arguments will be the instance containing
3583          * the field, and the value to be stored.
3584          * If the {@code Field} object's {@code accessible} flag is not set,
3585          * access checking is performed immediately on behalf of the lookup class.
3586          * <p>
3587          * If the field is {@code final}, write access will not be
3588          * allowed and access checking will fail, except under certain
3589          * narrow circumstances documented for {@link Field#set Field.set}.
3590          * A method handle is returned only if a corresponding call to
3591          * the {@code Field} object's {@code set} method could return
3592          * normally.  In particular, fields which are both {@code static}
3593          * and {@code final} may never be set.
3594          * <p>
3595          * If the field is {@code static}, and
3596          * if the returned method handle is invoked, the field's class will
3597          * be initialized, if it has not already been initialized.
3598          * @param f the reflected field
3599          * @return a method handle which can store values into the reflected field
3600          * @throws IllegalAccessException if access checking fails,
3601          *         or if the field is {@code final} and write access
3602          *         is not enabled on the {@code Field} object
3603          * @throws NullPointerException if the argument is null
3604          */
3605         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3606             return unreflectField(f, true);
3607         }
3608 
3609         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3610             MemberName field = new MemberName(f, isSetter);
3611             if (isSetter && field.isFinal()) {
3612                 if (field.isTrustedFinalField()) {
3613                     String msg = field.isStatic() ? "static final field has no write access"
3614                                                   : "final field has no write access";
3615                     throw field.makeAccessException(msg, this);
3616                 }
3617             }
3618             assert(isSetter
3619                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3620                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3621             @SuppressWarnings("deprecation")
3622             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3623             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3624         }
3625 
3626         /**
3627          * Produces a VarHandle giving access to a reflected field {@code f}
3628          * of type {@code T} declared in a class of type {@code R}.
3629          * The VarHandle's variable type is {@code T}.
3630          * If the field is non-static the VarHandle has one coordinate type,
3631          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3632          * coordinate types.
3633          * <p>
3634          * Access checking is performed immediately on behalf of the lookup
3635          * class, regardless of the value of the field's {@code accessible}
3636          * flag.
3637          * <p>
3638          * If the field is static, and if the returned VarHandle is operated
3639          * on, the field's declaring class will be initialized, if it has not
3640          * already been initialized.
3641          * <p>
3642          * Certain access modes of the returned VarHandle are unsupported under
3643          * the following conditions:
3644          * <ul>
3645          * <li>if the field is declared {@code final}, then the write, atomic
3646          *     update, numeric atomic update, and bitwise atomic update access
3647          *     modes are unsupported.
3648          * <li>if the field type is anything other than {@code byte},
3649          *     {@code short}, {@code char}, {@code int}, {@code long},
3650          *     {@code float}, or {@code double} then numeric atomic update
3651          *     access modes are unsupported.
3652          * <li>if the field type is anything other than {@code boolean},
3653          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3654          *     {@code long} then bitwise atomic update access modes are
3655          *     unsupported.
3656          * </ul>
3657          * <p>
3658          * If the field is declared {@code volatile} then the returned VarHandle
3659          * will override access to the field (effectively ignore the
3660          * {@code volatile} declaration) in accordance to its specified
3661          * access modes.
3662          * <p>
3663          * If the field type is {@code float} or {@code double} then numeric
3664          * and atomic update access modes compare values using their bitwise
3665          * representation (see {@link Float#floatToRawIntBits} and
3666          * {@link Double#doubleToRawLongBits}, respectively).
3667          * @apiNote
3668          * Bitwise comparison of {@code float} values or {@code double} values,
3669          * as performed by the numeric and atomic update access modes, differ
3670          * from the primitive {@code ==} operator and the {@link Float#equals}
3671          * and {@link Double#equals} methods, specifically with respect to
3672          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3673          * Care should be taken when performing a compare and set or a compare
3674          * and exchange operation with such values since the operation may
3675          * unexpectedly fail.
3676          * There are many possible NaN values that are considered to be
3677          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3678          * provided by Java can distinguish between them.  Operation failure can
3679          * occur if the expected or witness value is a NaN value and it is
3680          * transformed (perhaps in a platform specific manner) into another NaN
3681          * value, and thus has a different bitwise representation (see
3682          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3683          * details).
3684          * The values {@code -0.0} and {@code +0.0} have different bitwise
3685          * representations but are considered equal when using the primitive
3686          * {@code ==} operator.  Operation failure can occur if, for example, a
3687          * numeric algorithm computes an expected value to be say {@code -0.0}
3688          * and previously computed the witness value to be say {@code +0.0}.
3689          * @param f the reflected field, with a field of type {@code T}, and
3690          * a declaring class of type {@code R}
3691          * @return a VarHandle giving access to non-static fields or a static
3692          * field
3693          * @throws IllegalAccessException if access checking fails
3694          * @throws NullPointerException if the argument is null
3695          * @since 9
3696          */
3697         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3698             MemberName getField = new MemberName(f, false);
3699             MemberName putField = new MemberName(f, true);
3700             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
3701                                                       f.getDeclaringClass(), getField, putField);
3702         }
3703 
3704         /**
3705          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3706          * created by this lookup object or a similar one.
3707          * Security and access checks are performed to ensure that this lookup object
3708          * is capable of reproducing the target method handle.
3709          * This means that the cracking may fail if target is a direct method handle
3710          * but was created by an unrelated lookup object.
3711          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3712          * and was created by a lookup object for a different class.
3713          * @param target a direct method handle to crack into symbolic reference components
3714          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3715          * @throws    SecurityException if a security manager is present and it
3716          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3717          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3718          * @throws    NullPointerException if the target is {@code null}
3719          * @see MethodHandleInfo
3720          * @since 1.8
3721          */
3722         public MethodHandleInfo revealDirect(MethodHandle target) {
3723             if (!target.isCrackable()) {
3724                 throw newIllegalArgumentException("not a direct method handle");
3725             }
3726             MemberName member = target.internalMemberName();
3727             Class<?> defc = member.getDeclaringClass();
3728             byte refKind = member.getReferenceKind();
3729             assert(MethodHandleNatives.refKindIsValid(refKind));
3730             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3731                 // Devirtualized method invocation is usually formally virtual.
3732                 // To avoid creating extra MemberName objects for this common case,
3733                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3734                 refKind = REF_invokeVirtual;
3735             if (refKind == REF_invokeVirtual && defc.isInterface())
3736                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3737                 refKind = REF_invokeInterface;
3738             // Check SM permissions and member access before cracking.
3739             try {
3740                 checkAccess(refKind, defc, member);
3741                 checkSecurityManager(defc, member);
3742             } catch (IllegalAccessException ex) {
3743                 throw new IllegalArgumentException(ex);
3744             }
3745             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3746                 Class<?> callerClass = target.internalCallerClass();
3747                 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3748                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3749             }
3750             // Produce the handle to the results.
3751             return new InfoFromMemberName(this, member, refKind);
3752         }
3753 
3754         /// Helper methods, all package-private.
3755 
3756         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3757             checkSymbolicClass(refc);  // do this before attempting to resolve
3758             Objects.requireNonNull(name);
3759             Objects.requireNonNull(type);
3760             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3761                                             NoSuchFieldException.class);
3762         }
3763 
3764         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3765             checkSymbolicClass(refc);  // do this before attempting to resolve
3766             Objects.requireNonNull(type);
3767             checkMethodName(refKind, name);  // implicit null-check of name
3768             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3769                                             NoSuchMethodException.class);
3770         }
3771 
3772         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3773             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3774             Objects.requireNonNull(member.getName());
3775             Objects.requireNonNull(member.getType());
3776             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3777                                             ReflectiveOperationException.class);
3778         }
3779 
3780         MemberName resolveOrNull(byte refKind, MemberName member) {
3781             // do this before attempting to resolve
3782             if (!isClassAccessible(member.getDeclaringClass())) {
3783                 return null;
3784             }
3785             Objects.requireNonNull(member.getName());
3786             Objects.requireNonNull(member.getType());
3787             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3788         }
3789 
3790         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3791             // do this before attempting to resolve
3792             if (!isClassAccessible(refc)) {
3793                 return null;
3794             }
3795             Objects.requireNonNull(type);
3796             // implicit null-check of name
3797             if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3798                 return null;
3799             }
3800 
3801             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3802         }
3803 
3804         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3805             if (!isClassAccessible(refc)) {
3806                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3807             }
3808         }
3809 
3810         boolean isClassAccessible(Class<?> refc) {
3811             Objects.requireNonNull(refc);
3812             Class<?> caller = lookupClassOrNull();
3813             Class<?> type = refc;
3814             while (type.isArray()) {
3815                 type = type.getComponentType();
3816             }
3817             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3818         }
3819 
3820         /** Check name for an illegal leading "&lt;" character. */
3821         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3822             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
3823                 throw new NoSuchMethodException("illegal method name: " + name + " ref kind " + refKind);
3824         }
3825 
3826         /**
3827          * Find my trustable caller class if m is a caller sensitive method.
3828          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3829          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3830          */
3831         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3832             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3833                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3834                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3835             }
3836             return this;
3837         }
3838 
3839         /**
3840          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3841          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3842          *
3843          * @deprecated This method was originally designed to test {@code PRIVATE} access
3844          * that implies full privilege access but {@code MODULE} access has since become
3845          * independent of {@code PRIVATE} access.  It is recommended to call
3846          * {@link #hasFullPrivilegeAccess()} instead.
3847          * @since 9
3848          */
3849         @Deprecated(since="14")
3850         public boolean hasPrivateAccess() {
3851             return hasFullPrivilegeAccess();
3852         }
3853 
3854         /**
3855          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3856          * i.e. {@code PRIVATE} and {@code MODULE} access.
3857          * A {@code Lookup} object must have full privilege access in order to
3858          * access all members that are allowed to the
3859          * {@linkplain #lookupClass() lookup class}.
3860          *
3861          * @return {@code true} if this lookup has full privilege access.
3862          * @since 14
3863          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3864          */
3865         public boolean hasFullPrivilegeAccess() {
3866             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3867         }
3868 
3869         /**
3870          * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a>
3871          * for ensureInitialized, findClass or accessClass.
3872          */
3873         void checkSecurityManager(Class<?> refc) {
3874             if (allowedModes == TRUSTED)  return;
3875 
3876             @SuppressWarnings("removal")
3877             SecurityManager smgr = System.getSecurityManager();
3878             if (smgr == null)  return;
3879 
3880             // Step 1:
3881             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3882             if (!fullPrivilegeLookup ||
3883                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3884                 ReflectUtil.checkPackageAccess(refc);
3885             }
3886 
3887             // Step 2b:
3888             if (!fullPrivilegeLookup) {
3889                 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
3890             }
3891         }
3892 
3893         /**
3894          * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
3895          * Determines a trustable caller class to compare with refc, the symbolic reference class.
3896          * If this lookup object has full privilege access except original access,
3897          * then the caller class is the lookupClass.
3898          *
3899          * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)}
3900          * from the same module skips the security permission check.
3901          */
3902         void checkSecurityManager(Class<?> refc, MemberName m) {
3903             Objects.requireNonNull(refc);
3904             Objects.requireNonNull(m);
3905 
3906             if (allowedModes == TRUSTED)  return;
3907 
3908             @SuppressWarnings("removal")
3909             SecurityManager smgr = System.getSecurityManager();
3910             if (smgr == null)  return;
3911 
3912             // Step 1:
3913             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3914             if (!fullPrivilegeLookup ||
3915                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3916                 ReflectUtil.checkPackageAccess(refc);
3917             }
3918 
3919             // Step 2a:
3920             if (m.isPublic()) return;
3921             if (!fullPrivilegeLookup) {
3922                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3923             }
3924 
3925             // Step 3:
3926             Class<?> defc = m.getDeclaringClass();
3927             if (!fullPrivilegeLookup && defc != refc) {
3928                 ReflectUtil.checkPackageAccess(defc);
3929             }
3930         }
3931 
3932         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3933             boolean wantStatic = (refKind == REF_invokeStatic);
3934             String message;
3935             if (m.isObjectConstructor())
3936                 message = "expected a method, not a constructor";
3937             else if (!m.isMethod())
3938                 message = "expected a method";
3939             else if (wantStatic != m.isStatic())
3940                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3941             else
3942                 { checkAccess(refKind, refc, m); return; }
3943             throw m.makeAccessException(message, this);
3944         }
3945 
3946         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3947             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3948             String message;
3949             if (wantStatic != m.isStatic())
3950                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3951             else
3952                 { checkAccess(refKind, refc, m); return; }
3953             throw m.makeAccessException(message, this);
3954         }
3955 
3956         private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) {
3957             return Modifier.isProtected(m.getModifiers()) &&
3958                     refKind == REF_invokeVirtual &&
3959                     m.getDeclaringClass() == Object.class &&
3960                     m.getName().equals("clone") &&
3961                     refc.isArray();
3962         }
3963 
3964         /** Check public/protected/private bits on the symbolic reference class and its member. */
3965         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3966             assert(m.referenceKindIsConsistentWith(refKind) &&
3967                    MethodHandleNatives.refKindIsValid(refKind) &&
3968                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3969             int allowedModes = this.allowedModes;
3970             if (allowedModes == TRUSTED)  return;
3971             int mods = m.getModifiers();
3972             if (isArrayClone(refKind, refc, m)) {
3973                 // The JVM does this hack also.
3974                 // (See ClassVerifier::verify_invoke_instructions
3975                 // and LinkResolver::check_method_accessability.)
3976                 // Because the JVM does not allow separate methods on array types,
3977                 // there is no separate method for int[].clone.
3978                 // All arrays simply inherit Object.clone.
3979                 // But for access checking logic, we make Object.clone
3980                 // (normally protected) appear to be public.
3981                 // Later on, when the DirectMethodHandle is created,
3982                 // its leading argument will be restricted to the
3983                 // requested array type.
3984                 // N.B. The return type is not adjusted, because
3985                 // that is *not* the bytecode behavior.
3986                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3987             }
3988             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3989                 // cannot "new" a protected ctor in a different package
3990                 mods ^= Modifier.PROTECTED;
3991             }
3992             if (Modifier.isFinal(mods) &&
3993                     MethodHandleNatives.refKindIsSetter(refKind))
3994                 throw m.makeAccessException("unexpected set of a final field", this);
3995             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3996             if ((requestedModes & allowedModes) != 0) {
3997                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3998                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3999                     return;
4000             } else {
4001                 // Protected members can also be checked as if they were package-private.
4002                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
4003                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
4004                     return;
4005             }
4006             throw m.makeAccessException(accessFailedMessage(refc, m), this);
4007         }
4008 
4009         String accessFailedMessage(Class<?> refc, MemberName m) {
4010             Class<?> defc = m.getDeclaringClass();
4011             int mods = m.getModifiers();
4012             // check the class first:
4013             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
4014                                (defc == refc ||
4015                                 Modifier.isPublic(refc.getModifiers())));
4016             if (!classOK && (allowedModes & PACKAGE) != 0) {
4017                 // ignore previous lookup class to check if default package access
4018                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
4019                            (defc == refc ||
4020                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
4021             }
4022             if (!classOK)
4023                 return "class is not public";
4024             if (Modifier.isPublic(mods))
4025                 return "access to public member failed";  // (how?, module not readable?)
4026             if (Modifier.isPrivate(mods))
4027                 return "member is private";
4028             if (Modifier.isProtected(mods))
4029                 return "member is protected";
4030             return "member is private to package";
4031         }
4032 
4033         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
4034             int allowedModes = this.allowedModes;
4035             if (allowedModes == TRUSTED)  return;
4036             if ((lookupModes() & PRIVATE) == 0
4037                 || (specialCaller != lookupClass()
4038                        // ensure non-abstract methods in superinterfaces can be special-invoked
4039                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
4040                 throw new MemberName(specialCaller).
4041                     makeAccessException("no private access for invokespecial", this);
4042         }
4043 
4044         private boolean restrictProtectedReceiver(MemberName method) {
4045             // The accessing class only has the right to use a protected member
4046             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
4047             if (!method.isProtected() || method.isStatic()
4048                 || allowedModes == TRUSTED
4049                 || method.getDeclaringClass() == lookupClass()
4050                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
4051                 return false;
4052             return true;
4053         }
4054         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
4055             assert(!method.isStatic());
4056             // receiver type of mh is too wide; narrow to caller
4057             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
4058                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
4059             }
4060             MethodType rawType = mh.type();
4061             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
4062             MethodType narrowType = rawType.changeParameterType(0, caller);
4063             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
4064             assert(mh.viewAsTypeChecks(narrowType, true));
4065             return mh.copyWith(narrowType, mh.form);
4066         }
4067 
4068         /** Check access and get the requested method. */
4069         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4070             final boolean doRestrict    = true;
4071             final boolean checkSecurity = true;
4072             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4073         }
4074         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
4075         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4076             final boolean doRestrict    = false;
4077             final boolean checkSecurity = true;
4078             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
4079         }
4080         /** Check access and get the requested method, eliding security manager checks. */
4081         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4082             final boolean doRestrict    = true;
4083             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4084             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4085         }
4086         /** Common code for all methods; do not call directly except from immediately above. */
4087         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
4088                                                    boolean checkSecurity,
4089                                                    boolean doRestrict,
4090                                                    Lookup boundCaller) throws IllegalAccessException {
4091             checkMethod(refKind, refc, method);
4092             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4093             if (checkSecurity)
4094                 checkSecurityManager(refc, method);
4095             assert(!method.isMethodHandleInvoke());
4096             if (refKind == REF_invokeSpecial &&
4097                 refc != lookupClass() &&
4098                 !refc.isInterface() && !lookupClass().isInterface() &&
4099                 refc != lookupClass().getSuperclass() &&
4100                 refc.isAssignableFrom(lookupClass())) {
4101                 assert(!method.getName().equals(ConstantDescs.INIT_NAME));  // not this code path
4102 
4103                 // Per JVMS 6.5, desc. of invokespecial instruction:
4104                 // If the method is in a superclass of the LC,
4105                 // and if our original search was above LC.super,
4106                 // repeat the search (symbolic lookup) from LC.super
4107                 // and continue with the direct superclass of that class,
4108                 // and so forth, until a match is found or no further superclasses exist.
4109                 // FIXME: MemberName.resolve should handle this instead.
4110                 Class<?> refcAsSuper = lookupClass();
4111                 MemberName m2;
4112                 do {
4113                     refcAsSuper = refcAsSuper.getSuperclass();
4114                     m2 = new MemberName(refcAsSuper,
4115                                         method.getName(),
4116                                         method.getMethodType(),
4117                                         REF_invokeSpecial);
4118                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
4119                 } while (m2 == null &&         // no method is found yet
4120                          refc != refcAsSuper); // search up to refc
4121                 if (m2 == null)  throw new InternalError(method.toString());
4122                 method = m2;
4123                 refc = refcAsSuper;
4124                 // redo basic checks
4125                 checkMethod(refKind, refc, method);
4126             }
4127             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
4128             MethodHandle mh = dmh;
4129             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
4130             if ((doRestrict && refKind == REF_invokeSpecial) ||
4131                     (MethodHandleNatives.refKindHasReceiver(refKind) &&
4132                             restrictProtectedReceiver(method) &&
4133                             // All arrays simply inherit the protected Object.clone method.
4134                             // The leading argument is already restricted to the requested
4135                             // array type (not the lookup class).
4136                             !isArrayClone(refKind, refc, method))) {
4137                 mh = restrictReceiver(method, dmh, lookupClass());
4138             }
4139             mh = maybeBindCaller(method, mh, boundCaller);
4140             mh = mh.setVarargs(method);
4141             return mh;
4142         }
4143         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
4144                                              throws IllegalAccessException {
4145             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
4146                 return mh;
4147 
4148             // boundCaller must have full privilege access.
4149             // It should have been checked by findBoundCallerLookup. Safe to check this again.
4150             if ((boundCaller.lookupModes() & ORIGINAL) == 0)
4151                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
4152 
4153             assert boundCaller.hasFullPrivilegeAccess();
4154 
4155             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
4156             // Note: caller will apply varargs after this step happens.
4157             return cbmh;
4158         }
4159 
4160         /** Check access and get the requested field. */
4161         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4162             final boolean checkSecurity = true;
4163             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4164         }
4165         /** Check access and get the requested field, eliding security manager checks. */
4166         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4167             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4168             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4169         }
4170         /** Common code for all fields; do not call directly except from immediately above. */
4171         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
4172                                                   boolean checkSecurity) throws IllegalAccessException {
4173             checkField(refKind, refc, field);
4174             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4175             if (checkSecurity)
4176                 checkSecurityManager(refc, field);
4177             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
4178             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
4179                                     restrictProtectedReceiver(field));
4180             if (doRestrict)
4181                 return restrictReceiver(field, dmh, lookupClass());
4182             return dmh;
4183         }
4184         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
4185                                             Class<?> refc, MemberName getField, MemberName putField)
4186                 throws IllegalAccessException {
4187             final boolean checkSecurity = true;
4188             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4189         }
4190         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
4191                                                              Class<?> refc, MemberName getField, MemberName putField)
4192                 throws IllegalAccessException {
4193             final boolean checkSecurity = false;
4194             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4195         }
4196         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
4197                                                   Class<?> refc, MemberName getField, MemberName putField,
4198                                                   boolean checkSecurity) throws IllegalAccessException {
4199             assert getField.isStatic() == putField.isStatic();
4200             assert getField.isGetter() && putField.isSetter();
4201             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
4202             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
4203 
4204             checkField(getRefKind, refc, getField);
4205             if (checkSecurity)
4206                 checkSecurityManager(refc, getField);
4207 
4208             if (!putField.isFinal()) {
4209                 // A VarHandle does not support updates to final fields, any
4210                 // such VarHandle to a final field will be read-only and
4211                 // therefore the following write-based accessibility checks are
4212                 // only required for non-final fields
4213                 checkField(putRefKind, refc, putField);
4214                 if (checkSecurity)
4215                     checkSecurityManager(refc, putField);
4216             }
4217 
4218             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
4219                                   restrictProtectedReceiver(getField));
4220             if (doRestrict) {
4221                 assert !getField.isStatic();
4222                 // receiver type of VarHandle is too wide; narrow to caller
4223                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
4224                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4225                 }
4226                 refc = lookupClass();
4227             }
4228             return VarHandles.makeFieldHandle(getField, refc,
4229                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4230         }
4231         /** Check access and get the requested constructor. */
4232         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4233             final boolean checkSecurity = true;
4234             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4235         }
4236         /** Check access and get the requested constructor, eliding security manager checks. */
4237         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4238             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4239             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4240         }
4241         /** Common code for all constructors; do not call directly except from immediately above. */
4242         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4243                                                   boolean checkSecurity) throws IllegalAccessException {
4244             assert(ctor.isObjectConstructor());
4245             checkAccess(REF_newInvokeSpecial, refc, ctor);
4246             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4247             if (checkSecurity)
4248                 checkSecurityManager(refc, ctor);
4249             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4250             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4251         }
4252 
4253         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4254          */
4255         /*non-public*/
4256         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4257                 throws ReflectiveOperationException {
4258             if (!(type instanceof Class || type instanceof MethodType))
4259                 throw new InternalError("unresolved MemberName");
4260             MemberName member = new MemberName(refKind, defc, name, type);
4261             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4262             if (mh != null) {
4263                 checkSymbolicClass(defc);
4264                 return mh;
4265             }
4266             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
4267                 // Treat MethodHandle.invoke and invokeExact specially.
4268                 mh = findVirtualForMH(member.getName(), member.getMethodType());
4269                 if (mh != null) {
4270                     return mh;
4271                 }
4272             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4273                 // Treat signature-polymorphic methods on VarHandle specially.
4274                 mh = findVirtualForVH(member.getName(), member.getMethodType());
4275                 if (mh != null) {
4276                     return mh;
4277                 }
4278             }
4279             MemberName resolved = resolveOrFail(refKind, member);
4280             mh = getDirectMethodForConstant(refKind, defc, resolved);
4281             if (mh instanceof DirectMethodHandle dmh
4282                     && canBeCached(refKind, defc, resolved)) {
4283                 MemberName key = mh.internalMemberName();
4284                 if (key != null) {
4285                     key = key.asNormalOriginal();
4286                 }
4287                 if (member.equals(key)) {  // better safe than sorry
4288                     LOOKASIDE_TABLE.put(key, dmh);
4289                 }
4290             }
4291             return mh;
4292         }
4293         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4294             if (refKind == REF_invokeSpecial) {
4295                 return false;
4296             }
4297             if (!Modifier.isPublic(defc.getModifiers()) ||
4298                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4299                     !member.isPublic() ||
4300                     member.isCallerSensitive()) {
4301                 return false;
4302             }
4303             ClassLoader loader = defc.getClassLoader();
4304             if (loader != null) {
4305                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4306                 boolean found = false;
4307                 while (sysl != null) {
4308                     if (loader == sysl) { found = true; break; }
4309                     sysl = sysl.getParent();
4310                 }
4311                 if (!found) {
4312                     return false;
4313                 }
4314             }
4315             try {
4316                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4317                     new MemberName(refKind, defc, member.getName(), member.getType()));
4318                 if (resolved2 == null) {
4319                     return false;
4320                 }
4321                 checkSecurityManager(defc, resolved2);
4322             } catch (SecurityException ex) {
4323                 return false;
4324             }
4325             return true;
4326         }
4327         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4328                 throws ReflectiveOperationException {
4329             if (MethodHandleNatives.refKindIsField(refKind)) {
4330                 return getDirectFieldNoSecurityManager(refKind, defc, member);
4331             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4332                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
4333             } else if (refKind == REF_newInvokeSpecial) {
4334                 return getDirectConstructorNoSecurityManager(defc, member);
4335             }
4336             // oops
4337             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4338         }
4339 
4340         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4341     }
4342 
4343     /**
4344      * Produces a method handle constructing arrays of a desired type,
4345      * as if by the {@code anewarray} bytecode.
4346      * The return type of the method handle will be the array type.
4347      * The type of its sole argument will be {@code int}, which specifies the size of the array.
4348      *
4349      * <p> If the returned method handle is invoked with a negative
4350      * array size, a {@code NegativeArraySizeException} will be thrown.
4351      *
4352      * @param arrayClass an array type
4353      * @return a method handle which can create arrays of the given type
4354      * @throws NullPointerException if the argument is {@code null}
4355      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4356      * @see java.lang.reflect.Array#newInstance(Class, int)
4357      * @jvms 6.5 {@code anewarray} Instruction
4358      * @since 9
4359      */
4360     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4361         if (!arrayClass.isArray()) {
4362             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4363         }
4364         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4365                 bindTo(arrayClass.getComponentType());
4366         return ani.asType(ani.type().changeReturnType(arrayClass));
4367     }
4368 
4369     /**
4370      * Produces a method handle returning the length of an array,
4371      * as if by the {@code arraylength} bytecode.
4372      * The type of the method handle will have {@code int} as return type,
4373      * and its sole argument will be the array type.
4374      *
4375      * <p> If the returned method handle is invoked with a {@code null}
4376      * array reference, a {@code NullPointerException} will be thrown.
4377      *
4378      * @param arrayClass an array type
4379      * @return a method handle which can retrieve the length of an array of the given array type
4380      * @throws NullPointerException if the argument is {@code null}
4381      * @throws IllegalArgumentException if arrayClass is not an array type
4382      * @jvms 6.5 {@code arraylength} Instruction
4383      * @since 9
4384      */
4385     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4386         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4387     }
4388 
4389     /**
4390      * Produces a method handle giving read access to elements of an array,
4391      * as if by the {@code aaload} bytecode.
4392      * The type of the method handle will have a return type of the array's
4393      * element type.  Its first argument will be the array type,
4394      * and the second will be {@code int}.
4395      *
4396      * <p> When the returned method handle is invoked,
4397      * the array reference and array index are checked.
4398      * A {@code NullPointerException} will be thrown if the array reference
4399      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4400      * thrown if the index is negative or if it is greater than or equal to
4401      * the length of the array.
4402      *
4403      * @param arrayClass an array type
4404      * @return a method handle which can load values from the given array type
4405      * @throws NullPointerException if the argument is null
4406      * @throws  IllegalArgumentException if arrayClass is not an array type
4407      * @jvms 6.5 {@code aaload} Instruction
4408      */
4409     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4410         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4411     }
4412 
4413     /**
4414      * Produces a method handle giving write access to elements of an array,
4415      * as if by the {@code astore} bytecode.
4416      * The type of the method handle will have a void return type.
4417      * Its last argument will be the array's element type.
4418      * The first and second arguments will be the array type and int.
4419      *
4420      * <p> When the returned method handle is invoked,
4421      * the array reference and array index are checked.
4422      * A {@code NullPointerException} will be thrown if the array reference
4423      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4424      * thrown if the index is negative or if it is greater than or equal to
4425      * the length of the array.
4426      *
4427      * @param arrayClass the class of an array
4428      * @return a method handle which can store values into the array type
4429      * @throws NullPointerException if the argument is null
4430      * @throws IllegalArgumentException if arrayClass is not an array type
4431      * @jvms 6.5 {@code aastore} Instruction
4432      */
4433     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4434         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4435     }
4436 
4437     /**
4438      * Produces a VarHandle giving access to elements of an array of type
4439      * {@code arrayClass}.  The VarHandle's variable type is the component type
4440      * of {@code arrayClass} and the list of coordinate types is
4441      * {@code (arrayClass, int)}, where the {@code int} coordinate type
4442      * corresponds to an argument that is an index into an array.
4443      * <p>
4444      * Certain access modes of the returned VarHandle are unsupported under
4445      * the following conditions:
4446      * <ul>
4447      * <li>if the component type is anything other than {@code byte},
4448      *     {@code short}, {@code char}, {@code int}, {@code long},
4449      *     {@code float}, or {@code double} then numeric atomic update access
4450      *     modes are unsupported.
4451      * <li>if the component type is anything other than {@code boolean},
4452      *     {@code byte}, {@code short}, {@code char}, {@code int} or
4453      *     {@code long} then bitwise atomic update access modes are
4454      *     unsupported.
4455      * </ul>
4456      * <p>
4457      * If the component type is {@code float} or {@code double} then numeric
4458      * and atomic update access modes compare values using their bitwise
4459      * representation (see {@link Float#floatToRawIntBits} and
4460      * {@link Double#doubleToRawLongBits}, respectively).
4461      *
4462      * <p> When the returned {@code VarHandle} is invoked,
4463      * the array reference and array index are checked.
4464      * A {@code NullPointerException} will be thrown if the array reference
4465      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4466      * thrown if the index is negative or if it is greater than or equal to
4467      * the length of the array.
4468      *
4469      * @apiNote
4470      * Bitwise comparison of {@code float} values or {@code double} values,
4471      * as performed by the numeric and atomic update access modes, differ
4472      * from the primitive {@code ==} operator and the {@link Float#equals}
4473      * and {@link Double#equals} methods, specifically with respect to
4474      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4475      * Care should be taken when performing a compare and set or a compare
4476      * and exchange operation with such values since the operation may
4477      * unexpectedly fail.
4478      * There are many possible NaN values that are considered to be
4479      * {@code NaN} in Java, although no IEEE 754 floating-point operation
4480      * provided by Java can distinguish between them.  Operation failure can
4481      * occur if the expected or witness value is a NaN value and it is
4482      * transformed (perhaps in a platform specific manner) into another NaN
4483      * value, and thus has a different bitwise representation (see
4484      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4485      * details).
4486      * The values {@code -0.0} and {@code +0.0} have different bitwise
4487      * representations but are considered equal when using the primitive
4488      * {@code ==} operator.  Operation failure can occur if, for example, a
4489      * numeric algorithm computes an expected value to be say {@code -0.0}
4490      * and previously computed the witness value to be say {@code +0.0}.
4491      * @param arrayClass the class of an array, of type {@code T[]}
4492      * @return a VarHandle giving access to elements of an array
4493      * @throws NullPointerException if the arrayClass is null
4494      * @throws IllegalArgumentException if arrayClass is not an array type
4495      * @since 9
4496      */
4497     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4498         return VarHandles.makeArrayElementHandle(arrayClass);
4499     }
4500 
4501     /**
4502      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4503      * viewed as if it were a different primitive array type, such as
4504      * {@code int[]} or {@code long[]}.
4505      * The VarHandle's variable type is the component type of
4506      * {@code viewArrayClass} and the list of coordinate types is
4507      * {@code (byte[], int)}, where the {@code int} coordinate type
4508      * corresponds to an argument that is an index into a {@code byte[]} array.
4509      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4510      * array, composing bytes to or from a value of the component type of
4511      * {@code viewArrayClass} according to the given endianness.
4512      * <p>
4513      * The supported component types (variables types) are {@code short},
4514      * {@code char}, {@code int}, {@code long}, {@code float} and
4515      * {@code double}.
4516      * <p>
4517      * Access of bytes at a given index will result in an
4518      * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4519      * or greater than the {@code byte[]} array length minus the size (in bytes)
4520      * of {@code T}.
4521      * <p>
4522      * Access of bytes at an index may be aligned or misaligned for {@code T},
4523      * with respect to the underlying memory address, {@code A} say, associated
4524      * with the array and index.
4525      * If access is misaligned then access for anything other than the
4526      * {@code get} and {@code set} access modes will result in an
4527      * {@code IllegalStateException}.  In such cases atomic access is only
4528      * guaranteed with respect to the largest power of two that divides the GCD
4529      * of {@code A} and the size (in bytes) of {@code T}.
4530      * If access is aligned then following access modes are supported and are
4531      * guaranteed to support atomic access:
4532      * <ul>
4533      * <li>read write access modes for all {@code T}, with the exception of
4534      *     access modes {@code get} and {@code set} for {@code long} and
4535      *     {@code double} on 32-bit platforms.
4536      * <li>atomic update access modes for {@code int}, {@code long},
4537      *     {@code float} or {@code double}.
4538      *     (Future major platform releases of the JDK may support additional
4539      *     types for certain currently unsupported access modes.)
4540      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4541      *     (Future major platform releases of the JDK may support additional
4542      *     numeric types for certain currently unsupported access modes.)
4543      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4544      *     (Future major platform releases of the JDK may support additional
4545      *     numeric types for certain currently unsupported access modes.)
4546      * </ul>
4547      * <p>
4548      * Misaligned access, and therefore atomicity guarantees, may be determined
4549      * for {@code byte[]} arrays without operating on a specific array.  Given
4550      * an {@code index}, {@code T} and its corresponding boxed type,
4551      * {@code T_BOX}, misalignment may be determined as follows:
4552      * <pre>{@code
4553      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4554      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
4555      *     alignmentOffset(0, sizeOfT);
4556      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
4557      * boolean isMisaligned = misalignedAtIndex != 0;
4558      * }</pre>
4559      * <p>
4560      * If the variable type is {@code float} or {@code double} then atomic
4561      * update access modes compare values using their bitwise representation
4562      * (see {@link Float#floatToRawIntBits} and
4563      * {@link Double#doubleToRawLongBits}, respectively).
4564      * @param viewArrayClass the view array class, with a component type of
4565      * type {@code T}
4566      * @param byteOrder the endianness of the view array elements, as
4567      * stored in the underlying {@code byte} array
4568      * @return a VarHandle giving access to elements of a {@code byte[]} array
4569      * viewed as if elements corresponding to the components type of the view
4570      * array class
4571      * @throws NullPointerException if viewArrayClass or byteOrder is null
4572      * @throws IllegalArgumentException if viewArrayClass is not an array type
4573      * @throws UnsupportedOperationException if the component type of
4574      * viewArrayClass is not supported as a variable type
4575      * @since 9
4576      */
4577     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4578                                      ByteOrder byteOrder) throws IllegalArgumentException {
4579         Objects.requireNonNull(byteOrder);
4580         return VarHandles.byteArrayViewHandle(viewArrayClass,
4581                                               byteOrder == ByteOrder.BIG_ENDIAN);
4582     }
4583 
4584     /**
4585      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4586      * viewed as if it were an array of elements of a different primitive
4587      * component type to that of {@code byte}, such as {@code int[]} or
4588      * {@code long[]}.
4589      * The VarHandle's variable type is the component type of
4590      * {@code viewArrayClass} and the list of coordinate types is
4591      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4592      * corresponds to an argument that is an index into a {@code byte[]} array.
4593      * The returned VarHandle accesses bytes at an index in a
4594      * {@code ByteBuffer}, composing bytes to or from a value of the component
4595      * type of {@code viewArrayClass} according to the given endianness.
4596      * <p>
4597      * The supported component types (variables types) are {@code short},
4598      * {@code char}, {@code int}, {@code long}, {@code float} and
4599      * {@code double}.
4600      * <p>
4601      * Access will result in a {@code ReadOnlyBufferException} for anything
4602      * other than the read access modes if the {@code ByteBuffer} is read-only.
4603      * <p>
4604      * Access of bytes at a given index will result in an
4605      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4606      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4607      * {@code T}.
4608      * <p>
4609      * Access of bytes at an index may be aligned or misaligned for {@code T},
4610      * with respect to the underlying memory address, {@code A} say, associated
4611      * with the {@code ByteBuffer} and index.
4612      * If access is misaligned then access for anything other than the
4613      * {@code get} and {@code set} access modes will result in an
4614      * {@code IllegalStateException}.  In such cases atomic access is only
4615      * guaranteed with respect to the largest power of two that divides the GCD
4616      * of {@code A} and the size (in bytes) of {@code T}.
4617      * If access is aligned then following access modes are supported and are
4618      * guaranteed to support atomic access:
4619      * <ul>
4620      * <li>read write access modes for all {@code T}, with the exception of
4621      *     access modes {@code get} and {@code set} for {@code long} and
4622      *     {@code double} on 32-bit platforms.
4623      * <li>atomic update access modes for {@code int}, {@code long},
4624      *     {@code float} or {@code double}.
4625      *     (Future major platform releases of the JDK may support additional
4626      *     types for certain currently unsupported access modes.)
4627      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4628      *     (Future major platform releases of the JDK may support additional
4629      *     numeric types for certain currently unsupported access modes.)
4630      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4631      *     (Future major platform releases of the JDK may support additional
4632      *     numeric types for certain currently unsupported access modes.)
4633      * </ul>
4634      * <p>
4635      * Misaligned access, and therefore atomicity guarantees, may be determined
4636      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4637      * {@code index}, {@code T} and its corresponding boxed type,
4638      * {@code T_BOX}, as follows:
4639      * <pre>{@code
4640      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4641      * ByteBuffer bb = ...
4642      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4643      * boolean isMisaligned = misalignedAtIndex != 0;
4644      * }</pre>
4645      * <p>
4646      * If the variable type is {@code float} or {@code double} then atomic
4647      * update access modes compare values using their bitwise representation
4648      * (see {@link Float#floatToRawIntBits} and
4649      * {@link Double#doubleToRawLongBits}, respectively).
4650      * @param viewArrayClass the view array class, with a component type of
4651      * type {@code T}
4652      * @param byteOrder the endianness of the view array elements, as
4653      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4654      * endianness of a {@code ByteBuffer})
4655      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4656      * viewed as if elements corresponding to the components type of the view
4657      * array class
4658      * @throws NullPointerException if viewArrayClass or byteOrder is null
4659      * @throws IllegalArgumentException if viewArrayClass is not an array type
4660      * @throws UnsupportedOperationException if the component type of
4661      * viewArrayClass is not supported as a variable type
4662      * @since 9
4663      */
4664     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4665                                       ByteOrder byteOrder) throws IllegalArgumentException {
4666         Objects.requireNonNull(byteOrder);
4667         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4668                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4669     }
4670 
4671 
4672     /// method handle invocation (reflective style)
4673 
4674     /**
4675      * Produces a method handle which will invoke any method handle of the
4676      * given {@code type}, with a given number of trailing arguments replaced by
4677      * a single trailing {@code Object[]} array.
4678      * The resulting invoker will be a method handle with the following
4679      * arguments:
4680      * <ul>
4681      * <li>a single {@code MethodHandle} target
4682      * <li>zero or more leading values (counted by {@code leadingArgCount})
4683      * <li>an {@code Object[]} array containing trailing arguments
4684      * </ul>
4685      * <p>
4686      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4687      * the indicated {@code type}.
4688      * That is, if the target is exactly of the given {@code type}, it will behave
4689      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4690      * is used to convert the target to the required {@code type}.
4691      * <p>
4692      * The type of the returned invoker will not be the given {@code type}, but rather
4693      * will have all parameters except the first {@code leadingArgCount}
4694      * replaced by a single array of type {@code Object[]}, which will be
4695      * the final parameter.
4696      * <p>
4697      * Before invoking its target, the invoker will spread the final array, apply
4698      * reference casts as necessary, and unbox and widen primitive arguments.
4699      * If, when the invoker is called, the supplied array argument does
4700      * not have the correct number of elements, the invoker will throw
4701      * an {@link IllegalArgumentException} instead of invoking the target.
4702      * <p>
4703      * This method is equivalent to the following code (though it may be more efficient):
4704      * {@snippet lang="java" :
4705 MethodHandle invoker = MethodHandles.invoker(type);
4706 int spreadArgCount = type.parameterCount() - leadingArgCount;
4707 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4708 return invoker;
4709      * }
4710      * This method throws no reflective or security exceptions.
4711      * @param type the desired target type
4712      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4713      * @return a method handle suitable for invoking any method handle of the given type
4714      * @throws NullPointerException if {@code type} is null
4715      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4716      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4717      *                  or if the resulting method handle's type would have
4718      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4719      */
4720     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4721         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4722             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4723         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4724         return type.invokers().spreadInvoker(leadingArgCount);
4725     }
4726 
4727     /**
4728      * Produces a special <em>invoker method handle</em> which can be used to
4729      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4730      * The resulting invoker will have a type which is
4731      * exactly equal to the desired type, except that it will accept
4732      * an additional leading argument of type {@code MethodHandle}.
4733      * <p>
4734      * This method is equivalent to the following code (though it may be more efficient):
4735      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4736      *
4737      * <p style="font-size:smaller;">
4738      * <em>Discussion:</em>
4739      * Invoker method handles can be useful when working with variable method handles
4740      * of unknown types.
4741      * For example, to emulate an {@code invokeExact} call to a variable method
4742      * handle {@code M}, extract its type {@code T},
4743      * look up the invoker method {@code X} for {@code T},
4744      * and call the invoker method, as {@code X.invoke(T, A...)}.
4745      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4746      * is unknown.)
4747      * If spreading, collecting, or other argument transformations are required,
4748      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4749      * method handle values, as long as they are compatible with the type of {@code X}.
4750      * <p style="font-size:smaller;">
4751      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4752      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4753      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4754      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4755      * <p>
4756      * This method throws no reflective or security exceptions.
4757      * @param type the desired target type
4758      * @return a method handle suitable for invoking any method handle of the given type
4759      * @throws IllegalArgumentException if the resulting method handle's type would have
4760      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4761      */
4762     public static MethodHandle exactInvoker(MethodType type) {
4763         return type.invokers().exactInvoker();
4764     }
4765 
4766     /**
4767      * Produces a special <em>invoker method handle</em> which can be used to
4768      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4769      * The resulting invoker will have a type which is
4770      * exactly equal to the desired type, except that it will accept
4771      * an additional leading argument of type {@code MethodHandle}.
4772      * <p>
4773      * Before invoking its target, if the target differs from the expected type,
4774      * the invoker will apply reference casts as
4775      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4776      * Similarly, the return value will be converted as necessary.
4777      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4778      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4779      * <p>
4780      * This method is equivalent to the following code (though it may be more efficient):
4781      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4782      * <p style="font-size:smaller;">
4783      * <em>Discussion:</em>
4784      * A {@linkplain MethodType#genericMethodType general method type} is one which
4785      * mentions only {@code Object} arguments and return values.
4786      * An invoker for such a type is capable of calling any method handle
4787      * of the same arity as the general type.
4788      * <p style="font-size:smaller;">
4789      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4790      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4791      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4792      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4793      * <p>
4794      * This method throws no reflective or security exceptions.
4795      * @param type the desired target type
4796      * @return a method handle suitable for invoking any method handle convertible to the given type
4797      * @throws IllegalArgumentException if the resulting method handle's type would have
4798      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4799      */
4800     public static MethodHandle invoker(MethodType type) {
4801         return type.invokers().genericInvoker();
4802     }
4803 
4804     /**
4805      * Produces a special <em>invoker method handle</em> which can be used to
4806      * invoke a signature-polymorphic access mode method on any VarHandle whose
4807      * associated access mode type is compatible with the given type.
4808      * The resulting invoker will have a type which is exactly equal to the
4809      * desired given type, except that it will accept an additional leading
4810      * argument of type {@code VarHandle}.
4811      *
4812      * @param accessMode the VarHandle access mode
4813      * @param type the desired target type
4814      * @return a method handle suitable for invoking an access mode method of
4815      *         any VarHandle whose access mode type is of the given type.
4816      * @since 9
4817      */
4818     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4819         return type.invokers().varHandleMethodExactInvoker(accessMode);
4820     }
4821 
4822     /**
4823      * Produces a special <em>invoker method handle</em> which can be used to
4824      * invoke a signature-polymorphic access mode method on any VarHandle whose
4825      * associated access mode type is compatible with the given type.
4826      * The resulting invoker will have a type which is exactly equal to the
4827      * desired given type, except that it will accept an additional leading
4828      * argument of type {@code VarHandle}.
4829      * <p>
4830      * Before invoking its target, if the access mode type differs from the
4831      * desired given type, the invoker will apply reference casts as necessary
4832      * and box, unbox, or widen primitive values, as if by
4833      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4834      * converted as necessary.
4835      * <p>
4836      * This method is equivalent to the following code (though it may be more
4837      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4838      *
4839      * @param accessMode the VarHandle access mode
4840      * @param type the desired target type
4841      * @return a method handle suitable for invoking an access mode method of
4842      *         any VarHandle whose access mode type is convertible to the given
4843      *         type.
4844      * @since 9
4845      */
4846     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4847         return type.invokers().varHandleMethodInvoker(accessMode);
4848     }
4849 
4850     /*non-public*/
4851     static MethodHandle basicInvoker(MethodType type) {
4852         return type.invokers().basicInvoker();
4853     }
4854 
4855      /// method handle modification (creation from other method handles)
4856 
4857     /**
4858      * Produces a method handle which adapts the type of the
4859      * given method handle to a new type by pairwise argument and return type conversion.
4860      * The original type and new type must have the same number of arguments.
4861      * The resulting method handle is guaranteed to report a type
4862      * which is equal to the desired new type.
4863      * <p>
4864      * If the original type and new type are equal, returns target.
4865      * <p>
4866      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4867      * and some additional conversions are also applied if those conversions fail.
4868      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4869      * if possible, before or instead of any conversions done by {@code asType}:
4870      * <ul>
4871      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4872      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4873      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4874      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4875      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4876      *     (This treatment follows the usage of the bytecode verifier.)
4877      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4878      *     <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}),
4879      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4880      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4881      *     then a Java casting conversion (JLS {@jls 5.5}) is applied.
4882      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4883      *     widening and/or narrowing.)
4884      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4885      *     conversion will be applied at runtime, possibly followed
4886      *     by a Java casting conversion (JLS {@jls 5.5}) on the primitive value,
4887      *     possibly followed by a conversion from byte to boolean by testing
4888      *     the low-order bit.
4889      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4890      *     and if the reference is null at runtime, a zero value is introduced.
4891      * </ul>
4892      * @param target the method handle to invoke after arguments are retyped
4893      * @param newType the expected type of the new method handle
4894      * @return a method handle which delegates to the target after performing
4895      *           any necessary argument conversions, and arranges for any
4896      *           necessary return value conversions
4897      * @throws NullPointerException if either argument is null
4898      * @throws WrongMethodTypeException if the conversion cannot be made
4899      * @see MethodHandle#asType
4900      */
4901     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4902         explicitCastArgumentsChecks(target, newType);
4903         // use the asTypeCache when possible:
4904         MethodType oldType = target.type();
4905         if (oldType == newType)  return target;
4906         if (oldType.explicitCastEquivalentToAsType(newType)) {
4907             return target.asFixedArity().asType(newType);
4908         }
4909         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4910     }
4911 
4912     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4913         if (target.type().parameterCount() != newType.parameterCount()) {
4914             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4915         }
4916     }
4917 
4918     /**
4919      * Produces a method handle which adapts the calling sequence of the
4920      * given method handle to a new type, by reordering the arguments.
4921      * The resulting method handle is guaranteed to report a type
4922      * which is equal to the desired new type.
4923      * <p>
4924      * The given array controls the reordering.
4925      * Call {@code #I} the number of incoming parameters (the value
4926      * {@code newType.parameterCount()}, and call {@code #O} the number
4927      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4928      * Then the length of the reordering array must be {@code #O},
4929      * and each element must be a non-negative number less than {@code #I}.
4930      * For every {@code N} less than {@code #O}, the {@code N}-th
4931      * outgoing argument will be taken from the {@code I}-th incoming
4932      * argument, where {@code I} is {@code reorder[N]}.
4933      * <p>
4934      * No argument or return value conversions are applied.
4935      * The type of each incoming argument, as determined by {@code newType},
4936      * must be identical to the type of the corresponding outgoing parameter
4937      * or parameters in the target method handle.
4938      * The return type of {@code newType} must be identical to the return
4939      * type of the original target.
4940      * <p>
4941      * The reordering array need not specify an actual permutation.
4942      * An incoming argument will be duplicated if its index appears
4943      * more than once in the array, and an incoming argument will be dropped
4944      * if its index does not appear in the array.
4945      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4946      * incoming arguments which are not mentioned in the reordering array
4947      * may be of any type, as determined only by {@code newType}.
4948      * {@snippet lang="java" :
4949 import static java.lang.invoke.MethodHandles.*;
4950 import static java.lang.invoke.MethodType.*;
4951 ...
4952 MethodType intfn1 = methodType(int.class, int.class);
4953 MethodType intfn2 = methodType(int.class, int.class, int.class);
4954 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4955 assert(sub.type().equals(intfn2));
4956 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4957 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4958 assert((int)rsub.invokeExact(1, 100) == 99);
4959 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4960 assert(add.type().equals(intfn2));
4961 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4962 assert(twice.type().equals(intfn1));
4963 assert((int)twice.invokeExact(21) == 42);
4964      * }
4965      * <p>
4966      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4967      * variable-arity method handle}, even if the original target method handle was.
4968      * @param target the method handle to invoke after arguments are reordered
4969      * @param newType the expected type of the new method handle
4970      * @param reorder an index array which controls the reordering
4971      * @return a method handle which delegates to the target after it
4972      *           drops unused arguments and moves and/or duplicates the other arguments
4973      * @throws NullPointerException if any argument is null
4974      * @throws IllegalArgumentException if the index array length is not equal to
4975      *                  the arity of the target, or if any index array element
4976      *                  not a valid index for a parameter of {@code newType},
4977      *                  or if two corresponding parameter types in
4978      *                  {@code target.type()} and {@code newType} are not identical,
4979      */
4980     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4981         reorder = reorder.clone();  // get a private copy
4982         MethodType oldType = target.type();
4983         permuteArgumentChecks(reorder, newType, oldType);
4984         // first detect dropped arguments and handle them separately
4985         int[] originalReorder = reorder;
4986         BoundMethodHandle result = target.rebind();
4987         LambdaForm form = result.form;
4988         int newArity = newType.parameterCount();
4989         // Normalize the reordering into a real permutation,
4990         // by removing duplicates and adding dropped elements.
4991         // This somewhat improves lambda form caching, as well
4992         // as simplifying the transform by breaking it up into steps.
4993         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4994             if (ddIdx > 0) {
4995                 // We found a duplicated entry at reorder[ddIdx].
4996                 // Example:  (x,y,z)->asList(x,y,z)
4997                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4998                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4999                 // The starred element corresponds to the argument
5000                 // deleted by the dupArgumentForm transform.
5001                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
5002                 boolean killFirst = false;
5003                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
5004                     // Set killFirst if the dup is larger than an intervening position.
5005                     // This will remove at least one inversion from the permutation.
5006                     if (dupVal > val) killFirst = true;
5007                 }
5008                 if (!killFirst) {
5009                     srcPos = dstPos;
5010                     dstPos = ddIdx;
5011                 }
5012                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
5013                 assert (reorder[srcPos] == reorder[dstPos]);
5014                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
5015                 // contract the reordering by removing the element at dstPos
5016                 int tailPos = dstPos + 1;
5017                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
5018                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
5019             } else {
5020                 int dropVal = ~ddIdx, insPos = 0;
5021                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
5022                     // Find first element of reorder larger than dropVal.
5023                     // This is where we will insert the dropVal.
5024                     insPos += 1;
5025                 }
5026                 Class<?> ptype = newType.parameterType(dropVal);
5027                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
5028                 oldType = oldType.insertParameterTypes(insPos, ptype);
5029                 // expand the reordering by inserting an element at insPos
5030                 int tailPos = insPos + 1;
5031                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
5032                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
5033                 reorder[insPos] = dropVal;
5034             }
5035             assert (permuteArgumentChecks(reorder, newType, oldType));
5036         }
5037         assert (reorder.length == newArity);  // a perfect permutation
5038         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
5039         form = form.editor().permuteArgumentsForm(1, reorder);
5040         if (newType == result.type() && form == result.internalForm())
5041             return result;
5042         return result.copyWith(newType, form);
5043     }
5044 
5045     /**
5046      * Return an indication of any duplicate or omission in reorder.
5047      * If the reorder contains a duplicate entry, return the index of the second occurrence.
5048      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
5049      * Otherwise, return zero.
5050      * If an element not in [0..newArity-1] is encountered, return reorder.length.
5051      */
5052     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
5053         final int BIT_LIMIT = 63;  // max number of bits in bit mask
5054         if (newArity < BIT_LIMIT) {
5055             long mask = 0;
5056             for (int i = 0; i < reorder.length; i++) {
5057                 int arg = reorder[i];
5058                 if (arg >= newArity) {
5059                     return reorder.length;
5060                 }
5061                 long bit = 1L << arg;
5062                 if ((mask & bit) != 0) {
5063                     return i;  // >0 indicates a dup
5064                 }
5065                 mask |= bit;
5066             }
5067             if (mask == (1L << newArity) - 1) {
5068                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
5069                 return 0;
5070             }
5071             // find first zero
5072             long zeroBit = Long.lowestOneBit(~mask);
5073             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
5074             assert(zeroPos <= newArity);
5075             if (zeroPos == newArity) {
5076                 return 0;
5077             }
5078             return ~zeroPos;
5079         } else {
5080             // same algorithm, different bit set
5081             BitSet mask = new BitSet(newArity);
5082             for (int i = 0; i < reorder.length; i++) {
5083                 int arg = reorder[i];
5084                 if (arg >= newArity) {
5085                     return reorder.length;
5086                 }
5087                 if (mask.get(arg)) {
5088                     return i;  // >0 indicates a dup
5089                 }
5090                 mask.set(arg);
5091             }
5092             int zeroPos = mask.nextClearBit(0);
5093             assert(zeroPos <= newArity);
5094             if (zeroPos == newArity) {
5095                 return 0;
5096             }
5097             return ~zeroPos;
5098         }
5099     }
5100 
5101     static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
5102         if (newType.returnType() != oldType.returnType())
5103             throw newIllegalArgumentException("return types do not match",
5104                     oldType, newType);
5105         if (reorder.length != oldType.parameterCount())
5106             throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
5107                     oldType, Arrays.toString(reorder));
5108 
5109         int limit = newType.parameterCount();
5110         for (int j = 0; j < reorder.length; j++) {
5111             int i = reorder[j];
5112             if (i < 0 || i >= limit) {
5113                 throw newIllegalArgumentException("index is out of bounds for new type",
5114                         i, newType);
5115             }
5116             Class<?> src = newType.parameterType(i);
5117             Class<?> dst = oldType.parameterType(j);
5118             if (src != dst)
5119                 throw newIllegalArgumentException("parameter types do not match after reorder",
5120                         oldType, newType);
5121         }
5122         return true;
5123     }
5124 
5125     /**
5126      * Produces a method handle of the requested return type which returns the given
5127      * constant value every time it is invoked.
5128      * <p>
5129      * Before the method handle is returned, the passed-in value is converted to the requested type.
5130      * If the requested type is primitive, widening primitive conversions are attempted,
5131      * else reference conversions are attempted.
5132      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5133      * @param type the return type of the desired method handle
5134      * @param value the value to return
5135      * @return a method handle of the given return type and no arguments, which always returns the given value
5136      * @throws NullPointerException if the {@code type} argument is null
5137      * @throws ClassCastException if the value cannot be converted to the required return type
5138      * @throws IllegalArgumentException if the given type is {@code void.class}
5139      */
5140     public static MethodHandle constant(Class<?> type, Object value) {
5141         if (type.isPrimitive()) {
5142             if (type == void.class)
5143                 throw newIllegalArgumentException("void type");
5144             Wrapper w = Wrapper.forPrimitiveType(type);
5145             value = w.convert(value, type);
5146             if (w.zero().equals(value))
5147                 return zero(w, type);
5148             return insertArguments(identity(type), 0, value);
5149         } else {
5150             if (value == null)
5151                 return zero(Wrapper.OBJECT, type);
5152             return identity(type).bindTo(value);
5153         }
5154     }
5155 
5156     /**
5157      * Produces a method handle which returns its sole argument when invoked.
5158      * @param type the type of the sole parameter and return value of the desired method handle
5159      * @return a unary method handle which accepts and returns the given type
5160      * @throws NullPointerException if the argument is null
5161      * @throws IllegalArgumentException if the given type is {@code void.class}
5162      */
5163     public static MethodHandle identity(Class<?> type) {
5164         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5165         int pos = btw.ordinal();
5166         MethodHandle ident = IDENTITY_MHS[pos];
5167         if (ident == null) {
5168             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5169         }
5170         if (ident.type().returnType() == type)
5171             return ident;
5172         // something like identity(Foo.class); do not bother to intern these
5173         assert (btw == Wrapper.OBJECT);
5174         return makeIdentity(type);
5175     }
5176 
5177     /**
5178      * Produces a constant method handle of the requested return type which
5179      * returns the default value for that type every time it is invoked.
5180      * The resulting constant method handle will have no side effects.
5181      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5182      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5183      * since {@code explicitCastArguments} converts {@code null} to default values.
5184      * @param type the expected return type of the desired method handle
5185      * @return a constant method handle that takes no arguments
5186      *         and returns the default value of the given type (or void, if the type is void)
5187      * @throws NullPointerException if the argument is null
5188      * @see MethodHandles#constant
5189      * @see MethodHandles#empty
5190      * @see MethodHandles#explicitCastArguments
5191      * @since 9
5192      */
5193     public static MethodHandle zero(Class<?> type) {
5194         Objects.requireNonNull(type);
5195         // TODO: implicitly constructible value class
5196         if (type.isPrimitive()) {
5197             return zero(Wrapper.forPrimitiveType(type), type);
5198         } else {
5199             return zero(Wrapper.OBJECT, type);
5200         }
5201     }
5202 
5203     private static MethodHandle identityOrVoid(Class<?> type) {
5204         return type == void.class ? zero(type) : identity(type);
5205     }
5206 
5207     /**
5208      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5209      * and returns a suitable default depending on the return type.
5210      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
5211      * <p>The returned method handle is equivalent to
5212      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5213      *
5214      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5215      * {@code guardWithTest(pred, target, empty(target.type())}.
5216      * @param type the type of the desired method handle
5217      * @return a constant method handle of the given type, which returns a default value of the given return type
5218      * @throws NullPointerException if the argument is null
5219      * @see MethodHandles#zero
5220      * @see MethodHandles#constant
5221      * @since 9
5222      */
5223     public static  MethodHandle empty(MethodType type) {
5224         Objects.requireNonNull(type);
5225         return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes());
5226     }
5227 
5228     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5229     private static MethodHandle makeIdentity(Class<?> ptype) {
5230         MethodType mtype = MethodType.methodType(ptype, ptype);
5231         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5232         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5233     }
5234 
5235     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5236         int pos = btw.ordinal();
5237         MethodHandle zero = ZERO_MHS[pos];
5238         if (zero == null) {
5239             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5240         }
5241         if (zero.type().returnType() == rtype)
5242             return zero;
5243         assert(btw == Wrapper.OBJECT);
5244         return makeZero(rtype);
5245     }
5246     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5247     private static MethodHandle makeZero(Class<?> rtype) {
5248         MethodType mtype = methodType(rtype);
5249         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5250         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
5251     }
5252 
5253     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
5254         // Simulate a CAS, to avoid racy duplication of results.
5255         MethodHandle prev = cache[pos];
5256         if (prev != null) return prev;
5257         return cache[pos] = value;
5258     }
5259 
5260     /**
5261      * Provides a target method handle with one or more <em>bound arguments</em>
5262      * in advance of the method handle's invocation.
5263      * The formal parameters to the target corresponding to the bound
5264      * arguments are called <em>bound parameters</em>.
5265      * Returns a new method handle which saves away the bound arguments.
5266      * When it is invoked, it receives arguments for any non-bound parameters,
5267      * binds the saved arguments to their corresponding parameters,
5268      * and calls the original target.
5269      * <p>
5270      * The type of the new method handle will drop the types for the bound
5271      * parameters from the original target type, since the new method handle
5272      * will no longer require those arguments to be supplied by its callers.
5273      * <p>
5274      * Each given argument object must match the corresponding bound parameter type.
5275      * If a bound parameter type is a primitive, the argument object
5276      * must be a wrapper, and will be unboxed to produce the primitive value.
5277      * <p>
5278      * The {@code pos} argument selects which parameters are to be bound.
5279      * It may range between zero and <i>N-L</i> (inclusively),
5280      * where <i>N</i> is the arity of the target method handle
5281      * and <i>L</i> is the length of the values array.
5282      * <p>
5283      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5284      * variable-arity method handle}, even if the original target method handle was.
5285      * @param target the method handle to invoke after the argument is inserted
5286      * @param pos where to insert the argument (zero for the first)
5287      * @param values the series of arguments to insert
5288      * @return a method handle which inserts an additional argument,
5289      *         before calling the original method handle
5290      * @throws NullPointerException if the target or the {@code values} array is null
5291      * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than
5292      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
5293      *         is the length of the values array.
5294      * @throws ClassCastException if an argument does not match the corresponding bound parameter
5295      *         type.
5296      * @see MethodHandle#bindTo
5297      */
5298     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
5299         int insCount = values.length;
5300         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
5301         if (insCount == 0)  return target;
5302         BoundMethodHandle result = target.rebind();
5303         for (int i = 0; i < insCount; i++) {
5304             Object value = values[i];
5305             Class<?> ptype = ptypes[pos+i];
5306             if (ptype.isPrimitive()) {
5307                 result = insertArgumentPrimitive(result, pos, ptype, value);
5308             } else {
5309                 value = ptype.cast(value);  // throw CCE if needed
5310                 result = result.bindArgumentL(pos, value);
5311             }
5312         }
5313         return result;
5314     }
5315 
5316     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5317                                                              Class<?> ptype, Object value) {
5318         Wrapper w = Wrapper.forPrimitiveType(ptype);
5319         // perform unboxing and/or primitive conversion
5320         value = w.convert(value, ptype);
5321         return switch (w) {
5322             case INT    -> result.bindArgumentI(pos, (int) value);
5323             case LONG   -> result.bindArgumentJ(pos, (long) value);
5324             case FLOAT  -> result.bindArgumentF(pos, (float) value);
5325             case DOUBLE -> result.bindArgumentD(pos, (double) value);
5326             default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5327         };
5328     }
5329 
5330     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5331         MethodType oldType = target.type();
5332         int outargs = oldType.parameterCount();
5333         int inargs  = outargs - insCount;
5334         if (inargs < 0)
5335             throw newIllegalArgumentException("too many values to insert");
5336         if (pos < 0 || pos > inargs)
5337             throw newIllegalArgumentException("no argument type to append");
5338         return oldType.ptypes();
5339     }
5340 
5341     /**
5342      * Produces a method handle which will discard some dummy arguments
5343      * before calling some other specified <i>target</i> method handle.
5344      * The type of the new method handle will be the same as the target's type,
5345      * except it will also include the dummy argument types,
5346      * at some given position.
5347      * <p>
5348      * The {@code pos} argument may range between zero and <i>N</i>,
5349      * where <i>N</i> is the arity of the target.
5350      * If {@code pos} is zero, the dummy arguments will precede
5351      * the target's real arguments; if {@code pos} is <i>N</i>
5352      * they will come after.
5353      * <p>
5354      * <b>Example:</b>
5355      * {@snippet lang="java" :
5356 import static java.lang.invoke.MethodHandles.*;
5357 import static java.lang.invoke.MethodType.*;
5358 ...
5359 MethodHandle cat = lookup().findVirtual(String.class,
5360   "concat", methodType(String.class, String.class));
5361 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5362 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5363 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5364 assertEquals(bigType, d0.type());
5365 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5366      * }
5367      * <p>
5368      * This method is also equivalent to the following code:
5369      * <blockquote><pre>
5370      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5371      * </pre></blockquote>
5372      * @param target the method handle to invoke after the arguments are dropped
5373      * @param pos position of first argument to drop (zero for the leftmost)
5374      * @param valueTypes the type(s) of the argument(s) to drop
5375      * @return a method handle which drops arguments of the given types,
5376      *         before calling the original method handle
5377      * @throws NullPointerException if the target is null,
5378      *                              or if the {@code valueTypes} list or any of its elements is null
5379      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5380      *                  or if {@code pos} is negative or greater than the arity of the target,
5381      *                  or if the new method handle's type would have too many parameters
5382      */
5383     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5384         return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone());
5385     }
5386 
5387     static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) {
5388         MethodType oldType = target.type();  // get NPE
5389         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5390         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5391         if (dropped == 0)  return target;
5392         BoundMethodHandle result = target.rebind();
5393         LambdaForm lform = result.form;
5394         int insertFormArg = 1 + pos;
5395         for (Class<?> ptype : valueTypes) {
5396             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5397         }
5398         result = result.copyWith(newType, lform);
5399         return result;
5400     }
5401 
5402     private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) {
5403         int dropped = valueTypes.length;
5404         MethodType.checkSlotCount(dropped);
5405         int outargs = oldType.parameterCount();
5406         int inargs  = outargs + dropped;
5407         if (pos < 0 || pos > outargs)
5408             throw newIllegalArgumentException("no argument type to remove"
5409                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5410                     );
5411         return dropped;
5412     }
5413 
5414     /**
5415      * Produces a method handle which will discard some dummy arguments
5416      * before calling some other specified <i>target</i> method handle.
5417      * The type of the new method handle will be the same as the target's type,
5418      * except it will also include the dummy argument types,
5419      * at some given position.
5420      * <p>
5421      * The {@code pos} argument may range between zero and <i>N</i>,
5422      * where <i>N</i> is the arity of the target.
5423      * If {@code pos} is zero, the dummy arguments will precede
5424      * the target's real arguments; if {@code pos} is <i>N</i>
5425      * they will come after.
5426      * @apiNote
5427      * {@snippet lang="java" :
5428 import static java.lang.invoke.MethodHandles.*;
5429 import static java.lang.invoke.MethodType.*;
5430 ...
5431 MethodHandle cat = lookup().findVirtual(String.class,
5432   "concat", methodType(String.class, String.class));
5433 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5434 MethodHandle d0 = dropArguments(cat, 0, String.class);
5435 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5436 MethodHandle d1 = dropArguments(cat, 1, String.class);
5437 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5438 MethodHandle d2 = dropArguments(cat, 2, String.class);
5439 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5440 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5441 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5442      * }
5443      * <p>
5444      * This method is also equivalent to the following code:
5445      * <blockquote><pre>
5446      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5447      * </pre></blockquote>
5448      * @param target the method handle to invoke after the arguments are dropped
5449      * @param pos position of first argument to drop (zero for the leftmost)
5450      * @param valueTypes the type(s) of the argument(s) to drop
5451      * @return a method handle which drops arguments of the given types,
5452      *         before calling the original method handle
5453      * @throws NullPointerException if the target is null,
5454      *                              or if the {@code valueTypes} array or any of its elements is null
5455      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5456      *                  or if {@code pos} is negative or greater than the arity of the target,
5457      *                  or if the new method handle's type would have
5458      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
5459      */
5460     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5461         return dropArgumentsTrusted(target, pos, valueTypes.clone());
5462     }
5463 
5464     /* Convenience overloads for trusting internal low-arity call-sites */
5465     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) {
5466         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 });
5467     }
5468     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) {
5469         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 });
5470     }
5471 
5472     // private version which allows caller some freedom with error handling
5473     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos,
5474                                       boolean nullOnFailure) {
5475         Class<?>[] oldTypes = target.type().ptypes();
5476         int match = oldTypes.length;
5477         if (skip != 0) {
5478             if (skip < 0 || skip > match) {
5479                 throw newIllegalArgumentException("illegal skip", skip, target);
5480             }
5481             oldTypes = Arrays.copyOfRange(oldTypes, skip, match);
5482             match -= skip;
5483         }
5484         Class<?>[] addTypes = newTypes;
5485         int add = addTypes.length;
5486         if (pos != 0) {
5487             if (pos < 0 || pos > add) {
5488                 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes));
5489             }
5490             addTypes = Arrays.copyOfRange(addTypes, pos, add);
5491             add -= pos;
5492             assert(addTypes.length == add);
5493         }
5494         // Do not add types which already match the existing arguments.
5495         if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) {
5496             if (nullOnFailure) {
5497                 return null;
5498             }
5499             throw newIllegalArgumentException("argument lists do not match",
5500                 Arrays.toString(oldTypes), Arrays.toString(newTypes));
5501         }
5502         addTypes = Arrays.copyOfRange(addTypes, match, add);
5503         add -= match;
5504         assert(addTypes.length == add);
5505         // newTypes:     (   P*[pos], M*[match], A*[add] )
5506         // target: ( S*[skip],        M*[match]  )
5507         MethodHandle adapter = target;
5508         if (add > 0) {
5509             adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes);
5510         }
5511         // adapter: (S*[skip],        M*[match], A*[add] )
5512         if (pos > 0) {
5513             adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos));
5514         }
5515         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5516         return adapter;
5517     }
5518 
5519     /**
5520      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5521      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5522      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5523      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5524      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5525      * {@link #dropArguments(MethodHandle, int, Class[])}.
5526      * <p>
5527      * The resulting handle will have the same return type as the target handle.
5528      * <p>
5529      * In more formal terms, assume these two type lists:<ul>
5530      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5531      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5532      * {@code newTypes}.
5533      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5534      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5535      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5536      * sub-list.
5537      * </ul>
5538      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5539      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5540      * {@link #dropArguments(MethodHandle, int, Class[])}.
5541      *
5542      * @apiNote
5543      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5544      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5545      * {@snippet lang="java" :
5546 import static java.lang.invoke.MethodHandles.*;
5547 import static java.lang.invoke.MethodType.*;
5548 ...
5549 ...
5550 MethodHandle h0 = constant(boolean.class, true);
5551 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5552 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5553 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5554 if (h1.type().parameterCount() < h2.type().parameterCount())
5555     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5556 else
5557     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5558 MethodHandle h3 = guardWithTest(h0, h1, h2);
5559 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5560      * }
5561      * @param target the method handle to adapt
5562      * @param skip number of targets parameters to disregard (they will be unchanged)
5563      * @param newTypes the list of types to match {@code target}'s parameter type list to
5564      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5565      * @return a possibly adapted method handle
5566      * @throws NullPointerException if either argument is null
5567      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5568      *         or if {@code skip} is negative or greater than the arity of the target,
5569      *         or if {@code pos} is negative or greater than the newTypes list size,
5570      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5571      *         {@code pos}.
5572      * @since 9
5573      */
5574     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5575         Objects.requireNonNull(target);
5576         Objects.requireNonNull(newTypes);
5577         return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false);
5578     }
5579 
5580     /**
5581      * Drop the return value of the target handle (if any).
5582      * The returned method handle will have a {@code void} return type.
5583      *
5584      * @param target the method handle to adapt
5585      * @return a possibly adapted method handle
5586      * @throws NullPointerException if {@code target} is null
5587      * @since 16
5588      */
5589     public static MethodHandle dropReturn(MethodHandle target) {
5590         Objects.requireNonNull(target);
5591         MethodType oldType = target.type();
5592         Class<?> oldReturnType = oldType.returnType();
5593         if (oldReturnType == void.class)
5594             return target;
5595         MethodType newType = oldType.changeReturnType(void.class);
5596         BoundMethodHandle result = target.rebind();
5597         LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5598         result = result.copyWith(newType, lform);
5599         return result;
5600     }
5601 
5602     /**
5603      * Adapts a target method handle by pre-processing
5604      * one or more of its arguments, each with its own unary filter function,
5605      * and then calling the target with each pre-processed argument
5606      * replaced by the result of its corresponding filter function.
5607      * <p>
5608      * The pre-processing is performed by one or more method handles,
5609      * specified in the elements of the {@code filters} array.
5610      * The first element of the filter array corresponds to the {@code pos}
5611      * argument of the target, and so on in sequence.
5612      * The filter functions are invoked in left to right order.
5613      * <p>
5614      * Null arguments in the array are treated as identity functions,
5615      * and the corresponding arguments left unchanged.
5616      * (If there are no non-null elements in the array, the original target is returned.)
5617      * Each filter is applied to the corresponding argument of the adapter.
5618      * <p>
5619      * If a filter {@code F} applies to the {@code N}th argument of
5620      * the target, then {@code F} must be a method handle which
5621      * takes exactly one argument.  The type of {@code F}'s sole argument
5622      * replaces the corresponding argument type of the target
5623      * in the resulting adapted method handle.
5624      * The return type of {@code F} must be identical to the corresponding
5625      * parameter type of the target.
5626      * <p>
5627      * It is an error if there are elements of {@code filters}
5628      * (null or not)
5629      * which do not correspond to argument positions in the target.
5630      * <p><b>Example:</b>
5631      * {@snippet lang="java" :
5632 import static java.lang.invoke.MethodHandles.*;
5633 import static java.lang.invoke.MethodType.*;
5634 ...
5635 MethodHandle cat = lookup().findVirtual(String.class,
5636   "concat", methodType(String.class, String.class));
5637 MethodHandle upcase = lookup().findVirtual(String.class,
5638   "toUpperCase", methodType(String.class));
5639 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5640 MethodHandle f0 = filterArguments(cat, 0, upcase);
5641 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5642 MethodHandle f1 = filterArguments(cat, 1, upcase);
5643 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5644 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5645 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5646      * }
5647      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5648      * denotes the return type of both the {@code target} and resulting adapter.
5649      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5650      * of the parameters and arguments that precede and follow the filter position
5651      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5652      * values of the filtered parameters and arguments; they also represent the
5653      * return types of the {@code filter[i]} handles. The latter accept arguments
5654      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5655      * the resulting adapter.
5656      * {@snippet lang="java" :
5657      * T target(P... p, A[i]... a[i], B... b);
5658      * A[i] filter[i](V[i]);
5659      * T adapter(P... p, V[i]... v[i], B... b) {
5660      *   return target(p..., filter[i](v[i])..., b...);
5661      * }
5662      * }
5663      * <p>
5664      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5665      * variable-arity method handle}, even if the original target method handle was.
5666      *
5667      * @param target the method handle to invoke after arguments are filtered
5668      * @param pos the position of the first argument to filter
5669      * @param filters method handles to call initially on filtered arguments
5670      * @return method handle which incorporates the specified argument filtering logic
5671      * @throws NullPointerException if the target is null
5672      *                              or if the {@code filters} array is null
5673      * @throws IllegalArgumentException if a non-null element of {@code filters}
5674      *          does not match a corresponding argument type of target as described above,
5675      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5676      *          or if the resulting method handle's type would have
5677      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5678      */
5679     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5680         // In method types arguments start at index 0, while the LF
5681         // editor have the MH receiver at position 0 - adjust appropriately.
5682         final int MH_RECEIVER_OFFSET = 1;
5683         filterArgumentsCheckArity(target, pos, filters);
5684         MethodHandle adapter = target;
5685 
5686         // keep track of currently matched filters, as to optimize repeated filters
5687         int index = 0;
5688         int[] positions = new int[filters.length];
5689         MethodHandle filter = null;
5690 
5691         // process filters in reverse order so that the invocation of
5692         // the resulting adapter will invoke the filters in left-to-right order
5693         for (int i = filters.length - 1; i >= 0; --i) {
5694             MethodHandle newFilter = filters[i];
5695             if (newFilter == null) continue;  // ignore null elements of filters
5696 
5697             // flush changes on update
5698             if (filter != newFilter) {
5699                 if (filter != null) {
5700                     if (index > 1) {
5701                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5702                     } else {
5703                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5704                     }
5705                 }
5706                 filter = newFilter;
5707                 index = 0;
5708             }
5709 
5710             filterArgumentChecks(target, pos + i, newFilter);
5711             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5712         }
5713         if (index > 1) {
5714             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5715         } else if (index == 1) {
5716             adapter = filterArgument(adapter, positions[0] - 1, filter);
5717         }
5718         return adapter;
5719     }
5720 
5721     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5722         MethodType targetType = adapter.type();
5723         MethodType filterType = filter.type();
5724         BoundMethodHandle result = adapter.rebind();
5725         Class<?> newParamType = filterType.parameterType(0);
5726 
5727         Class<?>[] ptypes = targetType.ptypes().clone();
5728         for (int pos : positions) {
5729             ptypes[pos - 1] = newParamType;
5730         }
5731         MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true);
5732 
5733         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5734         return result.copyWithExtendL(newType, lform, filter);
5735     }
5736 
5737     /*non-public*/
5738     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5739         filterArgumentChecks(target, pos, filter);
5740         MethodType targetType = target.type();
5741         MethodType filterType = filter.type();
5742         BoundMethodHandle result = target.rebind();
5743         Class<?> newParamType = filterType.parameterType(0);
5744         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5745         MethodType newType = targetType.changeParameterType(pos, newParamType);
5746         result = result.copyWithExtendL(newType, lform, filter);
5747         return result;
5748     }
5749 
5750     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5751         MethodType targetType = target.type();
5752         int maxPos = targetType.parameterCount();
5753         if (pos + filters.length > maxPos)
5754             throw newIllegalArgumentException("too many filters");
5755     }
5756 
5757     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5758         MethodType targetType = target.type();
5759         MethodType filterType = filter.type();
5760         if (filterType.parameterCount() != 1
5761             || filterType.returnType() != targetType.parameterType(pos))
5762             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5763     }
5764 
5765     /**
5766      * Adapts a target method handle by pre-processing
5767      * a sub-sequence of its arguments with a filter (another method handle).
5768      * The pre-processed arguments are replaced by the result (if any) of the
5769      * filter function.
5770      * The target is then called on the modified (usually shortened) argument list.
5771      * <p>
5772      * If the filter returns a value, the target must accept that value as
5773      * its argument in position {@code pos}, preceded and/or followed by
5774      * any arguments not passed to the filter.
5775      * If the filter returns void, the target must accept all arguments
5776      * not passed to the filter.
5777      * No arguments are reordered, and a result returned from the filter
5778      * replaces (in order) the whole subsequence of arguments originally
5779      * passed to the adapter.
5780      * <p>
5781      * The argument types (if any) of the filter
5782      * replace zero or one argument types of the target, at position {@code pos},
5783      * in the resulting adapted method handle.
5784      * The return type of the filter (if any) must be identical to the
5785      * argument type of the target at position {@code pos}, and that target argument
5786      * is supplied by the return value of the filter.
5787      * <p>
5788      * In all cases, {@code pos} must be greater than or equal to zero, and
5789      * {@code pos} must also be less than or equal to the target's arity.
5790      * <p><b>Example:</b>
5791      * {@snippet lang="java" :
5792 import static java.lang.invoke.MethodHandles.*;
5793 import static java.lang.invoke.MethodType.*;
5794 ...
5795 MethodHandle deepToString = publicLookup()
5796   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5797 
5798 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5799 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5800 
5801 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5802 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5803 
5804 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5805 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5806 assertEquals("[top, [up, down], strange]",
5807              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5808 
5809 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5810 assertEquals("[top, [up, down], [strange]]",
5811              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5812 
5813 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5814 assertEquals("[top, [[up, down, strange], charm], bottom]",
5815              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5816      * }
5817      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5818      * represents the return type of the {@code target} and resulting adapter.
5819      * {@code V}/{@code v} stand for the return type and value of the
5820      * {@code filter}, which are also found in the signature and arguments of
5821      * the {@code target}, respectively, unless {@code V} is {@code void}.
5822      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5823      * and values preceding and following the collection position, {@code pos},
5824      * in the {@code target}'s signature. They also turn up in the resulting
5825      * adapter's signature and arguments, where they surround
5826      * {@code B}/{@code b}, which represent the parameter types and arguments
5827      * to the {@code filter} (if any).
5828      * {@snippet lang="java" :
5829      * T target(A...,V,C...);
5830      * V filter(B...);
5831      * T adapter(A... a,B... b,C... c) {
5832      *   V v = filter(b...);
5833      *   return target(a...,v,c...);
5834      * }
5835      * // and if the filter has no arguments:
5836      * T target2(A...,V,C...);
5837      * V filter2();
5838      * T adapter2(A... a,C... c) {
5839      *   V v = filter2();
5840      *   return target2(a...,v,c...);
5841      * }
5842      * // and if the filter has a void return:
5843      * T target3(A...,C...);
5844      * void filter3(B...);
5845      * T adapter3(A... a,B... b,C... c) {
5846      *   filter3(b...);
5847      *   return target3(a...,c...);
5848      * }
5849      * }
5850      * <p>
5851      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5852      * one which first "folds" the affected arguments, and then drops them, in separate
5853      * steps as follows:
5854      * {@snippet lang="java" :
5855      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5856      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5857      * }
5858      * If the target method handle consumes no arguments besides than the result
5859      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5860      * is equivalent to {@code filterReturnValue(coll, mh)}.
5861      * If the filter method handle {@code coll} consumes one argument and produces
5862      * a non-void result, then {@code collectArguments(mh, N, coll)}
5863      * is equivalent to {@code filterArguments(mh, N, coll)}.
5864      * Other equivalences are possible but would require argument permutation.
5865      * <p>
5866      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5867      * variable-arity method handle}, even if the original target method handle was.
5868      *
5869      * @param target the method handle to invoke after filtering the subsequence of arguments
5870      * @param pos the position of the first adapter argument to pass to the filter,
5871      *            and/or the target argument which receives the result of the filter
5872      * @param filter method handle to call on the subsequence of arguments
5873      * @return method handle which incorporates the specified argument subsequence filtering logic
5874      * @throws NullPointerException if either argument is null
5875      * @throws IllegalArgumentException if the return type of {@code filter}
5876      *          is non-void and is not the same as the {@code pos} argument of the target,
5877      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5878      *          or if the resulting method handle's type would have
5879      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5880      * @see MethodHandles#foldArguments
5881      * @see MethodHandles#filterArguments
5882      * @see MethodHandles#filterReturnValue
5883      */
5884     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5885         MethodType newType = collectArgumentsChecks(target, pos, filter);
5886         MethodType collectorType = filter.type();
5887         BoundMethodHandle result = target.rebind();
5888         LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5889         return result.copyWithExtendL(newType, lform, filter);
5890     }
5891 
5892     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5893         MethodType targetType = target.type();
5894         MethodType filterType = filter.type();
5895         Class<?> rtype = filterType.returnType();
5896         Class<?>[] filterArgs = filterType.ptypes();
5897         if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5898                        (rtype != void.class && pos >= targetType.parameterCount())) {
5899             throw newIllegalArgumentException("position is out of range for target", target, pos);
5900         }
5901         if (rtype == void.class) {
5902             return targetType.insertParameterTypes(pos, filterArgs);
5903         }
5904         if (rtype != targetType.parameterType(pos)) {
5905             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5906         }
5907         return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs);
5908     }
5909 
5910     /**
5911      * Adapts a target method handle by post-processing
5912      * its return value (if any) with a filter (another method handle).
5913      * The result of the filter is returned from the adapter.
5914      * <p>
5915      * If the target returns a value, the filter must accept that value as
5916      * its only argument.
5917      * If the target returns void, the filter must accept no arguments.
5918      * <p>
5919      * The return type of the filter
5920      * replaces the return type of the target
5921      * in the resulting adapted method handle.
5922      * The argument type of the filter (if any) must be identical to the
5923      * return type of the target.
5924      * <p><b>Example:</b>
5925      * {@snippet lang="java" :
5926 import static java.lang.invoke.MethodHandles.*;
5927 import static java.lang.invoke.MethodType.*;
5928 ...
5929 MethodHandle cat = lookup().findVirtual(String.class,
5930   "concat", methodType(String.class, String.class));
5931 MethodHandle length = lookup().findVirtual(String.class,
5932   "length", methodType(int.class));
5933 System.out.println((String) cat.invokeExact("x", "y")); // xy
5934 MethodHandle f0 = filterReturnValue(cat, length);
5935 System.out.println((int) f0.invokeExact("x", "y")); // 2
5936      * }
5937      * <p>Here is pseudocode for the resulting adapter. In the code,
5938      * {@code T}/{@code t} represent the result type and value of the
5939      * {@code target}; {@code V}, the result type of the {@code filter}; and
5940      * {@code A}/{@code a}, the types and values of the parameters and arguments
5941      * of the {@code target} as well as the resulting adapter.
5942      * {@snippet lang="java" :
5943      * T target(A...);
5944      * V filter(T);
5945      * V adapter(A... a) {
5946      *   T t = target(a...);
5947      *   return filter(t);
5948      * }
5949      * // and if the target has a void return:
5950      * void target2(A...);
5951      * V filter2();
5952      * V adapter2(A... a) {
5953      *   target2(a...);
5954      *   return filter2();
5955      * }
5956      * // and if the filter has a void return:
5957      * T target3(A...);
5958      * void filter3(V);
5959      * void adapter3(A... a) {
5960      *   T t = target3(a...);
5961      *   filter3(t);
5962      * }
5963      * }
5964      * <p>
5965      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5966      * variable-arity method handle}, even if the original target method handle was.
5967      * @param target the method handle to invoke before filtering the return value
5968      * @param filter method handle to call on the return value
5969      * @return method handle which incorporates the specified return value filtering logic
5970      * @throws NullPointerException if either argument is null
5971      * @throws IllegalArgumentException if the argument list of {@code filter}
5972      *          does not match the return type of target as described above
5973      */
5974     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5975         MethodType targetType = target.type();
5976         MethodType filterType = filter.type();
5977         filterReturnValueChecks(targetType, filterType);
5978         BoundMethodHandle result = target.rebind();
5979         BasicType rtype = BasicType.basicType(filterType.returnType());
5980         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5981         MethodType newType = targetType.changeReturnType(filterType.returnType());
5982         result = result.copyWithExtendL(newType, lform, filter);
5983         return result;
5984     }
5985 
5986     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5987         Class<?> rtype = targetType.returnType();
5988         int filterValues = filterType.parameterCount();
5989         if (filterValues == 0
5990                 ? (rtype != void.class)
5991                 : (rtype != filterType.parameterType(0) || filterValues != 1))
5992             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5993     }
5994 
5995     /**
5996      * Filter the return value of a target method handle with a filter function. The filter function is
5997      * applied to the return value of the original handle; if the filter specifies more than one parameters,
5998      * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5999      * as follows:
6000      * {@snippet lang="java" :
6001      * T target(A...)
6002      * V filter(B... , T)
6003      * V adapter(A... a, B... b) {
6004      *     T t = target(a...);
6005      *     return filter(b..., t);
6006      * }
6007      * }
6008      * <p>
6009      * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
6010      *
6011      * @param target the target method handle
6012      * @param filter the filter method handle
6013      * @return the adapter method handle
6014      */
6015     /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
6016         MethodType targetType = target.type();
6017         MethodType filterType = filter.type();
6018         BoundMethodHandle result = target.rebind();
6019         LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
6020         MethodType newType = targetType.changeReturnType(filterType.returnType());
6021         if (filterType.parameterCount() > 1) {
6022             for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
6023                 newType = newType.appendParameterTypes(filterType.parameterType(i));
6024             }
6025         }
6026         result = result.copyWithExtendL(newType, lform, filter);
6027         return result;
6028     }
6029 
6030     /**
6031      * Adapts a target method handle by pre-processing
6032      * some of its arguments, and then calling the target with
6033      * the result of the pre-processing, inserted into the original
6034      * sequence of arguments.
6035      * <p>
6036      * The pre-processing is performed by {@code combiner}, a second method handle.
6037      * Of the arguments passed to the adapter, the first {@code N} arguments
6038      * are copied to the combiner, which is then called.
6039      * (Here, {@code N} is defined as the parameter count of the combiner.)
6040      * After this, control passes to the target, with any result
6041      * from the combiner inserted before the original {@code N} incoming
6042      * arguments.
6043      * <p>
6044      * If the combiner returns a value, the first parameter type of the target
6045      * must be identical with the return type of the combiner, and the next
6046      * {@code N} parameter types of the target must exactly match the parameters
6047      * of the combiner.
6048      * <p>
6049      * If the combiner has a void return, no result will be inserted,
6050      * and the first {@code N} parameter types of the target
6051      * must exactly match the parameters of the combiner.
6052      * <p>
6053      * The resulting adapter is the same type as the target, except that the
6054      * first parameter type is dropped,
6055      * if it corresponds to the result of the combiner.
6056      * <p>
6057      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
6058      * that either the combiner or the target does not wish to receive.
6059      * If some of the incoming arguments are destined only for the combiner,
6060      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
6061      * arguments will not need to be live on the stack on entry to the
6062      * target.)
6063      * <p><b>Example:</b>
6064      * {@snippet lang="java" :
6065 import static java.lang.invoke.MethodHandles.*;
6066 import static java.lang.invoke.MethodType.*;
6067 ...
6068 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6069   "println", methodType(void.class, String.class))
6070     .bindTo(System.out);
6071 MethodHandle cat = lookup().findVirtual(String.class,
6072   "concat", methodType(String.class, String.class));
6073 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6074 MethodHandle catTrace = foldArguments(cat, trace);
6075 // also prints "boo":
6076 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6077      * }
6078      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6079      * represents the result type of the {@code target} and resulting adapter.
6080      * {@code V}/{@code v} represent the type and value of the parameter and argument
6081      * of {@code target} that precedes the folding position; {@code V} also is
6082      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6083      * types and values of the {@code N} parameters and arguments at the folding
6084      * position. {@code B}/{@code b} represent the types and values of the
6085      * {@code target} parameters and arguments that follow the folded parameters
6086      * and arguments.
6087      * {@snippet lang="java" :
6088      * // there are N arguments in A...
6089      * T target(V, A[N]..., B...);
6090      * V combiner(A...);
6091      * T adapter(A... a, B... b) {
6092      *   V v = combiner(a...);
6093      *   return target(v, a..., b...);
6094      * }
6095      * // and if the combiner has a void return:
6096      * T target2(A[N]..., B...);
6097      * void combiner2(A...);
6098      * T adapter2(A... a, B... b) {
6099      *   combiner2(a...);
6100      *   return target2(a..., b...);
6101      * }
6102      * }
6103      * <p>
6104      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6105      * variable-arity method handle}, even if the original target method handle was.
6106      * @param target the method handle to invoke after arguments are combined
6107      * @param combiner method handle to call initially on the incoming arguments
6108      * @return method handle which incorporates the specified argument folding logic
6109      * @throws NullPointerException if either argument is null
6110      * @throws IllegalArgumentException if {@code combiner}'s return type
6111      *          is non-void and not the same as the first argument type of
6112      *          the target, or if the initial {@code N} argument types
6113      *          of the target
6114      *          (skipping one matching the {@code combiner}'s return type)
6115      *          are not identical with the argument types of {@code combiner}
6116      */
6117     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
6118         return foldArguments(target, 0, combiner);
6119     }
6120 
6121     /**
6122      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
6123      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
6124      * before the folded arguments.
6125      * <p>
6126      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
6127      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
6128      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
6129      * 0.
6130      *
6131      * @apiNote Example:
6132      * {@snippet lang="java" :
6133     import static java.lang.invoke.MethodHandles.*;
6134     import static java.lang.invoke.MethodType.*;
6135     ...
6136     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6137     "println", methodType(void.class, String.class))
6138     .bindTo(System.out);
6139     MethodHandle cat = lookup().findVirtual(String.class,
6140     "concat", methodType(String.class, String.class));
6141     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6142     MethodHandle catTrace = foldArguments(cat, 1, trace);
6143     // also prints "jum":
6144     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6145      * }
6146      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6147      * represents the result type of the {@code target} and resulting adapter.
6148      * {@code V}/{@code v} represent the type and value of the parameter and argument
6149      * of {@code target} that precedes the folding position; {@code V} also is
6150      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6151      * types and values of the {@code N} parameters and arguments at the folding
6152      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
6153      * and values of the {@code target} parameters and arguments that precede and
6154      * follow the folded parameters and arguments starting at {@code pos},
6155      * respectively.
6156      * {@snippet lang="java" :
6157      * // there are N arguments in A...
6158      * T target(Z..., V, A[N]..., B...);
6159      * V combiner(A...);
6160      * T adapter(Z... z, A... a, B... b) {
6161      *   V v = combiner(a...);
6162      *   return target(z..., v, a..., b...);
6163      * }
6164      * // and if the combiner has a void return:
6165      * T target2(Z..., A[N]..., B...);
6166      * void combiner2(A...);
6167      * T adapter2(Z... z, A... a, B... b) {
6168      *   combiner2(a...);
6169      *   return target2(z..., a..., b...);
6170      * }
6171      * }
6172      * <p>
6173      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6174      * variable-arity method handle}, even if the original target method handle was.
6175      *
6176      * @param target the method handle to invoke after arguments are combined
6177      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
6178      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6179      * @param combiner method handle to call initially on the incoming arguments
6180      * @return method handle which incorporates the specified argument folding logic
6181      * @throws NullPointerException if either argument is null
6182      * @throws IllegalArgumentException if either of the following two conditions holds:
6183      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6184      *              {@code pos} of the target signature;
6185      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
6186      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
6187      *
6188      * @see #foldArguments(MethodHandle, MethodHandle)
6189      * @since 9
6190      */
6191     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
6192         MethodType targetType = target.type();
6193         MethodType combinerType = combiner.type();
6194         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
6195         BoundMethodHandle result = target.rebind();
6196         boolean dropResult = rtype == void.class;
6197         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
6198         MethodType newType = targetType;
6199         if (!dropResult) {
6200             newType = newType.dropParameterTypes(pos, pos + 1);
6201         }
6202         result = result.copyWithExtendL(newType, lform, combiner);
6203         return result;
6204     }
6205 
6206     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
6207         int foldArgs   = combinerType.parameterCount();
6208         Class<?> rtype = combinerType.returnType();
6209         int foldVals = rtype == void.class ? 0 : 1;
6210         int afterInsertPos = foldPos + foldVals;
6211         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
6212         if (ok) {
6213             for (int i = 0; i < foldArgs; i++) {
6214                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
6215                     ok = false;
6216                     break;
6217                 }
6218             }
6219         }
6220         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
6221             ok = false;
6222         if (!ok)
6223             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6224         return rtype;
6225     }
6226 
6227     /**
6228      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
6229      * of the pre-processing replacing the argument at the given position.
6230      *
6231      * @param target the method handle to invoke after arguments are combined
6232      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6233      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6234      * @param combiner method handle to call initially on the incoming arguments
6235      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6236      * @return method handle which incorporates the specified argument folding logic
6237      * @throws NullPointerException if either argument is null
6238      * @throws IllegalArgumentException if either of the following two conditions holds:
6239      *          (1) {@code combiner}'s return type is not the same as the argument type at position
6240      *              {@code pos} of the target signature;
6241      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
6242      *              not identical with the argument types of {@code combiner}.
6243      */
6244     /*non-public*/
6245     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6246         return argumentsWithCombiner(true, target, position, combiner, argPositions);
6247     }
6248 
6249     /**
6250      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
6251      * the pre-processing inserted into the original sequence of arguments at the given position.
6252      *
6253      * @param target the method handle to invoke after arguments are combined
6254      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6255      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6256      * @param combiner method handle to call initially on the incoming arguments
6257      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6258      * @return method handle which incorporates the specified argument folding logic
6259      * @throws NullPointerException if either argument is null
6260      * @throws IllegalArgumentException if either of the following two conditions holds:
6261      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6262      *              {@code pos} of the target signature;
6263      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
6264      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
6265      *              with the argument types of {@code combiner}.
6266      */
6267     /*non-public*/
6268     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6269         return argumentsWithCombiner(false, target, position, combiner, argPositions);
6270     }
6271 
6272     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6273         MethodType targetType = target.type();
6274         MethodType combinerType = combiner.type();
6275         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
6276         BoundMethodHandle result = target.rebind();
6277 
6278         MethodType newType = targetType;
6279         LambdaForm lform;
6280         if (filter) {
6281             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
6282         } else {
6283             boolean dropResult = rtype == void.class;
6284             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
6285             if (!dropResult) {
6286                 newType = newType.dropParameterTypes(position, position + 1);
6287             }
6288         }
6289         result = result.copyWithExtendL(newType, lform, combiner);
6290         return result;
6291     }
6292 
6293     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
6294         int combinerArgs = combinerType.parameterCount();
6295         if (argPos.length != combinerArgs) {
6296             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
6297         }
6298         Class<?> rtype = combinerType.returnType();
6299 
6300         for (int i = 0; i < combinerArgs; i++) {
6301             int arg = argPos[i];
6302             if (arg < 0 || arg > targetType.parameterCount()) {
6303                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
6304             }
6305             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
6306                 throw newIllegalArgumentException("target argument type at position " + arg
6307                         + " must match combiner argument type at index " + i + ": " + targetType
6308                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6309             }
6310         }
6311         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6312             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6313         }
6314         return rtype;
6315     }
6316 
6317     /**
6318      * Makes a method handle which adapts a target method handle,
6319      * by guarding it with a test, a boolean-valued method handle.
6320      * If the guard fails, a fallback handle is called instead.
6321      * All three method handles must have the same corresponding
6322      * argument and return types, except that the return type
6323      * of the test must be boolean, and the test is allowed
6324      * to have fewer arguments than the other two method handles.
6325      * <p>
6326      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6327      * represents the uniform result type of the three involved handles;
6328      * {@code A}/{@code a}, the types and values of the {@code target}
6329      * parameters and arguments that are consumed by the {@code test}; and
6330      * {@code B}/{@code b}, those types and values of the {@code target}
6331      * parameters and arguments that are not consumed by the {@code test}.
6332      * {@snippet lang="java" :
6333      * boolean test(A...);
6334      * T target(A...,B...);
6335      * T fallback(A...,B...);
6336      * T adapter(A... a,B... b) {
6337      *   if (test(a...))
6338      *     return target(a..., b...);
6339      *   else
6340      *     return fallback(a..., b...);
6341      * }
6342      * }
6343      * Note that the test arguments ({@code a...} in the pseudocode) cannot
6344      * be modified by execution of the test, and so are passed unchanged
6345      * from the caller to the target or fallback as appropriate.
6346      * @param test method handle used for test, must return boolean
6347      * @param target method handle to call if test passes
6348      * @param fallback method handle to call if test fails
6349      * @return method handle which incorporates the specified if/then/else logic
6350      * @throws NullPointerException if any argument is null
6351      * @throws IllegalArgumentException if {@code test} does not return boolean,
6352      *          or if all three method types do not match (with the return
6353      *          type of {@code test} changed to match that of the target).
6354      */
6355     public static MethodHandle guardWithTest(MethodHandle test,
6356                                MethodHandle target,
6357                                MethodHandle fallback) {
6358         MethodType gtype = test.type();
6359         MethodType ttype = target.type();
6360         MethodType ftype = fallback.type();
6361         if (!ttype.equals(ftype))
6362             throw misMatchedTypes("target and fallback types", ttype, ftype);
6363         if (gtype.returnType() != boolean.class)
6364             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6365 
6366         test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true);
6367         if (test == null) {
6368             throw misMatchedTypes("target and test types", ttype, gtype);
6369         }
6370         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6371     }
6372 
6373     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6374         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6375     }
6376 
6377     /**
6378      * Makes a method handle which adapts a target method handle,
6379      * by running it inside an exception handler.
6380      * If the target returns normally, the adapter returns that value.
6381      * If an exception matching the specified type is thrown, the fallback
6382      * handle is called instead on the exception, plus the original arguments.
6383      * <p>
6384      * The target and handler must have the same corresponding
6385      * argument and return types, except that handler may omit trailing arguments
6386      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6387      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6388      * <p>
6389      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6390      * represents the return type of the {@code target} and {@code handler},
6391      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6392      * the types and values of arguments to the resulting handle consumed by
6393      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6394      * resulting handle discarded by {@code handler}.
6395      * {@snippet lang="java" :
6396      * T target(A..., B...);
6397      * T handler(ExType, A...);
6398      * T adapter(A... a, B... b) {
6399      *   try {
6400      *     return target(a..., b...);
6401      *   } catch (ExType ex) {
6402      *     return handler(ex, a...);
6403      *   }
6404      * }
6405      * }
6406      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6407      * be modified by execution of the target, and so are passed unchanged
6408      * from the caller to the handler, if the handler is invoked.
6409      * <p>
6410      * The target and handler must return the same type, even if the handler
6411      * always throws.  (This might happen, for instance, because the handler
6412      * is simulating a {@code finally} clause).
6413      * To create such a throwing handler, compose the handler creation logic
6414      * with {@link #throwException throwException},
6415      * in order to create a method handle of the correct return type.
6416      * @param target method handle to call
6417      * @param exType the type of exception which the handler will catch
6418      * @param handler method handle to call if a matching exception is thrown
6419      * @return method handle which incorporates the specified try/catch logic
6420      * @throws NullPointerException if any argument is null
6421      * @throws IllegalArgumentException if {@code handler} does not accept
6422      *          the given exception type, or if the method handle types do
6423      *          not match in their return types and their
6424      *          corresponding parameters
6425      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6426      */
6427     public static MethodHandle catchException(MethodHandle target,
6428                                 Class<? extends Throwable> exType,
6429                                 MethodHandle handler) {
6430         MethodType ttype = target.type();
6431         MethodType htype = handler.type();
6432         if (!Throwable.class.isAssignableFrom(exType))
6433             throw new ClassCastException(exType.getName());
6434         if (htype.parameterCount() < 1 ||
6435             !htype.parameterType(0).isAssignableFrom(exType))
6436             throw newIllegalArgumentException("handler does not accept exception type "+exType);
6437         if (htype.returnType() != ttype.returnType())
6438             throw misMatchedTypes("target and handler return types", ttype, htype);
6439         handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true);
6440         if (handler == null) {
6441             throw misMatchedTypes("target and handler types", ttype, htype);
6442         }
6443         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6444     }
6445 
6446     /**
6447      * Produces a method handle which will throw exceptions of the given {@code exType}.
6448      * The method handle will accept a single argument of {@code exType},
6449      * and immediately throw it as an exception.
6450      * The method type will nominally specify a return of {@code returnType}.
6451      * The return type may be anything convenient:  It doesn't matter to the
6452      * method handle's behavior, since it will never return normally.
6453      * @param returnType the return type of the desired method handle
6454      * @param exType the parameter type of the desired method handle
6455      * @return method handle which can throw the given exceptions
6456      * @throws NullPointerException if either argument is null
6457      */
6458     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6459         if (!Throwable.class.isAssignableFrom(exType))
6460             throw new ClassCastException(exType.getName());
6461         return MethodHandleImpl.throwException(methodType(returnType, exType));
6462     }
6463 
6464     /**
6465      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6466      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6467      * delivers the loop's result, which is the return value of the resulting handle.
6468      * <p>
6469      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6470      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6471      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6472      * terms of method handles, each clause will specify up to four independent actions:<ul>
6473      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6474      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6475      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6476      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6477      * </ul>
6478      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6479      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
6480      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6481      * <p>
6482      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6483      * this case. See below for a detailed description.
6484      * <p>
6485      * <em>Parameters optional everywhere:</em>
6486      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6487      * As an exception, the init functions cannot take any {@code v} parameters,
6488      * because those values are not yet computed when the init functions are executed.
6489      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6490      * In fact, any clause function may take no arguments at all.
6491      * <p>
6492      * <em>Loop parameters:</em>
6493      * A clause function may take all the iteration variable values it is entitled to, in which case
6494      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6495      * with their types and values notated as {@code (A...)} and {@code (a...)}.
6496      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6497      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6498      * init function is automatically a loop parameter {@code a}.)
6499      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6500      * These loop parameters act as loop-invariant values visible across the whole loop.
6501      * <p>
6502      * <em>Parameters visible everywhere:</em>
6503      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6504      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6505      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6506      * Most clause functions will not need all of this information, but they will be formally connected to it
6507      * as if by {@link #dropArguments}.
6508      * <a id="astar"></a>
6509      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6510      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6511      * In that notation, the general form of an init function parameter list
6512      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6513      * <p>
6514      * <em>Checking clause structure:</em>
6515      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6516      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6517      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6518      * met by the inputs to the loop combinator.
6519      * <p>
6520      * <em>Effectively identical sequences:</em>
6521      * <a id="effid"></a>
6522      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6523      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6524      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6525      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6526      * that longest list.
6527      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6528      * and the same is true if more sequences of the form {@code (V... A*)} are added.
6529      * <p>
6530      * <em>Step 0: Determine clause structure.</em><ol type="a">
6531      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6532      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6533      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6534      * four. Padding takes place by appending elements to the array.
6535      * <li>Clauses with all {@code null}s are disregarded.
6536      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6537      * </ol>
6538      * <p>
6539      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6540      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6541      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6542      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6543      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6544      * iteration variable type.
6545      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6546      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6547      * </ol>
6548      * <p>
6549      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6550      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6551      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6552      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6553      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6554      * (These types will be checked in step 2, along with all the clause function types.)
6555      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6556      * <li>All of the collected parameter lists must be effectively identical.
6557      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6558      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6559      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6560      * the "internal parameter list".
6561      * </ul>
6562      * <p>
6563      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6564      * <li>Examine fini function return types, disregarding omitted fini functions.
6565      * <li>If there are no fini functions, the loop return type is {@code void}.
6566      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6567      * type.
6568      * </ol>
6569      * <p>
6570      * <em>Step 1D: Check other types.</em><ol type="a">
6571      * <li>There must be at least one non-omitted pred function.
6572      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6573      * </ol>
6574      * <p>
6575      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6576      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6577      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6578      * (Note that their parameter lists are already effectively identical to this list.)
6579      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6580      * effectively identical to the internal parameter list {@code (V... A...)}.
6581      * </ol>
6582      * <p>
6583      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6584      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6585      * type.
6586      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6587      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6588      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6589      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6590      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6591      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6592      * loop return type.
6593      * </ol>
6594      * <p>
6595      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6596      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6597      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6598      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6599      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6600      * pad out the end of the list.
6601      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6602      * </ol>
6603      * <p>
6604      * <em>Final observations.</em><ol type="a">
6605      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6606      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6607      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6608      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6609      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6610      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6611      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6612      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6613      * </ol>
6614      * <p>
6615      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6616      * <ul>
6617      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6618      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6619      * (Only one {@code Pn} has to be non-{@code null}.)
6620      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6621      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6622      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6623      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6624      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6625      * the resulting loop handle's parameter types {@code (A...)}.
6626      * </ul>
6627      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6628      * which is natural if most of the loop computation happens in the steps.  For some loops,
6629      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6630      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6631      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6632      * where the init functions will need the extra parameters.  For such reasons, the rules for
6633      * determining these parameters are as symmetric as possible, across all clause parts.
6634      * In general, the loop parameters function as common invariant values across the whole
6635      * loop, while the iteration variables function as common variant values, or (if there is
6636      * no step function) as internal loop invariant temporaries.
6637      * <p>
6638      * <em>Loop execution.</em><ol type="a">
6639      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6640      * every clause function. These locals are loop invariant.
6641      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6642      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6643      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6644      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6645      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6646      * (in argument order).
6647      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6648      * returns {@code false}.
6649      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6650      * sequence {@code (v...)} of loop variables.
6651      * The updated value is immediately visible to all subsequent function calls.
6652      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6653      * (of type {@code R}) is returned from the loop as a whole.
6654      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6655      * except by throwing an exception.
6656      * </ol>
6657      * <p>
6658      * <em>Usage tips.</em>
6659      * <ul>
6660      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6661      * sometimes a step function only needs to observe the current value of its own variable.
6662      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6663      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6664      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6665      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6666      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6667      * <li>If some of the clause functions are virtual methods on an instance, the instance
6668      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6669      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6670      * will be the first iteration variable value, and it will be easy to use virtual
6671      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6672      * </ul>
6673      * <p>
6674      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6675      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6676      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6677      * {@snippet lang="java" :
6678      * V... init...(A...);
6679      * boolean pred...(V..., A...);
6680      * V... step...(V..., A...);
6681      * R fini...(V..., A...);
6682      * R loop(A... a) {
6683      *   V... v... = init...(a...);
6684      *   for (;;) {
6685      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6686      *       v = s(v..., a...);
6687      *       if (!p(v..., a...)) {
6688      *         return f(v..., a...);
6689      *       }
6690      *     }
6691      *   }
6692      * }
6693      * }
6694      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6695      * to their full length, even though individual clause functions may neglect to take them all.
6696      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6697      *
6698      * @apiNote Example:
6699      * {@snippet lang="java" :
6700      * // iterative implementation of the factorial function as a loop handle
6701      * static int one(int k) { return 1; }
6702      * static int inc(int i, int acc, int k) { return i + 1; }
6703      * static int mult(int i, int acc, int k) { return i * acc; }
6704      * static boolean pred(int i, int acc, int k) { return i < k; }
6705      * static int fin(int i, int acc, int k) { return acc; }
6706      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6707      * // null initializer for counter, should initialize to 0
6708      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6709      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6710      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6711      * assertEquals(120, loop.invoke(5));
6712      * }
6713      * The same example, dropping arguments and using combinators:
6714      * {@snippet lang="java" :
6715      * // simplified implementation of the factorial function as a loop handle
6716      * static int inc(int i) { return i + 1; } // drop acc, k
6717      * static int mult(int i, int acc) { return i * acc; } //drop k
6718      * static boolean cmp(int i, int k) { return i < k; }
6719      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6720      * // null initializer for counter, should initialize to 0
6721      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6722      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6723      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6724      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6725      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6726      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6727      * assertEquals(720, loop.invoke(6));
6728      * }
6729      * A similar example, using a helper object to hold a loop parameter:
6730      * {@snippet lang="java" :
6731      * // instance-based implementation of the factorial function as a loop handle
6732      * static class FacLoop {
6733      *   final int k;
6734      *   FacLoop(int k) { this.k = k; }
6735      *   int inc(int i) { return i + 1; }
6736      *   int mult(int i, int acc) { return i * acc; }
6737      *   boolean pred(int i) { return i < k; }
6738      *   int fin(int i, int acc) { return acc; }
6739      * }
6740      * // assume MH_FacLoop is a handle to the constructor
6741      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6742      * // null initializer for counter, should initialize to 0
6743      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6744      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6745      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6746      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6747      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6748      * assertEquals(5040, loop.invoke(7));
6749      * }
6750      *
6751      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6752      *
6753      * @return a method handle embodying the looping behavior as defined by the arguments.
6754      *
6755      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6756      *
6757      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6758      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6759      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6760      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6761      * @since 9
6762      */
6763     public static MethodHandle loop(MethodHandle[]... clauses) {
6764         // Step 0: determine clause structure.
6765         loopChecks0(clauses);
6766 
6767         List<MethodHandle> init = new ArrayList<>();
6768         List<MethodHandle> step = new ArrayList<>();
6769         List<MethodHandle> pred = new ArrayList<>();
6770         List<MethodHandle> fini = new ArrayList<>();
6771 
6772         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6773             init.add(clause[0]); // all clauses have at least length 1
6774             step.add(clause.length <= 1 ? null : clause[1]);
6775             pred.add(clause.length <= 2 ? null : clause[2]);
6776             fini.add(clause.length <= 3 ? null : clause[3]);
6777         });
6778 
6779         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6780         final int nclauses = init.size();
6781 
6782         // Step 1A: determine iteration variables (V...).
6783         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6784         for (int i = 0; i < nclauses; ++i) {
6785             MethodHandle in = init.get(i);
6786             MethodHandle st = step.get(i);
6787             if (in == null && st == null) {
6788                 iterationVariableTypes.add(void.class);
6789             } else if (in != null && st != null) {
6790                 loopChecks1a(i, in, st);
6791                 iterationVariableTypes.add(in.type().returnType());
6792             } else {
6793                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6794             }
6795         }
6796         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6797 
6798         // Step 1B: determine loop parameters (A...).
6799         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6800         loopChecks1b(init, commonSuffix);
6801 
6802         // Step 1C: determine loop return type.
6803         // Step 1D: check other types.
6804         // local variable required here; see JDK-8223553
6805         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6806                 .map(MethodType::returnType);
6807         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6808         loopChecks1cd(pred, fini, loopReturnType);
6809 
6810         // Step 2: determine parameter lists.
6811         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6812         commonParameterSequence.addAll(commonSuffix);
6813         loopChecks2(step, pred, fini, commonParameterSequence);
6814         // Step 3: fill in omitted functions.
6815         for (int i = 0; i < nclauses; ++i) {
6816             Class<?> t = iterationVariableTypes.get(i);
6817             if (init.get(i) == null) {
6818                 init.set(i, empty(methodType(t, commonSuffix)));
6819             }
6820             if (step.get(i) == null) {
6821                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6822             }
6823             if (pred.get(i) == null) {
6824                 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
6825             }
6826             if (fini.get(i) == null) {
6827                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6828             }
6829         }
6830 
6831         // Step 4: fill in missing parameter types.
6832         // Also convert all handles to fixed-arity handles.
6833         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6834         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6835         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6836         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6837 
6838         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6839                 allMatch(pl -> pl.equals(commonSuffix));
6840         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6841                 allMatch(pl -> pl.equals(commonParameterSequence));
6842 
6843         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6844     }
6845 
6846     private static void loopChecks0(MethodHandle[][] clauses) {
6847         if (clauses == null || clauses.length == 0) {
6848             throw newIllegalArgumentException("null or no clauses passed");
6849         }
6850         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6851             throw newIllegalArgumentException("null clauses are not allowed");
6852         }
6853         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6854             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6855         }
6856     }
6857 
6858     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6859         if (in.type().returnType() != st.type().returnType()) {
6860             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6861                     st.type().returnType());
6862         }
6863     }
6864 
6865     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6866         return mhs.filter(Objects::nonNull)
6867                 // take only those that can contribute to a common suffix because they are longer than the prefix
6868                 .map(MethodHandle::type)
6869                 .filter(t -> t.parameterCount() > skipSize)
6870                 .max(Comparator.comparingInt(MethodType::parameterCount))
6871                 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount())))
6872                 .orElse(List.of());
6873     }
6874 
6875     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6876         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6877         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6878         return longest1.size() >= longest2.size() ? longest1 : longest2;
6879     }
6880 
6881     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6882         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6883                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6884             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6885                     " (common suffix: " + commonSuffix + ")");
6886         }
6887     }
6888 
6889     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6890         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6891                 anyMatch(t -> t != loopReturnType)) {
6892             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6893                     loopReturnType + ")");
6894         }
6895 
6896         if (pred.stream().noneMatch(Objects::nonNull)) {
6897             throw newIllegalArgumentException("no predicate found", pred);
6898         }
6899         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6900                 anyMatch(t -> t != boolean.class)) {
6901             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6902         }
6903     }
6904 
6905     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6906         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6907                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6908             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6909                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6910         }
6911     }
6912 
6913     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6914         return hs.stream().map(h -> {
6915             int pc = h.type().parameterCount();
6916             int tpsize = targetParams.size();
6917             return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
6918         }).toList();
6919     }
6920 
6921     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6922         return hs.stream().map(MethodHandle::asFixedArity).toList();
6923     }
6924 
6925     /**
6926      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6927      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6928      * <p>
6929      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6930      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6931      * evaluates to {@code true}).
6932      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6933      * <p>
6934      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6935      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6936      * and updated with the value returned from its invocation. The result of loop execution will be
6937      * the final value of the additional loop-local variable (if present).
6938      * <p>
6939      * The following rules hold for these argument handles:<ul>
6940      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6941      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6942      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6943      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6944      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6945      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6946      * It will constrain the parameter lists of the other loop parts.
6947      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6948      * list {@code (A...)} is called the <em>external parameter list</em>.
6949      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6950      * additional state variable of the loop.
6951      * The body must both accept and return a value of this type {@code V}.
6952      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6953      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6954      * <a href="MethodHandles.html#effid">effectively identical</a>
6955      * to the external parameter list {@code (A...)}.
6956      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6957      * {@linkplain #empty default value}.
6958      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6959      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6960      * effectively identical to the internal parameter list.
6961      * </ul>
6962      * <p>
6963      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6964      * <li>The loop handle's result type is the result type {@code V} of the body.
6965      * <li>The loop handle's parameter types are the types {@code (A...)},
6966      * from the external parameter list.
6967      * </ul>
6968      * <p>
6969      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6970      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6971      * passed to the loop.
6972      * {@snippet lang="java" :
6973      * V init(A...);
6974      * boolean pred(V, A...);
6975      * V body(V, A...);
6976      * V whileLoop(A... a...) {
6977      *   V v = init(a...);
6978      *   while (pred(v, a...)) {
6979      *     v = body(v, a...);
6980      *   }
6981      *   return v;
6982      * }
6983      * }
6984      *
6985      * @apiNote Example:
6986      * {@snippet lang="java" :
6987      * // implement the zip function for lists as a loop handle
6988      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6989      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6990      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6991      *   zip.add(a.next());
6992      *   zip.add(b.next());
6993      *   return zip;
6994      * }
6995      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6996      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6997      * List<String> a = Arrays.asList("a", "b", "c", "d");
6998      * List<String> b = Arrays.asList("e", "f", "g", "h");
6999      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
7000      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
7001      * }
7002      *
7003      *
7004      * @apiNote The implementation of this method can be expressed as follows:
7005      * {@snippet lang="java" :
7006      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
7007      *     MethodHandle fini = (body.type().returnType() == void.class
7008      *                         ? null : identity(body.type().returnType()));
7009      *     MethodHandle[]
7010      *         checkExit = { null, null, pred, fini },
7011      *         varBody   = { init, body };
7012      *     return loop(checkExit, varBody);
7013      * }
7014      * }
7015      *
7016      * @param init optional initializer, providing the initial value of the loop variable.
7017      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7018      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7019      *             above for other constraints.
7020      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7021      *             See above for other constraints.
7022      *
7023      * @return a method handle implementing the {@code while} loop as described by the arguments.
7024      * @throws IllegalArgumentException if the rules for the arguments are violated.
7025      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7026      *
7027      * @see #loop(MethodHandle[][])
7028      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
7029      * @since 9
7030      */
7031     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
7032         whileLoopChecks(init, pred, body);
7033         MethodHandle fini = identityOrVoid(body.type().returnType());
7034         MethodHandle[] checkExit = { null, null, pred, fini };
7035         MethodHandle[] varBody = { init, body };
7036         return loop(checkExit, varBody);
7037     }
7038 
7039     /**
7040      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
7041      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7042      * <p>
7043      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
7044      * method will, in each iteration, first execute its body and then evaluate the predicate.
7045      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
7046      * <p>
7047      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
7048      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
7049      * and updated with the value returned from its invocation. The result of loop execution will be
7050      * the final value of the additional loop-local variable (if present).
7051      * <p>
7052      * The following rules hold for these argument handles:<ul>
7053      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7054      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
7055      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7056      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
7057      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
7058      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
7059      * It will constrain the parameter lists of the other loop parts.
7060      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
7061      * list {@code (A...)} is called the <em>external parameter list</em>.
7062      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7063      * additional state variable of the loop.
7064      * The body must both accept and return a value of this type {@code V}.
7065      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7066      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7067      * <a href="MethodHandles.html#effid">effectively identical</a>
7068      * to the external parameter list {@code (A...)}.
7069      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7070      * {@linkplain #empty default value}.
7071      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
7072      * Its parameter list (either empty or of the form {@code (V A*)}) must be
7073      * effectively identical to the internal parameter list.
7074      * </ul>
7075      * <p>
7076      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7077      * <li>The loop handle's result type is the result type {@code V} of the body.
7078      * <li>The loop handle's parameter types are the types {@code (A...)},
7079      * from the external parameter list.
7080      * </ul>
7081      * <p>
7082      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7083      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
7084      * passed to the loop.
7085      * {@snippet lang="java" :
7086      * V init(A...);
7087      * boolean pred(V, A...);
7088      * V body(V, A...);
7089      * V doWhileLoop(A... a...) {
7090      *   V v = init(a...);
7091      *   do {
7092      *     v = body(v, a...);
7093      *   } while (pred(v, a...));
7094      *   return v;
7095      * }
7096      * }
7097      *
7098      * @apiNote Example:
7099      * {@snippet lang="java" :
7100      * // int i = 0; while (i < limit) { ++i; } return i; => limit
7101      * static int zero(int limit) { return 0; }
7102      * static int step(int i, int limit) { return i + 1; }
7103      * static boolean pred(int i, int limit) { return i < limit; }
7104      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
7105      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
7106      * assertEquals(23, loop.invoke(23));
7107      * }
7108      *
7109      *
7110      * @apiNote The implementation of this method can be expressed as follows:
7111      * {@snippet lang="java" :
7112      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7113      *     MethodHandle fini = (body.type().returnType() == void.class
7114      *                         ? null : identity(body.type().returnType()));
7115      *     MethodHandle[] clause = { init, body, pred, fini };
7116      *     return loop(clause);
7117      * }
7118      * }
7119      *
7120      * @param init optional initializer, providing the initial value of the loop variable.
7121      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7122      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7123      *             See above for other constraints.
7124      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7125      *             above for other constraints.
7126      *
7127      * @return a method handle implementing the {@code while} loop as described by the arguments.
7128      * @throws IllegalArgumentException if the rules for the arguments are violated.
7129      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7130      *
7131      * @see #loop(MethodHandle[][])
7132      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
7133      * @since 9
7134      */
7135     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7136         whileLoopChecks(init, pred, body);
7137         MethodHandle fini = identityOrVoid(body.type().returnType());
7138         MethodHandle[] clause = {init, body, pred, fini };
7139         return loop(clause);
7140     }
7141 
7142     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
7143         Objects.requireNonNull(pred);
7144         Objects.requireNonNull(body);
7145         MethodType bodyType = body.type();
7146         Class<?> returnType = bodyType.returnType();
7147         List<Class<?>> innerList = bodyType.parameterList();
7148         List<Class<?>> outerList = innerList;
7149         if (returnType == void.class) {
7150             // OK
7151         } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
7152             // leading V argument missing => error
7153             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7154             throw misMatchedTypes("body function", bodyType, expected);
7155         } else {
7156             outerList = innerList.subList(1, innerList.size());
7157         }
7158         MethodType predType = pred.type();
7159         if (predType.returnType() != boolean.class ||
7160                 !predType.effectivelyIdenticalParameters(0, innerList)) {
7161             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
7162         }
7163         if (init != null) {
7164             MethodType initType = init.type();
7165             if (initType.returnType() != returnType ||
7166                     !initType.effectivelyIdenticalParameters(0, outerList)) {
7167                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7168             }
7169         }
7170     }
7171 
7172     /**
7173      * Constructs a loop that runs a given number of iterations.
7174      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7175      * <p>
7176      * The number of iterations is determined by the {@code iterations} handle evaluation result.
7177      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
7178      * It will be initialized to 0 and incremented by 1 in each iteration.
7179      * <p>
7180      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7181      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7182      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7183      * <p>
7184      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7185      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7186      * iteration variable.
7187      * The result of the loop handle execution will be the final {@code V} value of that variable
7188      * (or {@code void} if there is no {@code V} variable).
7189      * <p>
7190      * The following rules hold for the argument handles:<ul>
7191      * <li>The {@code iterations} handle must not be {@code null}, and must return
7192      * the type {@code int}, referred to here as {@code I} in parameter type lists.
7193      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7194      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7195      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7196      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7197      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7198      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7199      * of types called the <em>internal parameter list</em>.
7200      * It will constrain the parameter lists of the other loop parts.
7201      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7202      * with no additional {@code A} types, then the internal parameter list is extended by
7203      * the argument types {@code A...} of the {@code iterations} handle.
7204      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7205      * list {@code (A...)} is called the <em>external parameter list</em>.
7206      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7207      * additional state variable of the loop.
7208      * The body must both accept a leading parameter and return a value of this type {@code V}.
7209      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7210      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7211      * <a href="MethodHandles.html#effid">effectively identical</a>
7212      * to the external parameter list {@code (A...)}.
7213      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7214      * {@linkplain #empty default value}.
7215      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
7216      * effectively identical to the external parameter list {@code (A...)}.
7217      * </ul>
7218      * <p>
7219      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7220      * <li>The loop handle's result type is the result type {@code V} of the body.
7221      * <li>The loop handle's parameter types are the types {@code (A...)},
7222      * from the external parameter list.
7223      * </ul>
7224      * <p>
7225      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7226      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7227      * arguments passed to the loop.
7228      * {@snippet lang="java" :
7229      * int iterations(A...);
7230      * V init(A...);
7231      * V body(V, int, A...);
7232      * V countedLoop(A... a...) {
7233      *   int end = iterations(a...);
7234      *   V v = init(a...);
7235      *   for (int i = 0; i < end; ++i) {
7236      *     v = body(v, i, a...);
7237      *   }
7238      *   return v;
7239      * }
7240      * }
7241      *
7242      * @apiNote Example with a fully conformant body method:
7243      * {@snippet lang="java" :
7244      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7245      * // => a variation on a well known theme
7246      * static String step(String v, int counter, String init) { return "na " + v; }
7247      * // assume MH_step is a handle to the method above
7248      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
7249      * MethodHandle start = MethodHandles.identity(String.class);
7250      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
7251      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
7252      * }
7253      *
7254      * @apiNote Example with the simplest possible body method type,
7255      * and passing the number of iterations to the loop invocation:
7256      * {@snippet lang="java" :
7257      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7258      * // => a variation on a well known theme
7259      * static String step(String v, int counter ) { return "na " + v; }
7260      * // assume MH_step is a handle to the method above
7261      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
7262      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
7263      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
7264      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
7265      * }
7266      *
7267      * @apiNote Example that treats the number of iterations, string to append to, and string to append
7268      * as loop parameters:
7269      * {@snippet lang="java" :
7270      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7271      * // => a variation on a well known theme
7272      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
7273      * // assume MH_step is a handle to the method above
7274      * MethodHandle count = MethodHandles.identity(int.class);
7275      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
7276      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
7277      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
7278      * }
7279      *
7280      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
7281      * to enforce a loop type:
7282      * {@snippet lang="java" :
7283      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7284      * // => a variation on a well known theme
7285      * static String step(String v, int counter, String pre) { return pre + " " + v; }
7286      * // assume MH_step is a handle to the method above
7287      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
7288      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
7289      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
7290      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
7291      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
7292      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
7293      * }
7294      *
7295      * @apiNote The implementation of this method can be expressed as follows:
7296      * {@snippet lang="java" :
7297      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7298      *     return countedLoop(empty(iterations.type()), iterations, init, body);
7299      * }
7300      * }
7301      *
7302      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
7303      *                   result type must be {@code int}. See above for other constraints.
7304      * @param init optional initializer, providing the initial value of the loop variable.
7305      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7306      * @param body body of the loop, which may not be {@code null}.
7307      *             It controls the loop parameters and result type in the standard case (see above for details).
7308      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7309      *             and may accept any number of additional types.
7310      *             See above for other constraints.
7311      *
7312      * @return a method handle representing the loop.
7313      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7314      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7315      *
7316      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7317      * @since 9
7318      */
7319     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7320         return countedLoop(empty(iterations.type()), iterations, init, body);
7321     }
7322 
7323     /**
7324      * Constructs a loop that counts over a range of numbers.
7325      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7326      * <p>
7327      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7328      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7329      * values of the loop counter.
7330      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7331      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7332      * <p>
7333      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7334      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7335      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7336      * <p>
7337      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7338      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7339      * iteration variable.
7340      * The result of the loop handle execution will be the final {@code V} value of that variable
7341      * (or {@code void} if there is no {@code V} variable).
7342      * <p>
7343      * The following rules hold for the argument handles:<ul>
7344      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7345      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7346      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7347      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7348      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7349      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7350      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7351      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7352      * of types called the <em>internal parameter list</em>.
7353      * It will constrain the parameter lists of the other loop parts.
7354      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7355      * with no additional {@code A} types, then the internal parameter list is extended by
7356      * the argument types {@code A...} of the {@code end} handle.
7357      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7358      * list {@code (A...)} is called the <em>external parameter list</em>.
7359      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7360      * additional state variable of the loop.
7361      * The body must both accept a leading parameter and return a value of this type {@code V}.
7362      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7363      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7364      * <a href="MethodHandles.html#effid">effectively identical</a>
7365      * to the external parameter list {@code (A...)}.
7366      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7367      * {@linkplain #empty default value}.
7368      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7369      * effectively identical to the external parameter list {@code (A...)}.
7370      * <li>Likewise, the parameter list of {@code end} must be effectively identical
7371      * to the external parameter list.
7372      * </ul>
7373      * <p>
7374      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7375      * <li>The loop handle's result type is the result type {@code V} of the body.
7376      * <li>The loop handle's parameter types are the types {@code (A...)},
7377      * from the external parameter list.
7378      * </ul>
7379      * <p>
7380      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7381      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7382      * arguments passed to the loop.
7383      * {@snippet lang="java" :
7384      * int start(A...);
7385      * int end(A...);
7386      * V init(A...);
7387      * V body(V, int, A...);
7388      * V countedLoop(A... a...) {
7389      *   int e = end(a...);
7390      *   int s = start(a...);
7391      *   V v = init(a...);
7392      *   for (int i = s; i < e; ++i) {
7393      *     v = body(v, i, a...);
7394      *   }
7395      *   return v;
7396      * }
7397      * }
7398      *
7399      * @apiNote The implementation of this method can be expressed as follows:
7400      * {@snippet lang="java" :
7401      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7402      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7403      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7404      *     // the following semantics:
7405      *     // MH_increment: (int limit, int counter) -> counter + 1
7406      *     // MH_predicate: (int limit, int counter) -> counter < limit
7407      *     Class<?> counterType = start.type().returnType();  // int
7408      *     Class<?> returnType = body.type().returnType();
7409      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7410      *     if (returnType != void.class) {  // ignore the V variable
7411      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7412      *         pred = dropArguments(pred, 1, returnType);  // ditto
7413      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7414      *     }
7415      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
7416      *     MethodHandle[]
7417      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7418      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
7419      *         indexVar   = { start, incr };           // i = start(); i = i + 1
7420      *     return loop(loopLimit, bodyClause, indexVar);
7421      * }
7422      * }
7423      *
7424      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7425      *              See above for other constraints.
7426      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7427      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
7428      * @param init optional initializer, providing the initial value of the loop variable.
7429      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7430      * @param body body of the loop, which may not be {@code null}.
7431      *             It controls the loop parameters and result type in the standard case (see above for details).
7432      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7433      *             and may accept any number of additional types.
7434      *             See above for other constraints.
7435      *
7436      * @return a method handle representing the loop.
7437      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7438      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7439      *
7440      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7441      * @since 9
7442      */
7443     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7444         countedLoopChecks(start, end, init, body);
7445         Class<?> counterType = start.type().returnType();  // int, but who's counting?
7446         Class<?> limitType   = end.type().returnType();    // yes, int again
7447         Class<?> returnType  = body.type().returnType();
7448         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7449         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7450         MethodHandle retv = null;
7451         if (returnType != void.class) {
7452             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7453             pred = dropArguments(pred, 1, returnType);  // ditto
7454             retv = dropArguments(identity(returnType), 0, counterType);
7455         }
7456         body = dropArguments(body, 0, counterType);  // ignore the limit variable
7457         MethodHandle[]
7458             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7459             bodyClause = { init, body },            // v = init(); v = body(v, i)
7460             indexVar   = { start, incr };           // i = start(); i = i + 1
7461         return loop(loopLimit, bodyClause, indexVar);
7462     }
7463 
7464     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7465         Objects.requireNonNull(start);
7466         Objects.requireNonNull(end);
7467         Objects.requireNonNull(body);
7468         Class<?> counterType = start.type().returnType();
7469         if (counterType != int.class) {
7470             MethodType expected = start.type().changeReturnType(int.class);
7471             throw misMatchedTypes("start function", start.type(), expected);
7472         } else if (end.type().returnType() != counterType) {
7473             MethodType expected = end.type().changeReturnType(counterType);
7474             throw misMatchedTypes("end function", end.type(), expected);
7475         }
7476         MethodType bodyType = body.type();
7477         Class<?> returnType = bodyType.returnType();
7478         List<Class<?>> innerList = bodyType.parameterList();
7479         // strip leading V value if present
7480         int vsize = (returnType == void.class ? 0 : 1);
7481         if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7482             // argument list has no "V" => error
7483             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7484             throw misMatchedTypes("body function", bodyType, expected);
7485         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7486             // missing I type => error
7487             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7488             throw misMatchedTypes("body function", bodyType, expected);
7489         }
7490         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7491         if (outerList.isEmpty()) {
7492             // special case; take lists from end handle
7493             outerList = end.type().parameterList();
7494             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7495         }
7496         MethodType expected = methodType(counterType, outerList);
7497         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7498             throw misMatchedTypes("start parameter types", start.type(), expected);
7499         }
7500         if (end.type() != start.type() &&
7501             !end.type().effectivelyIdenticalParameters(0, outerList)) {
7502             throw misMatchedTypes("end parameter types", end.type(), expected);
7503         }
7504         if (init != null) {
7505             MethodType initType = init.type();
7506             if (initType.returnType() != returnType ||
7507                 !initType.effectivelyIdenticalParameters(0, outerList)) {
7508                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7509             }
7510         }
7511     }
7512 
7513     /**
7514      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7515      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7516      * <p>
7517      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7518      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7519      * <p>
7520      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7521      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7522      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7523      * <p>
7524      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7525      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7526      * iteration variable.
7527      * The result of the loop handle execution will be the final {@code V} value of that variable
7528      * (or {@code void} if there is no {@code V} variable).
7529      * <p>
7530      * The following rules hold for the argument handles:<ul>
7531      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7532      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7533      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7534      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7535      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7536      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7537      * of types called the <em>internal parameter list</em>.
7538      * It will constrain the parameter lists of the other loop parts.
7539      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7540      * with no additional {@code A} types, then the internal parameter list is extended by
7541      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7542      * single type {@code Iterable} is added and constitutes the {@code A...} list.
7543      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7544      * list {@code (A...)} is called the <em>external parameter list</em>.
7545      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7546      * additional state variable of the loop.
7547      * The body must both accept a leading parameter and return a value of this type {@code V}.
7548      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7549      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7550      * <a href="MethodHandles.html#effid">effectively identical</a>
7551      * to the external parameter list {@code (A...)}.
7552      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7553      * {@linkplain #empty default value}.
7554      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7555      * type {@code java.util.Iterator} or a subtype thereof.
7556      * The iterator it produces when the loop is executed will be assumed
7557      * to yield values which can be converted to type {@code T}.
7558      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7559      * effectively identical to the external parameter list {@code (A...)}.
7560      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7561      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7562      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7563      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7564      * the {@link MethodHandle#asType asType} conversion method.
7565      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7566      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7567      * </ul>
7568      * <p>
7569      * The type {@code T} may be either a primitive or reference.
7570      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7571      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7572      * as if by the {@link MethodHandle#asType asType} conversion method.
7573      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7574      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7575      * <p>
7576      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7577      * <li>The loop handle's result type is the result type {@code V} of the body.
7578      * <li>The loop handle's parameter types are the types {@code (A...)},
7579      * from the external parameter list.
7580      * </ul>
7581      * <p>
7582      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7583      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7584      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7585      * {@snippet lang="java" :
7586      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7587      * V init(A...);
7588      * V body(V,T,A...);
7589      * V iteratedLoop(A... a...) {
7590      *   Iterator<T> it = iterator(a...);
7591      *   V v = init(a...);
7592      *   while (it.hasNext()) {
7593      *     T t = it.next();
7594      *     v = body(v, t, a...);
7595      *   }
7596      *   return v;
7597      * }
7598      * }
7599      *
7600      * @apiNote Example:
7601      * {@snippet lang="java" :
7602      * // get an iterator from a list
7603      * static List<String> reverseStep(List<String> r, String e) {
7604      *   r.add(0, e);
7605      *   return r;
7606      * }
7607      * static List<String> newArrayList() { return new ArrayList<>(); }
7608      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7609      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7610      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7611      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7612      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7613      * }
7614      *
7615      * @apiNote The implementation of this method can be expressed approximately as follows:
7616      * {@snippet lang="java" :
7617      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7618      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7619      *     Class<?> returnType = body.type().returnType();
7620      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7621      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7622      *     MethodHandle retv = null, step = body, startIter = iterator;
7623      *     if (returnType != void.class) {
7624      *         // the simple thing first:  in (I V A...), drop the I to get V
7625      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7626      *         // body type signature (V T A...), internal loop types (I V A...)
7627      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7628      *     }
7629      *     if (startIter == null)  startIter = MH_getIter;
7630      *     MethodHandle[]
7631      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7632      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7633      *     return loop(iterVar, bodyClause);
7634      * }
7635      * }
7636      *
7637      * @param iterator an optional handle to return the iterator to start the loop.
7638      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7639      *                 See above for other constraints.
7640      * @param init optional initializer, providing the initial value of the loop variable.
7641      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7642      * @param body body of the loop, which may not be {@code null}.
7643      *             It controls the loop parameters and result type in the standard case (see above for details).
7644      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7645      *             and may accept any number of additional types.
7646      *             See above for other constraints.
7647      *
7648      * @return a method handle embodying the iteration loop functionality.
7649      * @throws NullPointerException if the {@code body} handle is {@code null}.
7650      * @throws IllegalArgumentException if any argument violates the above requirements.
7651      *
7652      * @since 9
7653      */
7654     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7655         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7656         Class<?> returnType = body.type().returnType();
7657         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7658         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7659         MethodHandle startIter;
7660         MethodHandle nextVal;
7661         {
7662             MethodType iteratorType;
7663             if (iterator == null) {
7664                 // derive argument type from body, if available, else use Iterable
7665                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7666                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7667             } else {
7668                 // force return type to the internal iterator class
7669                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7670                 startIter = iterator;
7671             }
7672             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7673             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7674 
7675             // perform the asType transforms under an exception transformer, as per spec.:
7676             try {
7677                 startIter = startIter.asType(iteratorType);
7678                 nextVal = nextRaw.asType(nextValType);
7679             } catch (WrongMethodTypeException ex) {
7680                 throw new IllegalArgumentException(ex);
7681             }
7682         }
7683 
7684         MethodHandle retv = null, step = body;
7685         if (returnType != void.class) {
7686             // the simple thing first:  in (I V A...), drop the I to get V
7687             retv = dropArguments(identity(returnType), 0, Iterator.class);
7688             // body type signature (V T A...), internal loop types (I V A...)
7689             step = swapArguments(body, 0, 1);  // swap V <-> T
7690         }
7691 
7692         MethodHandle[]
7693             iterVar    = { startIter, null, hasNext, retv },
7694             bodyClause = { init, filterArgument(step, 0, nextVal) };
7695         return loop(iterVar, bodyClause);
7696     }
7697 
7698     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7699         Objects.requireNonNull(body);
7700         MethodType bodyType = body.type();
7701         Class<?> returnType = bodyType.returnType();
7702         List<Class<?>> internalParamList = bodyType.parameterList();
7703         // strip leading V value if present
7704         int vsize = (returnType == void.class ? 0 : 1);
7705         if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7706             // argument list has no "V" => error
7707             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7708             throw misMatchedTypes("body function", bodyType, expected);
7709         } else if (internalParamList.size() <= vsize) {
7710             // missing T type => error
7711             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7712             throw misMatchedTypes("body function", bodyType, expected);
7713         }
7714         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7715         Class<?> iterableType = null;
7716         if (iterator != null) {
7717             // special case; if the body handle only declares V and T then
7718             // the external parameter list is obtained from iterator handle
7719             if (externalParamList.isEmpty()) {
7720                 externalParamList = iterator.type().parameterList();
7721             }
7722             MethodType itype = iterator.type();
7723             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7724                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7725             }
7726             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7727                 MethodType expected = methodType(itype.returnType(), externalParamList);
7728                 throw misMatchedTypes("iterator parameters", itype, expected);
7729             }
7730         } else {
7731             if (externalParamList.isEmpty()) {
7732                 // special case; if the iterator handle is null and the body handle
7733                 // only declares V and T then the external parameter list consists
7734                 // of Iterable
7735                 externalParamList = List.of(Iterable.class);
7736                 iterableType = Iterable.class;
7737             } else {
7738                 // special case; if the iterator handle is null and the external
7739                 // parameter list is not empty then the first parameter must be
7740                 // assignable to Iterable
7741                 iterableType = externalParamList.get(0);
7742                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7743                     throw newIllegalArgumentException(
7744                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7745                 }
7746             }
7747         }
7748         if (init != null) {
7749             MethodType initType = init.type();
7750             if (initType.returnType() != returnType ||
7751                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7752                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7753             }
7754         }
7755         return iterableType;  // help the caller a bit
7756     }
7757 
7758     /*non-public*/
7759     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7760         // there should be a better way to uncross my wires
7761         int arity = mh.type().parameterCount();
7762         int[] order = new int[arity];
7763         for (int k = 0; k < arity; k++)  order[k] = k;
7764         order[i] = j; order[j] = i;
7765         Class<?>[] types = mh.type().parameterArray();
7766         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7767         MethodType swapType = methodType(mh.type().returnType(), types);
7768         return permuteArguments(mh, swapType, order);
7769     }
7770 
7771     /**
7772      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7773      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7774      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7775      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7776      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7777      * {@code try-finally} handle.
7778      * <p>
7779      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7780      * The first is the exception thrown during the
7781      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7782      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7783      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7784      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7785      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7786      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7787      * <p>
7788      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7789      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7790      * two extra leading parameters:<ul>
7791      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7792      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7793      * the result from the execution of the {@code target} handle.
7794      * This parameter is not present if the {@code target} returns {@code void}.
7795      * </ul>
7796      * <p>
7797      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7798      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7799      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7800      * the cleanup.
7801      * {@snippet lang="java" :
7802      * V target(A..., B...);
7803      * V cleanup(Throwable, V, A...);
7804      * V adapter(A... a, B... b) {
7805      *   V result = (zero value for V);
7806      *   Throwable throwable = null;
7807      *   try {
7808      *     result = target(a..., b...);
7809      *   } catch (Throwable t) {
7810      *     throwable = t;
7811      *     throw t;
7812      *   } finally {
7813      *     result = cleanup(throwable, result, a...);
7814      *   }
7815      *   return result;
7816      * }
7817      * }
7818      * <p>
7819      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7820      * be modified by execution of the target, and so are passed unchanged
7821      * from the caller to the cleanup, if it is invoked.
7822      * <p>
7823      * The target and cleanup must return the same type, even if the cleanup
7824      * always throws.
7825      * To create such a throwing cleanup, compose the cleanup logic
7826      * with {@link #throwException throwException},
7827      * in order to create a method handle of the correct return type.
7828      * <p>
7829      * Note that {@code tryFinally} never converts exceptions into normal returns.
7830      * In rare cases where exceptions must be converted in that way, first wrap
7831      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7832      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7833      * <p>
7834      * It is recommended that the first parameter type of {@code cleanup} be
7835      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7836      * {@code cleanup} will always be invoked with whatever exception that
7837      * {@code target} throws.  Declaring a narrower type may result in a
7838      * {@code ClassCastException} being thrown by the {@code try-finally}
7839      * handle if the type of the exception thrown by {@code target} is not
7840      * assignable to the first parameter type of {@code cleanup}.  Note that
7841      * various exception types of {@code VirtualMachineError},
7842      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7843      * thrown by almost any kind of Java code, and a finally clause that
7844      * catches (say) only {@code IOException} would mask any of the others
7845      * behind a {@code ClassCastException}.
7846      *
7847      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7848      * @param cleanup the handle that is invoked in the finally block.
7849      *
7850      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7851      * @throws NullPointerException if any argument is null
7852      * @throws IllegalArgumentException if {@code cleanup} does not accept
7853      *          the required leading arguments, or if the method handle types do
7854      *          not match in their return types and their
7855      *          corresponding trailing parameters
7856      *
7857      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7858      * @since 9
7859      */
7860     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7861         Class<?>[] targetParamTypes = target.type().ptypes();
7862         Class<?> rtype = target.type().returnType();
7863 
7864         tryFinallyChecks(target, cleanup);
7865 
7866         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7867         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7868         // target parameter list.
7869         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false);
7870 
7871         // Ensure that the intrinsic type checks the instance thrown by the
7872         // target against the first parameter of cleanup
7873         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7874 
7875         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7876         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7877     }
7878 
7879     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7880         Class<?> rtype = target.type().returnType();
7881         if (rtype != cleanup.type().returnType()) {
7882             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7883         }
7884         MethodType cleanupType = cleanup.type();
7885         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7886             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7887         }
7888         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7889             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7890         }
7891         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7892         // target parameter list.
7893         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7894         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7895             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7896                     cleanup.type(), target.type());
7897         }
7898     }
7899 
7900     /**
7901      * Creates a table switch method handle, which can be used to switch over a set of target
7902      * method handles, based on a given target index, called selector.
7903      * <p>
7904      * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7905      * and where {@code N} is the number of target method handles, the table switch method
7906      * handle will invoke the n-th target method handle from the list of target method handles.
7907      * <p>
7908      * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7909      * method handle will invoke the given fallback method handle.
7910      * <p>
7911      * All method handles passed to this method must have the same type, with the additional
7912      * requirement that the leading parameter be of type {@code int}. The leading parameter
7913      * represents the selector.
7914      * <p>
7915      * Any trailing parameters present in the type will appear on the returned table switch
7916      * method handle as well. Any arguments assigned to these parameters will be forwarded,
7917      * together with the selector value, to the selected method handle when invoking it.
7918      *
7919      * @apiNote Example:
7920      * The cases each drop the {@code selector} value they are given, and take an additional
7921      * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7922      * to a specific constant label string for each case:
7923      * {@snippet lang="java" :
7924      * MethodHandles.Lookup lookup = MethodHandles.lookup();
7925      * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7926      *         MethodType.methodType(String.class, String.class));
7927      * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7928      *
7929      * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7930      * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7931      * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7932      *
7933      * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7934      *     caseDefault,
7935      *     case0,
7936      *     case1
7937      * );
7938      *
7939      * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7940      * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7941      * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7942      * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7943      * }
7944      *
7945      * @param fallback the fallback method handle that is called when the selector is not
7946      *                 within the range {@code [0, N)}.
7947      * @param targets array of target method handles.
7948      * @return the table switch method handle.
7949      * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7950      *                              any of the elements of the {@code targets} array are
7951      *                              {@code null}.
7952      * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7953      *                                  parameter of the fallback handle or any of the target
7954      *                                  handles is not {@code int}, or if the types of
7955      *                                  the fallback handle and all of target handles are
7956      *                                  not the same.
7957      */
7958     public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7959         Objects.requireNonNull(fallback);
7960         Objects.requireNonNull(targets);
7961         targets = targets.clone();
7962         MethodType type = tableSwitchChecks(fallback, targets);
7963         return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7964     }
7965 
7966     private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7967         if (caseActions.length == 0)
7968             throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7969 
7970         MethodType expectedType = defaultCase.type();
7971 
7972         if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7973             throw new IllegalArgumentException(
7974                 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7975 
7976         for (MethodHandle mh : caseActions) {
7977             Objects.requireNonNull(mh);
7978             if (mh.type() != expectedType)
7979                 throw new IllegalArgumentException(
7980                     "Case actions must have the same type: " + Arrays.toString(caseActions));
7981         }
7982 
7983         return expectedType;
7984     }
7985 
7986     /**
7987      * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions.
7988      * <p>
7989      * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where
7990      * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed
7991      * to the target var handle.
7992      * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from
7993      * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function)
7994      * is processed using the second filter and returned to the caller. More advanced access mode types, such as
7995      * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time.
7996      * <p>
7997      * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and
7998      * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case,
7999      * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which
8000      * will be appended to the coordinates of the target var handle).
8001      * <p>
8002      * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will
8003      * throw an {@link IllegalStateException}.
8004      * <p>
8005      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8006      * atomic access guarantees as those featured by the target var handle.
8007      *
8008      * @param target the target var handle
8009      * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target}
8010      * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S}
8011      * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions.
8012      * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types
8013      * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle,
8014      * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions.
8015      * @throws NullPointerException if any of the arguments is {@code null}.
8016      * @since 22
8017      */
8018     public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
8019         return VarHandles.filterValue(target, filterToTarget, filterFromTarget);
8020     }
8021 
8022     /**
8023      * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions.
8024      * <p>
8025      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values
8026      * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types
8027      * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the
8028      * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered
8029      * by the adaptation) to the target var handle.
8030      * <p>
8031      * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn},
8032      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
8033      * <p>
8034      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8035      * throw an {@link IllegalStateException}.
8036      * <p>
8037      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8038      * atomic access guarantees as those featured by the target var handle.
8039      *
8040      * @param target the target var handle
8041      * @param pos the position of the first coordinate to be transformed
8042      * @param filters the unary functions which are used to transform coordinates starting at position {@code pos}
8043      * @return an adapter var handle which accepts new coordinate types, applying the provided transformation
8044      * to the new coordinate values.
8045      * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types
8046      * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting
8047      * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8048      * or if more filters are provided than the actual number of coordinate types available starting at {@code pos},
8049      * or if it's determined that any of the filters throws any checked exceptions.
8050      * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}.
8051      * @since 22
8052      */
8053     public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
8054         return VarHandles.filterCoordinates(target, pos, filters);
8055     }
8056 
8057     /**
8058      * Provides a target var handle with one or more <em>bound coordinates</em>
8059      * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less
8060      * coordinate types than the target var handle.
8061      * <p>
8062      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values
8063      * are joined with bound coordinate values, and then passed to the target var handle.
8064      * <p>
8065      * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn },
8066      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
8067      * <p>
8068      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8069      * atomic access guarantees as those featured by the target var handle.
8070      *
8071      * @param target the var handle to invoke after the bound coordinates are inserted
8072      * @param pos the position of the first coordinate to be inserted
8073      * @param values the series of bound coordinates to insert
8074      * @return an adapter var handle which inserts additional coordinates,
8075      *         before calling the target var handle
8076      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8077      * or if more values are provided than the actual number of coordinate types available starting at {@code pos}.
8078      * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types
8079      * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos}
8080      * of the target var handle.
8081      * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}.
8082      * @since 22
8083      */
8084     public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
8085         return VarHandles.insertCoordinates(target, pos, values);
8086     }
8087 
8088     /**
8089      * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them
8090      * so that the new coordinates match the provided ones.
8091      * <p>
8092      * The given array controls the reordering.
8093      * Call {@code #I} the number of incoming coordinates (the value
8094      * {@code newCoordinates.size()}), and call {@code #O} the number
8095      * of outgoing coordinates (the number of coordinates associated with the target var handle).
8096      * Then the length of the reordering array must be {@code #O},
8097      * and each element must be a non-negative number less than {@code #I}.
8098      * For every {@code N} less than {@code #O}, the {@code N}-th
8099      * outgoing coordinate will be taken from the {@code I}-th incoming
8100      * coordinate, where {@code I} is {@code reorder[N]}.
8101      * <p>
8102      * No coordinate value conversions are applied.
8103      * The type of each incoming coordinate, as determined by {@code newCoordinates},
8104      * must be identical to the type of the corresponding outgoing coordinate
8105      * in the target var handle.
8106      * <p>
8107      * The reordering array need not specify an actual permutation.
8108      * An incoming coordinate will be duplicated if its index appears
8109      * more than once in the array, and an incoming coordinate will be dropped
8110      * if its index does not appear in the array.
8111      * <p>
8112      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8113      * atomic access guarantees as those featured by the target var handle.
8114      * @param target the var handle to invoke after the coordinates have been reordered
8115      * @param newCoordinates the new coordinate types
8116      * @param reorder an index array which controls the reordering
8117      * @return an adapter var handle which re-arranges the incoming coordinate values,
8118      * before calling the target var handle
8119      * @throws IllegalArgumentException if the index array length is not equal to
8120      * the number of coordinates of the target var handle, or if any index array element is not a valid index for
8121      * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in
8122      * the target var handle and in {@code newCoordinates} are not identical.
8123      * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}.
8124      * @since 22
8125      */
8126     public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
8127         return VarHandles.permuteCoordinates(target, newCoordinates, reorder);
8128     }
8129 
8130     /**
8131      * Adapts a target var handle by pre-processing
8132      * a sub-sequence of its coordinate values with a filter (a method handle).
8133      * The pre-processed coordinates are replaced by the result (if any) of the
8134      * filter function and the target var handle is then called on the modified (usually shortened)
8135      * coordinate list.
8136      * <p>
8137      * If {@code R} is the return type of the filter, then:
8138      * <ul>
8139      * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in
8140      * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos}
8141      * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first,
8142      * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the
8143      * target var handle.</li>
8144      * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the
8145      * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle
8146      * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a
8147      * downstream invocation of the target var handle.</li>
8148      * </ul>
8149      * <p>
8150      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8151      * throw an {@link IllegalStateException}.
8152      * <p>
8153      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8154      * atomic access guarantees as those featured by the target var handle.
8155      *
8156      * @param target the var handle to invoke after the coordinates have been filtered
8157      * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted
8158      * @param filter the filter method handle
8159      * @return an adapter var handle which filters the incoming coordinate values,
8160      * before calling the target var handle
8161      * @throws IllegalArgumentException if the return type of {@code filter}
8162      * is not void, and it is not the same as the {@code pos} coordinate of the target var handle,
8163      * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8164      * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>,
8165      * or if it's determined that {@code filter} throws any checked exceptions.
8166      * @throws NullPointerException if any of the arguments is {@code null}.
8167      * @since 22
8168      */
8169     public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
8170         return VarHandles.collectCoordinates(target, pos, filter);
8171     }
8172 
8173     /**
8174      * Returns a var handle which will discard some dummy coordinates before delegating to the
8175      * target var handle. As a consequence, the resulting var handle will feature more
8176      * coordinate types than the target var handle.
8177      * <p>
8178      * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the
8179      * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede
8180      * the target's real arguments; if {@code pos} is <i>N</i> they will come after.
8181      * <p>
8182      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8183      * atomic access guarantees as those featured by the target var handle.
8184      *
8185      * @param target the var handle to invoke after the dummy coordinates are dropped
8186      * @param pos position of the first coordinate to drop (zero for the leftmost)
8187      * @param valueTypes the type(s) of the coordinate(s) to drop
8188      * @return an adapter var handle which drops some dummy coordinates,
8189      *         before calling the target var handle
8190      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive.
8191      * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}.
8192      * @since 22
8193      */
8194     public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
8195         return VarHandles.dropCoordinates(target, pos, valueTypes);
8196     }
8197 }