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.foreign.Utils;
  30 import jdk.internal.javac.PreviewFeature;
  31 import jdk.internal.misc.Unsafe;
  32 import jdk.internal.misc.VM;
  33 import jdk.internal.org.objectweb.asm.ClassReader;
  34 import jdk.internal.org.objectweb.asm.Opcodes;
  35 import jdk.internal.org.objectweb.asm.Type;
  36 import jdk.internal.reflect.CallerSensitive;
  37 import jdk.internal.reflect.CallerSensitiveAdapter;
  38 import jdk.internal.reflect.Reflection;
  39 import jdk.internal.util.ClassFileDumper;
  40 import jdk.internal.vm.annotation.ForceInline;
  41 import sun.invoke.util.ValueConversions;
  42 import sun.invoke.util.VerifyAccess;
  43 import sun.invoke.util.Wrapper;
  44 import sun.reflect.misc.ReflectUtil;
  45 import sun.security.util.SecurityConstants;
  46 
  47 import java.lang.constant.ConstantDescs;
  48 import java.lang.foreign.GroupLayout;
  49 import java.lang.foreign.MemoryLayout;
  50 import java.lang.foreign.MemorySegment;
  51 import java.lang.foreign.ValueLayout;
  52 import java.lang.invoke.LambdaForm.BasicType;
  53 import java.lang.reflect.Constructor;
  54 import java.lang.reflect.Field;
  55 import java.lang.reflect.Member;
  56 import java.lang.reflect.Method;
  57 import java.lang.reflect.Modifier;
  58 import java.nio.ByteOrder;
  59 import java.security.ProtectionDomain;
  60 import java.util.ArrayList;
  61 import java.util.Arrays;
  62 import java.util.BitSet;
  63 import java.util.Comparator;
  64 import java.util.Iterator;
  65 import java.util.List;
  66 import java.util.Objects;
  67 import java.util.Set;
  68 import java.util.concurrent.ConcurrentHashMap;
  69 import java.util.stream.Stream;
  70 
  71 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
  72 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  73 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  74 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
  75 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  76 import static java.lang.invoke.MethodHandleStatics.newInternalError;
  77 import static java.lang.invoke.MethodType.methodType;
  78 
  79 /**
  80  * This class consists exclusively of static methods that operate on or return
  81  * method handles. They fall into several categories:
  82  * <ul>
  83  * <li>Lookup methods which help create method handles for methods and fields.
  84  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  85  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  86  * </ul>
  87  * A lookup, combinator, or factory method will fail and throw an
  88  * {@code IllegalArgumentException} if the created method handle's type
  89  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  90  *
  91  * @author John Rose, JSR 292 EG
  92  * @since 1.7
  93  */
  94 public class MethodHandles {
  95 
  96     private MethodHandles() { }  // do not instantiate
  97 
  98     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  99 
 100     // See IMPL_LOOKUP below.
 101 
 102     //// Method handle creation from ordinary methods.
 103 
 104     /**
 105      * Returns a {@link Lookup lookup object} with
 106      * full capabilities to emulate all supported bytecode behaviors of the caller.
 107      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
 108      * Factory methods on the lookup object can create
 109      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
 110      * for any member that the caller has access to via bytecodes,
 111      * including protected and private fields and methods.
 112      * This lookup object is created by the original lookup class
 113      * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
 114      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 115      * Do not store it in place where untrusted code can access it.
 116      * <p>
 117      * This method is caller sensitive, which means that it may return different
 118      * values to different callers.
 119      * In cases where {@code MethodHandles.lookup} is called from a context where
 120      * there is no caller frame on the stack (e.g. when called directly
 121      * from a JNI attached thread), {@code IllegalCallerException} is thrown.
 122      * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will
 123      * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()}
 124      * to obtain a low-privileged lookup instead.
 125      * @return a lookup object for the caller of this method, with
 126      * {@linkplain Lookup#ORIGINAL original} and
 127      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
 128      * @throws IllegalCallerException if there is no caller frame on the stack.
 129      */
 130     @CallerSensitive
 131     @ForceInline // to ensure Reflection.getCallerClass optimization
 132     public static Lookup lookup() {
 133         final Class<?> c = Reflection.getCallerClass();
 134         if (c == null) {
 135             throw new IllegalCallerException("no caller frame");
 136         }
 137         return new Lookup(c);
 138     }
 139 
 140     /**
 141      * This lookup method is the alternate implementation of
 142      * the lookup method with a leading caller class argument which is
 143      * non-caller-sensitive.  This method is only invoked by reflection
 144      * and method handle.
 145      */
 146     @CallerSensitiveAdapter
 147     private static Lookup lookup(Class<?> caller) {
 148         if (caller.getClassLoader() == null) {
 149             throw newInternalError("calling lookup() reflectively is not supported: "+caller);
 150         }
 151         return new Lookup(caller);
 152     }
 153 
 154     /**
 155      * Returns a {@link Lookup lookup object} which is trusted minimally.
 156      * The lookup has the {@code UNCONDITIONAL} mode.
 157      * It can only be used to create method handles to public members of
 158      * public classes in packages that are exported unconditionally.
 159      * <p>
 160      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 161      * of this lookup object will be {@link java.lang.Object}.
 162      *
 163      * @apiNote The use of Object is conventional, and because the lookup modes are
 164      * limited, there is no special access provided to the internals of Object, its package
 165      * or its module.  This public lookup object or other lookup object with
 166      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 167      * is not used to determine the lookup context.
 168      *
 169      * <p style="font-size:smaller;">
 170      * <em>Discussion:</em>
 171      * The lookup class can be changed to any other class {@code C} using an expression of the form
 172      * {@link Lookup#in publicLookup().in(C.class)}.
 173      * A public lookup object is always subject to
 174      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 175      * Also, it cannot access
 176      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 177      * @return a lookup object which is trusted minimally
 178      *
 179      * @revised 9
 180      */
 181     public static Lookup publicLookup() {
 182         return Lookup.PUBLIC_LOOKUP;
 183     }
 184 
 185     /**
 186      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 187      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 188      * The returned lookup object can provide access to classes in modules and packages,
 189      * and members of those classes, outside the normal rules of Java access control,
 190      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 191      * <p>
 192      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 193      * allowed to do deep reflection on module {@code M2} and package of the target class
 194      * if and only if all of the following conditions are {@code true}:
 195      * <ul>
 196      * <li>If there is a security manager, its {@code checkPermission} method is
 197      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 198      * that must return normally.
 199      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 200      * full privilege access}.  Specifically:
 201      *   <ul>
 202      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 203      *         (This is because otherwise there would be no way to ensure the original lookup
 204      *         creator was a member of any particular module, and so any subsequent checks
 205      *         for readability and qualified exports would become ineffective.)
 206      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 207      *         (This is because an application intending to share intra-module access
 208      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 209      *         deep reflection to its own module.)
 210      *   </ul>
 211      * <li>The target class must be a proper class, not a primitive or array class.
 212      * (Thus, {@code M2} is well-defined.)
 213      * <li>If the caller module {@code M1} differs from
 214      * the target module {@code M2} then both of the following must be true:
 215      *   <ul>
 216      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 217      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 218      *         containing the target class to at least {@code M1}.</li>
 219      *   </ul>
 220      * </ul>
 221      * <p>
 222      * If any of the above checks is violated, this method fails with an
 223      * exception.
 224      * <p>
 225      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 226      * returns a {@code Lookup} on {@code targetClass} with
 227      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 228      * with {@code null} previous lookup class.
 229      * <p>
 230      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 231      * returns a {@code Lookup} on {@code targetClass} that records
 232      * the lookup class of the caller as the new previous lookup class with
 233      * {@code PRIVATE} access but no {@code MODULE} access.
 234      * <p>
 235      * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
 236      *
 237      * @apiNote The {@code Lookup} object returned by this method is allowed to
 238      * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
 239      * of {@code targetClass}. Extreme caution should be taken when opening a package
 240      * to another module as such defined classes have the same full privilege
 241      * access as other members in {@code targetClass}'s module.
 242      *
 243      * @param targetClass the target class
 244      * @param caller the caller lookup object
 245      * @return a lookup object for the target class, with private access
 246      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 247      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 248      * @throws SecurityException if denied by the security manager
 249      * @throws IllegalAccessException if any of the other access checks specified above fails
 250      * @since 9
 251      * @see Lookup#dropLookupMode
 252      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 253      */
 254     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 255         if (caller.allowedModes == Lookup.TRUSTED) {
 256             return new Lookup(targetClass);
 257         }
 258 
 259         @SuppressWarnings("removal")
 260         SecurityManager sm = System.getSecurityManager();
 261         if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 262         if (targetClass.isPrimitive())
 263             throw new IllegalArgumentException(targetClass + " is a primitive class");
 264         if (targetClass.isArray())
 265             throw new IllegalArgumentException(targetClass + " is an array class");
 266         // Ensure that we can reason accurately about private and module access.
 267         int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
 268         if ((caller.lookupModes() & requireAccess) != requireAccess)
 269             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 270 
 271         // previous lookup class is never set if it has MODULE access
 272         assert caller.previousLookupClass() == null;
 273 
 274         Class<?> callerClass = caller.lookupClass();
 275         Module callerModule = callerClass.getModule();  // M1
 276         Module targetModule = targetClass.getModule();  // M2
 277         Class<?> newPreviousClass = null;
 278         int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
 279 
 280         if (targetModule != callerModule) {
 281             if (!callerModule.canRead(targetModule))
 282                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 283             if (targetModule.isNamed()) {
 284                 String pn = targetClass.getPackageName();
 285                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 286                 if (!targetModule.isOpen(pn, callerModule))
 287                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 288             }
 289 
 290             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 291             newPreviousClass = callerClass;
 292             newModes &= ~Lookup.MODULE;
 293         }
 294         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 295     }
 296 
 297     /**
 298      * Returns the <em>class data</em> associated with the lookup class
 299      * of the given {@code caller} lookup object, or {@code null}.
 300      *
 301      * <p> A hidden class with class data can be created by calling
 302      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 303      * Lookup::defineHiddenClassWithClassData}.
 304      * This method will cause the static class initializer of the lookup
 305      * class of the given {@code caller} lookup object be executed if
 306      * it has not been initialized.
 307      *
 308      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 309      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 310      * {@code null} is returned if this method is called on the lookup object
 311      * on these classes.
 312      *
 313      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 314      * must have {@linkplain Lookup#ORIGINAL original access}
 315      * in order to retrieve the class data.
 316      *
 317      * @apiNote
 318      * This method can be called as a bootstrap method for a dynamically computed
 319      * constant.  A framework can create a hidden class with class data, for
 320      * example that can be {@code Class} or {@code MethodHandle} object.
 321      * The class data is accessible only to the lookup object
 322      * created by the original caller but inaccessible to other members
 323      * in the same nest.  If a framework passes security sensitive objects
 324      * to a hidden class via class data, it is recommended to load the value
 325      * of class data as a dynamically computed constant instead of storing
 326      * the class data in private static field(s) which are accessible to
 327      * other nestmates.
 328      *
 329      * @param <T> the type to cast the class data object to
 330      * @param caller the lookup context describing the class performing the
 331      * operation (normally stacked by the JVM)
 332      * @param name must be {@link ConstantDescs#DEFAULT_NAME}
 333      *             ({@code "_"})
 334      * @param type the type of the class data
 335      * @return the value of the class data if present in the lookup class;
 336      * otherwise {@code null}
 337      * @throws IllegalArgumentException if name is not {@code "_"}
 338      * @throws IllegalAccessException if the lookup context does not have
 339      * {@linkplain Lookup#ORIGINAL original} access
 340      * @throws ClassCastException if the class data cannot be converted to
 341      * the given {@code type}
 342      * @throws NullPointerException if {@code caller} or {@code type} argument
 343      * is {@code null}
 344      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 345      * @see MethodHandles#classDataAt(Lookup, String, Class, int)
 346      * @since 16
 347      * @jvms 5.5 Initialization
 348      */
 349      public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 350          Objects.requireNonNull(caller);
 351          Objects.requireNonNull(type);
 352          if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
 353              throw new IllegalArgumentException("name must be \"_\": " + name);
 354          }
 355 
 356          if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL)  {
 357              throw new IllegalAccessException(caller + " does not have ORIGINAL access");
 358          }
 359 
 360          Object classdata = classData(caller.lookupClass());
 361          if (classdata == null) return null;
 362 
 363          try {
 364              return BootstrapMethodInvoker.widenAndCast(classdata, type);
 365          } catch (RuntimeException|Error e) {
 366              throw e; // let CCE and other runtime exceptions through
 367          } catch (Throwable e) {
 368              throw new InternalError(e);
 369          }
 370     }
 371 
 372     /*
 373      * Returns the class data set by the VM in the Class::classData field.
 374      *
 375      * This is also invoked by LambdaForms as it cannot use condy via
 376      * MethodHandles::classData due to bootstrapping issue.
 377      */
 378     static Object classData(Class<?> c) {
 379         UNSAFE.ensureClassInitialized(c);
 380         return SharedSecrets.getJavaLangAccess().classData(c);
 381     }
 382 
 383     /**
 384      * Returns the element at the specified index in the
 385      * {@linkplain #classData(Lookup, String, Class) class data},
 386      * if the class data associated with the lookup class
 387      * of the given {@code caller} lookup object is a {@code List}.
 388      * If the class data is not present in this lookup class, this method
 389      * returns {@code null}.
 390      *
 391      * <p> A hidden class with class data can be created by calling
 392      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 393      * Lookup::defineHiddenClassWithClassData}.
 394      * This method will cause the static class initializer of the lookup
 395      * class of the given {@code caller} lookup object be executed if
 396      * it has not been initialized.
 397      *
 398      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 399      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 400      * {@code null} is returned if this method is called on the lookup object
 401      * on these classes.
 402      *
 403      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 404      * must have {@linkplain Lookup#ORIGINAL original access}
 405      * in order to retrieve the class data.
 406      *
 407      * @apiNote
 408      * This method can be called as a bootstrap method for a dynamically computed
 409      * constant.  A framework can create a hidden class with class data, for
 410      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 411      * one object and use this method to load one element at a specific index.
 412      * The class data is accessible only to the lookup object
 413      * created by the original caller but inaccessible to other members
 414      * in the same nest.  If a framework passes security sensitive objects
 415      * to a hidden class via class data, it is recommended to load the value
 416      * of class data as a dynamically computed constant instead of storing
 417      * the class data in private static field(s) which are accessible to other
 418      * nestmates.
 419      *
 420      * @param <T> the type to cast the result object to
 421      * @param caller the lookup context describing the class performing the
 422      * operation (normally stacked by the JVM)
 423      * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
 424      *             ({@code "_"})
 425      * @param type the type of the element at the given index in the class data
 426      * @param index index of the element in the class data
 427      * @return the element at the given index in the class data
 428      * if the class data is present; otherwise {@code null}
 429      * @throws IllegalArgumentException if name is not {@code "_"}
 430      * @throws IllegalAccessException if the lookup context does not have
 431      * {@linkplain Lookup#ORIGINAL original} access
 432      * @throws ClassCastException if the class data cannot be converted to {@code List}
 433      * or the element at the specified index cannot be converted to the given type
 434      * @throws IndexOutOfBoundsException if the index is out of range
 435      * @throws NullPointerException if {@code caller} or {@code type} argument is
 436      * {@code null}; or if unboxing operation fails because
 437      * the element at the given index is {@code null}
 438      *
 439      * @since 16
 440      * @see #classData(Lookup, String, Class)
 441      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 442      */
 443     public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
 444             throws IllegalAccessException
 445     {
 446         @SuppressWarnings("unchecked")
 447         List<Object> classdata = (List<Object>)classData(caller, name, List.class);
 448         if (classdata == null) return null;
 449 
 450         try {
 451             Object element = classdata.get(index);
 452             return BootstrapMethodInvoker.widenAndCast(element, type);
 453         } catch (RuntimeException|Error e) {
 454             throw e; // let specified exceptions and other runtime exceptions/errors through
 455         } catch (Throwable e) {
 456             throw new InternalError(e);
 457         }
 458     }
 459 
 460     /**
 461      * Performs an unchecked "crack" of a
 462      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 463      * The result is as if the user had obtained a lookup object capable enough
 464      * to crack the target method handle, called
 465      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 466      * on the target to obtain its symbolic reference, and then called
 467      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 468      * to resolve the symbolic reference to a member.
 469      * <p>
 470      * If there is a security manager, its {@code checkPermission} method
 471      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 472      * @param <T> the desired type of the result, either {@link Member} or a subtype
 473      * @param target a direct method handle to crack into symbolic reference components
 474      * @param expected a class object representing the desired result type {@code T}
 475      * @return a reference to the method, constructor, or field object
 476      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 477      * @throws    NullPointerException if either argument is {@code null}
 478      * @throws    IllegalArgumentException if the target is not a direct method handle
 479      * @throws    ClassCastException if the member is not of the expected type
 480      * @since 1.8
 481      */
 482     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 483         @SuppressWarnings("removal")
 484         SecurityManager smgr = System.getSecurityManager();
 485         if (smgr != null)  smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 486         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 487         return lookup.revealDirect(target).reflectAs(expected, lookup);
 488     }
 489 
 490     /**
 491      * A <em>lookup object</em> is a factory for creating method handles,
 492      * when the creation requires access checking.
 493      * Method handles do not perform
 494      * access checks when they are called, but rather when they are created.
 495      * Therefore, method handle access
 496      * restrictions must be enforced when a method handle is created.
 497      * The caller class against which those restrictions are enforced
 498      * is known as the {@linkplain #lookupClass() lookup class}.
 499      * <p>
 500      * A lookup class which needs to create method handles will call
 501      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 502      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 503      * determined, and securely stored in the {@code Lookup} object.
 504      * The lookup class (or its delegates) may then use factory methods
 505      * on the {@code Lookup} object to create method handles for access-checked members.
 506      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 507      * even private ones.
 508      *
 509      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 510      * The factory methods on a {@code Lookup} object correspond to all major
 511      * use cases for methods, constructors, and fields.
 512      * Each method handle created by a factory method is the functional
 513      * equivalent of a particular <em>bytecode behavior</em>.
 514      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 515      * the Java Virtual Machine Specification.)
 516      * Here is a summary of the correspondence between these factory methods and
 517      * the behavior of the resulting method handles:
 518      * <table class="striped">
 519      * <caption style="display:none">lookup method behaviors</caption>
 520      * <thead>
 521      * <tr>
 522      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 523      *     <th scope="col">member</th>
 524      *     <th scope="col">bytecode behavior</th>
 525      * </tr>
 526      * </thead>
 527      * <tbody>
 528      * <tr>
 529      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 530      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 531      * </tr>
 532      * <tr>
 533      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 534      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 535      * </tr>
 536      * <tr>
 537      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 538      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 539      * </tr>
 540      * <tr>
 541      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 542      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 543      * </tr>
 544      * <tr>
 545      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 546      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 547      * </tr>
 548      * <tr>
 549      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 550      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 551      * </tr>
 552      * <tr>
 553      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 554      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 555      * </tr>
 556      * <tr>
 557      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 558      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 559      * </tr>
 560      * <tr>
 561      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 562      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 563      * </tr>
 564      * <tr>
 565      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 566      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 567      * </tr>
 568      * <tr>
 569      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 570      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 571      * </tr>
 572      * <tr>
 573      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 574      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 575      * </tr>
 576      * <tr>
 577      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 578      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 579      * </tr>
 580      * <tr>
 581      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 582      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 583      * </tr>
 584      * </tbody>
 585      * </table>
 586      *
 587      * Here, the type {@code C} is the class or interface being searched for a member,
 588      * documented as a parameter named {@code refc} in the lookup methods.
 589      * The method type {@code MT} is composed from the return type {@code T}
 590      * and the sequence of argument types {@code A*}.
 591      * The constructor also has a sequence of argument types {@code A*} and
 592      * is deemed to return the newly-created object of type {@code C}.
 593      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 594      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 595      * if it is present, it is always the leading argument to the method handle invocation.
 596      * (In the case of some {@code protected} members, {@code this} may be
 597      * restricted in type to the lookup class; see below.)
 598      * The name {@code arg} stands for all the other method handle arguments.
 599      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 600      * stands for a null reference if the accessed method or field is static,
 601      * and {@code this} otherwise.
 602      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 603      * for reflective objects corresponding to the given members declared in type {@code C}.
 604      * <p>
 605      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 606      * as if by {@code ldc CONSTANT_Class}.
 607      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 608      * <p>
 609      * In cases where the given member is of variable arity (i.e., a method or constructor)
 610      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 611      * In all other cases, the returned method handle will be of fixed arity.
 612      * <p style="font-size:smaller;">
 613      * <em>Discussion:</em>
 614      * The equivalence between looked-up method handles and underlying
 615      * class members and bytecode behaviors
 616      * can break down in a few ways:
 617      * <ul style="font-size:smaller;">
 618      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 619      * the lookup can still succeed, even when there is no equivalent
 620      * Java expression or bytecoded constant.
 621      * <li>Likewise, if {@code T} or {@code MT}
 622      * is not symbolically accessible from the lookup class's loader,
 623      * the lookup can still succeed.
 624      * For example, lookups for {@code MethodHandle.invokeExact} and
 625      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 626      * <li>If there is a security manager installed, it can forbid the lookup
 627      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 628      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 629      * constant is not subject to security manager checks.
 630      * <li>If the looked-up method has a
 631      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 632      * the method handle creation may fail with an
 633      * {@code IllegalArgumentException}, due to the method handle type having
 634      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 635      * </ul>
 636      *
 637      * <h2><a id="access"></a>Access checking</h2>
 638      * Access checks are applied in the factory methods of {@code Lookup},
 639      * when a method handle is created.
 640      * This is a key difference from the Core Reflection API, since
 641      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 642      * performs access checking against every caller, on every call.
 643      * <p>
 644      * All access checks start from a {@code Lookup} object, which
 645      * compares its recorded lookup class against all requests to
 646      * create method handles.
 647      * A single {@code Lookup} object can be used to create any number
 648      * of access-checked method handles, all checked against a single
 649      * lookup class.
 650      * <p>
 651      * A {@code Lookup} object can be shared with other trusted code,
 652      * such as a metaobject protocol.
 653      * A shared {@code Lookup} object delegates the capability
 654      * to create method handles on private members of the lookup class.
 655      * Even if privileged code uses the {@code Lookup} object,
 656      * the access checking is confined to the privileges of the
 657      * original lookup class.
 658      * <p>
 659      * A lookup can fail, because
 660      * the containing class is not accessible to the lookup class, or
 661      * because the desired class member is missing, or because the
 662      * desired class member is not accessible to the lookup class, or
 663      * because the lookup object is not trusted enough to access the member.
 664      * In the case of a field setter function on a {@code final} field,
 665      * finality enforcement is treated as a kind of access control,
 666      * and the lookup will fail, except in special cases of
 667      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 668      * In any of these cases, a {@code ReflectiveOperationException} will be
 669      * thrown from the attempted lookup.  The exact class will be one of
 670      * the following:
 671      * <ul>
 672      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 673      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 674      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 675      * </ul>
 676      * <p>
 677      * In general, the conditions under which a method handle may be
 678      * looked up for a method {@code M} are no more restrictive than the conditions
 679      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 680      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 681      * a method handle lookup will generally raise a corresponding
 682      * checked exception, such as {@code NoSuchMethodException}.
 683      * And the effect of invoking the method handle resulting from the lookup
 684      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 685      * to executing the compiled, verified, and resolved call to {@code M}.
 686      * The same point is true of fields and constructors.
 687      * <p style="font-size:smaller;">
 688      * <em>Discussion:</em>
 689      * Access checks only apply to named and reflected methods,
 690      * constructors, and fields.
 691      * Other method handle creation methods, such as
 692      * {@link MethodHandle#asType MethodHandle.asType},
 693      * do not require any access checks, and are used
 694      * independently of any {@code Lookup} object.
 695      * <p>
 696      * If the desired member is {@code protected}, the usual JVM rules apply,
 697      * including the requirement that the lookup class must either be in the
 698      * same package as the desired member, or must inherit that member.
 699      * (See the Java Virtual Machine Specification, sections {@jvms
 700      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 701      * In addition, if the desired member is a non-static field or method
 702      * in a different package, the resulting method handle may only be applied
 703      * to objects of the lookup class or one of its subclasses.
 704      * This requirement is enforced by narrowing the type of the leading
 705      * {@code this} parameter from {@code C}
 706      * (which will necessarily be a superclass of the lookup class)
 707      * to the lookup class itself.
 708      * <p>
 709      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 710      * that the receiver argument must match both the resolved method <em>and</em>
 711      * the current class.  Again, this requirement is enforced by narrowing the
 712      * type of the leading parameter to the resulting method handle.
 713      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 714      * <p>
 715      * The JVM represents constructors and static initializer blocks as internal methods
 716      * with special names ({@value ConstantDescs#INIT_NAME} and {@value
 717      * ConstantDescs#CLASS_INIT_NAME}).
 718      * The internal syntax of invocation instructions allows them to refer to such internal
 719      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 720      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 721      * <p>
 722      * If the relationship between nested types is expressed directly through the
 723      * {@code NestHost} and {@code NestMembers} attributes
 724      * (see the Java Virtual Machine Specification, sections {@jvms
 725      * 4.7.28} and {@jvms 4.7.29}),
 726      * then the associated {@code Lookup} object provides direct access to
 727      * the lookup class and all of its nestmates
 728      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 729      * Otherwise, access between nested classes is obtained by the Java compiler creating
 730      * a wrapper method to access a private method of another class in the same nest.
 731      * For example, a nested class {@code C.D}
 732      * can access private members within other related classes such as
 733      * {@code C}, {@code C.D.E}, or {@code C.B},
 734      * but the Java compiler may need to generate wrapper methods in
 735      * those related classes.  In such cases, a {@code Lookup} object on
 736      * {@code C.E} would be unable to access those private members.
 737      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 738      * which can transform a lookup on {@code C.E} into one on any of those other
 739      * classes, without special elevation of privilege.
 740      * <p>
 741      * The accesses permitted to a given lookup object may be limited,
 742      * according to its set of {@link #lookupModes lookupModes},
 743      * to a subset of members normally accessible to the lookup class.
 744      * For example, the {@link MethodHandles#publicLookup publicLookup}
 745      * method produces a lookup object which is only allowed to access
 746      * public members in public classes of exported packages.
 747      * The caller sensitive method {@link MethodHandles#lookup lookup}
 748      * produces a lookup object with full capabilities relative to
 749      * its caller class, to emulate all supported bytecode behaviors.
 750      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 751      * with fewer access modes than the original lookup object.
 752      *
 753      * <p style="font-size:smaller;">
 754      * <a id="privacc"></a>
 755      * <em>Discussion of private and module access:</em>
 756      * We say that a lookup has <em>private access</em>
 757      * if its {@linkplain #lookupModes lookup modes}
 758      * include the possibility of accessing {@code private} members
 759      * (which includes the private members of nestmates).
 760      * As documented in the relevant methods elsewhere,
 761      * only lookups with private access possess the following capabilities:
 762      * <ul style="font-size:smaller;">
 763      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 764      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 765      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 766      *     for classes accessible to the lookup class
 767      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 768      *     within the same package member
 769      * </ul>
 770      * <p style="font-size:smaller;">
 771      * Similarly, a lookup with module access ensures that the original lookup creator was
 772      * a member in the same module as the lookup class.
 773      * <p style="font-size:smaller;">
 774      * Private and module access are independently determined modes; a lookup may have
 775      * either or both or neither.  A lookup which possesses both access modes is said to
 776      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
 777      * <p style="font-size:smaller;">
 778      * A lookup with <em>original access</em> ensures that this lookup is created by
 779      * the original lookup class and the bootstrap method invoked by the VM.
 780      * Such a lookup with original access also has private and module access
 781      * which has the following additional capability:
 782      * <ul style="font-size:smaller;">
 783      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 784      *     such as {@code Class.forName}
 785      * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
 786      * class data} associated with the lookup class</li>
 787      * </ul>
 788      * <p style="font-size:smaller;">
 789      * Each of these permissions is a consequence of the fact that a lookup object
 790      * with private access can be securely traced back to an originating class,
 791      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 792      * can be reliably determined and emulated by method handles.
 793      *
 794      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 795      * When a lookup class in one module {@code M1} accesses a class in another module
 796      * {@code M2}, extra access checking is performed beyond the access mode bits.
 797      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 798      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 799      * and when the type is in a package of {@code M2} that is exported to
 800      * at least {@code M1}.
 801      * <p>
 802      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 803      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 804      * MethodHandles.privateLookupIn} methods.
 805      * Teleporting across modules will always record the original lookup class as
 806      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 807      * and drops {@link Lookup#MODULE MODULE} access.
 808      * If the target class is in the same module as the lookup class {@code C},
 809      * then the target class becomes the new lookup class
 810      * and there is no change to the previous lookup class.
 811      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 812      * {@code C} becomes the new previous lookup class
 813      * and the target class becomes the new lookup class.
 814      * In that case, if there was already a previous lookup class in {@code M0},
 815      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 816      * drops all privileges.
 817      * For example,
 818      * {@snippet lang="java" :
 819      * Lookup lookup = MethodHandles.lookup();   // in class C
 820      * Lookup lookup2 = lookup.in(D.class);
 821      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 822      * }
 823      * <p>
 824      * The {@link #lookup()} factory method produces a {@code Lookup} object
 825      * with {@code null} previous lookup class.
 826      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 827      * to class {@code D} without elevation of privileges.
 828      * If {@code C} and {@code D} are in the same module,
 829      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 830      * same previous lookup class as the original {@code lookup}, or
 831      * {@code null} if not present.
 832      * <p>
 833      * When a {@code Lookup} teleports from a class
 834      * in one nest to another nest, {@code PRIVATE} access is dropped.
 835      * When a {@code Lookup} teleports from a class in one package to
 836      * another package, {@code PACKAGE} access is dropped.
 837      * When a {@code Lookup} teleports from a class in one module to another module,
 838      * {@code MODULE} access is dropped.
 839      * Teleporting across modules drops the ability to access non-exported classes
 840      * in both the module of the new lookup class and the module of the old lookup class
 841      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 842      * A {@code Lookup} can teleport back and forth to a class in the module of
 843      * the lookup class and the module of the previous class lookup.
 844      * Teleporting across modules can only decrease access but cannot increase it.
 845      * Teleporting to some third module drops all accesses.
 846      * <p>
 847      * In the above example, if {@code C} and {@code D} are in different modules,
 848      * {@code lookup2} records {@code D} as its lookup class and
 849      * {@code C} as its previous lookup class and {@code lookup2} has only
 850      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 851      * {@code C}'s module and {@code D}'s module.
 852      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 853      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 854      * class {@code D} is recorded as its previous lookup class.
 855      * <p>
 856      * Teleporting across modules restricts access to the public types that
 857      * both the lookup class and the previous lookup class can equally access
 858      * (see below).
 859      * <p>
 860      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 861      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 862      * and produce a new {@code Lookup} with <a href="#privacc">private access</a>
 863      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 864      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 865      * to call {@code privateLookupIn}.
 866      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 867      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 868      * produces a new {@code Lookup} on {@code T} with full capabilities.
 869      * A {@code lookup} on {@code C} is also allowed
 870      * to do deep reflection on {@code T} in another module {@code M2} if
 871      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 872      * the package containing {@code T} to at least {@code M1}.
 873      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 874      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 875      * The resulting {@code Lookup} can be used to do member lookup or teleport
 876      * to another lookup class by calling {@link #in Lookup::in}.  But
 877      * it cannot be used to obtain another private {@code Lookup} by calling
 878      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 879      * because it has no {@code MODULE} access.
 880      * <p>
 881      * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to
 882      * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
 883      * of {@code T}. Extreme caution should be taken when opening a package
 884      * to another module as such defined classes have the same full privilege
 885      * access as other members in {@code M2}.
 886      *
 887      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 888      *
 889      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 890      * allows cross-module access. The access checking is performed with respect
 891      * to both the lookup class and the previous lookup class if present.
 892      * <p>
 893      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 894      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 895      * exported unconditionally}.
 896      * <p>
 897      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 898      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 899      * that are readable to {@code M1} and the type is in a package that is exported
 900      * at least to {@code M1}.
 901      * <p>
 902      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 903      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 904      * the intersection of all public types that are accessible to {@code M1}
 905      * with all public types that are accessible to {@code M0}. {@code M0}
 906      * reads {@code M1} and hence the set of accessible types includes:
 907      *
 908      * <ul>
 909      * <li>unconditional-exported packages from {@code M1}</li>
 910      * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li>
 911      * <li>
 912      *     unconditional-exported packages from a third module {@code M2}if both {@code M0}
 913      *     and {@code M1} read {@code M2}
 914      * </li>
 915      * <li>qualified-exported packages from {@code M1} to {@code M0}</li>
 916      * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li>
 917      * <li>
 918      *     qualified-exported packages from a third module {@code M2} to both {@code M0} and
 919      *     {@code M1} if both {@code M0} and {@code M1} read {@code M2}
 920      * </li>
 921      * </ul>
 922      *
 923      * <h2><a id="access-modes"></a>Access modes</h2>
 924      *
 925      * The table below shows the access modes of a {@code Lookup} produced by
 926      * any of the following factory or transformation methods:
 927      * <ul>
 928      * <li>{@link #lookup() MethodHandles::lookup}</li>
 929      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 930      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 931      * <li>{@link Lookup#in Lookup::in}</li>
 932      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 933      * </ul>
 934      *
 935      * <table class="striped">
 936      * <caption style="display:none">
 937      * Access mode summary
 938      * </caption>
 939      * <thead>
 940      * <tr>
 941      * <th scope="col">Lookup object</th>
 942      * <th style="text-align:center">original</th>
 943      * <th style="text-align:center">protected</th>
 944      * <th style="text-align:center">private</th>
 945      * <th style="text-align:center">package</th>
 946      * <th style="text-align:center">module</th>
 947      * <th style="text-align:center">public</th>
 948      * </tr>
 949      * </thead>
 950      * <tbody>
 951      * <tr>
 952      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 953      * <td style="text-align:center">ORI</td>
 954      * <td style="text-align:center">PRO</td>
 955      * <td style="text-align:center">PRI</td>
 956      * <td style="text-align:center">PAC</td>
 957      * <td style="text-align:center">MOD</td>
 958      * <td style="text-align:center">1R</td>
 959      * </tr>
 960      * <tr>
 961      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 962      * <td></td>
 963      * <td></td>
 964      * <td></td>
 965      * <td style="text-align:center">PAC</td>
 966      * <td style="text-align:center">MOD</td>
 967      * <td style="text-align:center">1R</td>
 968      * </tr>
 969      * <tr>
 970      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 971      * <td></td>
 972      * <td></td>
 973      * <td></td>
 974      * <td></td>
 975      * <td style="text-align:center">MOD</td>
 976      * <td style="text-align:center">1R</td>
 977      * </tr>
 978      * <tr>
 979      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 980      * <td></td>
 981      * <td></td>
 982      * <td></td>
 983      * <td></td>
 984      * <td></td>
 985      * <td style="text-align:center">2R</td>
 986      * </tr>
 987      * <tr>
 988      * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th>
 989      * <td></td>
 990      * <td></td>
 991      * <td></td>
 992      * <td></td>
 993      * <td></td>
 994      * <td style="text-align:center">2R</td>
 995      * </tr>
 996      * <tr>
 997      * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th>
 998      * <td></td>
 999      * <td style="text-align:center">PRO</td>
1000      * <td style="text-align:center">PRI</td>
1001      * <td style="text-align:center">PAC</td>
1002      * <td style="text-align:center">MOD</td>
1003      * <td style="text-align:center">1R</td>
1004      * </tr>
1005      * <tr>
1006      * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th>
1007      * <td></td>
1008      * <td style="text-align:center">PRO</td>
1009      * <td style="text-align:center">PRI</td>
1010      * <td style="text-align:center">PAC</td>
1011      * <td style="text-align:center">MOD</td>
1012      * <td style="text-align:center">1R</td>
1013      * </tr>
1014      * <tr>
1015      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th>
1016      * <td></td>
1017      * <td></td>
1018      * <td></td>
1019      * <td style="text-align:center">PAC</td>
1020      * <td style="text-align:center">MOD</td>
1021      * <td style="text-align:center">1R</td>
1022      * </tr>
1023      * <tr>
1024      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th>
1025      * <td></td>
1026      * <td></td>
1027      * <td></td>
1028      * <td></td>
1029      * <td style="text-align:center">MOD</td>
1030      * <td style="text-align:center">1R</td>
1031      * </tr>
1032      * <tr>
1033      * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th>
1034      * <td></td>
1035      * <td></td>
1036      * <td></td>
1037      * <td></td>
1038      * <td></td>
1039      * <td style="text-align:center">2R</td>
1040      * </tr>
1041      * <tr>
1042      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th>
1043      * <td></td>
1044      * <td></td>
1045      * <td style="text-align:center">PRI</td>
1046      * <td style="text-align:center">PAC</td>
1047      * <td style="text-align:center">MOD</td>
1048      * <td style="text-align:center">1R</td>
1049      * </tr>
1050      * <tr>
1051      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th>
1052      * <td></td>
1053      * <td></td>
1054      * <td></td>
1055      * <td style="text-align:center">PAC</td>
1056      * <td style="text-align:center">MOD</td>
1057      * <td style="text-align:center">1R</td>
1058      * </tr>
1059      * <tr>
1060      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th>
1061      * <td></td>
1062      * <td></td>
1063      * <td></td>
1064      * <td></td>
1065      * <td style="text-align:center">MOD</td>
1066      * <td style="text-align:center">1R</td>
1067      * </tr>
1068      * <tr>
1069      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th>
1070      * <td></td>
1071      * <td></td>
1072      * <td></td>
1073      * <td></td>
1074      * <td></td>
1075      * <td style="text-align:center">1R</td>
1076      * </tr>
1077      * <tr>
1078      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th>
1079      * <td></td>
1080      * <td></td>
1081      * <td></td>
1082      * <td></td>
1083      * <td></td>
1084      * <td style="text-align:center">none</td>
1085      * <tr>
1086      * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th>
1087      * <td></td>
1088      * <td style="text-align:center">PRO</td>
1089      * <td style="text-align:center">PRI</td>
1090      * <td style="text-align:center">PAC</td>
1091      * <td></td>
1092      * <td style="text-align:center">2R</td>
1093      * </tr>
1094      * <tr>
1095      * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th>
1096      * <td></td>
1097      * <td style="text-align:center">PRO</td>
1098      * <td style="text-align:center">PRI</td>
1099      * <td style="text-align:center">PAC</td>
1100      * <td></td>
1101      * <td style="text-align:center">2R</td>
1102      * </tr>
1103      * <tr>
1104      * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th>
1105      * <td></td>
1106      * <td></td>
1107      * <td></td>
1108      * <td></td>
1109      * <td></td>
1110      * <td style="text-align:center">IAE</td>
1111      * </tr>
1112      * <tr>
1113      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th>
1114      * <td></td>
1115      * <td></td>
1116      * <td></td>
1117      * <td style="text-align:center">PAC</td>
1118      * <td></td>
1119      * <td style="text-align:center">2R</td>
1120      * </tr>
1121      * <tr>
1122      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th>
1123      * <td></td>
1124      * <td></td>
1125      * <td></td>
1126      * <td></td>
1127      * <td></td>
1128      * <td style="text-align:center">2R</td>
1129      * </tr>
1130      * <tr>
1131      * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th>
1132      * <td></td>
1133      * <td></td>
1134      * <td></td>
1135      * <td></td>
1136      * <td></td>
1137      * <td style="text-align:center">2R</td>
1138      * </tr>
1139      * <tr>
1140      * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th>
1141      * <td></td>
1142      * <td></td>
1143      * <td></td>
1144      * <td></td>
1145      * <td></td>
1146      * <td style="text-align:center">none</td>
1147      * </tr>
1148      * <tr>
1149      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th>
1150      * <td></td>
1151      * <td></td>
1152      * <td style="text-align:center">PRI</td>
1153      * <td style="text-align:center">PAC</td>
1154      * <td></td>
1155      * <td style="text-align:center">2R</td>
1156      * </tr>
1157      * <tr>
1158      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th>
1159      * <td></td>
1160      * <td></td>
1161      * <td></td>
1162      * <td style="text-align:center">PAC</td>
1163      * <td></td>
1164      * <td style="text-align:center">2R</td>
1165      * </tr>
1166      * <tr>
1167      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th>
1168      * <td></td>
1169      * <td></td>
1170      * <td></td>
1171      * <td></td>
1172      * <td></td>
1173      * <td style="text-align:center">2R</td>
1174      * </tr>
1175      * <tr>
1176      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th>
1177      * <td></td>
1178      * <td></td>
1179      * <td></td>
1180      * <td></td>
1181      * <td></td>
1182      * <td style="text-align:center">2R</td>
1183      * </tr>
1184      * <tr>
1185      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th>
1186      * <td></td>
1187      * <td></td>
1188      * <td></td>
1189      * <td></td>
1190      * <td></td>
1191      * <td style="text-align:center">none</td>
1192      * </tr>
1193      * <tr>
1194      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th>
1195      * <td></td>
1196      * <td></td>
1197      * <td style="text-align:center">PRI</td>
1198      * <td style="text-align:center">PAC</td>
1199      * <td style="text-align:center">MOD</td>
1200      * <td style="text-align:center">1R</td>
1201      * </tr>
1202      * <tr>
1203      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th>
1204      * <td></td>
1205      * <td></td>
1206      * <td></td>
1207      * <td style="text-align:center">PAC</td>
1208      * <td style="text-align:center">MOD</td>
1209      * <td style="text-align:center">1R</td>
1210      * </tr>
1211      * <tr>
1212      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th>
1213      * <td></td>
1214      * <td></td>
1215      * <td></td>
1216      * <td></td>
1217      * <td style="text-align:center">MOD</td>
1218      * <td style="text-align:center">1R</td>
1219      * </tr>
1220      * <tr>
1221      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th>
1222      * <td></td>
1223      * <td></td>
1224      * <td></td>
1225      * <td></td>
1226      * <td></td>
1227      * <td style="text-align:center">1R</td>
1228      * </tr>
1229      * <tr>
1230      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th>
1231      * <td></td>
1232      * <td></td>
1233      * <td></td>
1234      * <td></td>
1235      * <td></td>
1236      * <td style="text-align:center">none</td>
1237      * </tr>
1238      * <tr>
1239      * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th>
1240      * <td></td>
1241      * <td></td>
1242      * <td></td>
1243      * <td></td>
1244      * <td></td>
1245      * <td style="text-align:center">U</td>
1246      * </tr>
1247      * <tr>
1248      * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th>
1249      * <td></td>
1250      * <td></td>
1251      * <td></td>
1252      * <td></td>
1253      * <td></td>
1254      * <td style="text-align:center">U</td>
1255      * </tr>
1256      * <tr>
1257      * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th>
1258      * <td></td>
1259      * <td></td>
1260      * <td></td>
1261      * <td></td>
1262      * <td></td>
1263      * <td style="text-align:center">U</td>
1264      * </tr>
1265      * <tr>
1266      * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th>
1267      * <td></td>
1268      * <td></td>
1269      * <td></td>
1270      * <td></td>
1271      * <td></td>
1272      * <td style="text-align:center">none</td>
1273      * </tr>
1274      * <tr>
1275      * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th>
1276      * <td></td>
1277      * <td></td>
1278      * <td></td>
1279      * <td></td>
1280      * <td></td>
1281      * <td style="text-align:center">IAE</td>
1282      * </tr>
1283      * <tr>
1284      * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th>
1285      * <td></td>
1286      * <td></td>
1287      * <td></td>
1288      * <td></td>
1289      * <td></td>
1290      * <td style="text-align:center">none</td>
1291      * </tr>
1292      * </tbody>
1293      * </table>
1294      *
1295      * <p>
1296      * Notes:
1297      * <ul>
1298      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1299      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1300      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1301      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1302      * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1303      *     {@code PRO} indicates {@link #PROTECTED} bit set,
1304      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1305      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1306      *     {@code MOD} indicates {@link #MODULE} bit set,
1307      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1308      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1309      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1310      * <li>Public access comes in three kinds:
1311      * <ul>
1312      * <li>unconditional ({@code U}): the lookup assumes readability.
1313      *     The lookup has {@code null} previous lookup class.
1314      * <li>one-module-reads ({@code 1R}): the module access checking is
1315      *     performed with respect to the lookup class.  The lookup has {@code null}
1316      *     previous lookup class.
1317      * <li>two-module-reads ({@code 2R}): the module access checking is
1318      *     performed with respect to the lookup class and the previous lookup class.
1319      *     The lookup has a non-null previous lookup class which is in a
1320      *     different module from the current lookup class.
1321      * </ul>
1322      * <li>Any attempt to reach a third module loses all access.</li>
1323      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1324      * all access modes are dropped.</li>
1325      * </ul>
1326      *
1327      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1328      * Although bytecode instructions can only refer to classes in
1329      * a related class loader, this API can search for methods in any
1330      * class, as long as a reference to its {@code Class} object is
1331      * available.  Such cross-loader references are also possible with the
1332      * Core Reflection API, and are impossible to bytecode instructions
1333      * such as {@code invokestatic} or {@code getfield}.
1334      * There is a {@linkplain java.lang.SecurityManager security manager API}
1335      * to allow applications to check such cross-loader references.
1336      * These checks apply to both the {@code MethodHandles.Lookup} API
1337      * and the Core Reflection API
1338      * (as found on {@link java.lang.Class Class}).
1339      * <p>
1340      * If a security manager is present, member and class lookups are subject to
1341      * additional checks.
1342      * From one to three calls are made to the security manager.
1343      * Any of these calls can refuse access by throwing a
1344      * {@link java.lang.SecurityException SecurityException}.
1345      * Define {@code smgr} as the security manager,
1346      * {@code lookc} as the lookup class of the current lookup object,
1347      * {@code refc} as the containing class in which the member
1348      * is being sought, and {@code defc} as the class in which the
1349      * member is actually defined.
1350      * (If a class or other type is being accessed,
1351      * the {@code refc} and {@code defc} values are the class itself.)
1352      * The value {@code lookc} is defined as <em>not present</em>
1353      * if the current lookup object does not have
1354      * {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1355      * The calls are made according to the following rules:
1356      * <ul>
1357      * <li><b>Step 1:</b>
1358      *     If {@code lookc} is not present, or if its class loader is not
1359      *     the same as or an ancestor of the class loader of {@code refc},
1360      *     then {@link SecurityManager#checkPackageAccess
1361      *     smgr.checkPackageAccess(refcPkg)} is called,
1362      *     where {@code refcPkg} is the package of {@code refc}.
1363      * <li><b>Step 2a:</b>
1364      *     If the retrieved member is not public and
1365      *     {@code lookc} is not present, then
1366      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1367      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
1368      * <li><b>Step 2b:</b>
1369      *     If the retrieved class has a {@code null} class loader,
1370      *     and {@code lookc} is not present, then
1371      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1372      *     with {@code RuntimePermission("getClassLoader")} is called.
1373      * <li><b>Step 3:</b>
1374      *     If the retrieved member is not public,
1375      *     and if {@code lookc} is not present,
1376      *     and if {@code defc} and {@code refc} are different,
1377      *     then {@link SecurityManager#checkPackageAccess
1378      *     smgr.checkPackageAccess(defcPkg)} is called,
1379      *     where {@code defcPkg} is the package of {@code defc}.
1380      * </ul>
1381      * Security checks are performed after other access checks have passed.
1382      * Therefore, the above rules presuppose a member or class that is public,
1383      * or else that is being accessed from a lookup class that has
1384      * rights to access the member or class.
1385      * <p>
1386      * If a security manager is present and the current lookup object does not have
1387      * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then
1388      * {@link #defineClass(byte[]) defineClass},
1389      * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass},
1390      * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...)
1391      * defineHiddenClassWithClassData}
1392      * calls {@link SecurityManager#checkPermission smgr.checkPermission}
1393      * with {@code RuntimePermission("defineClass")}.
1394      *
1395      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1396      * A small number of Java methods have a special property called caller sensitivity.
1397      * A <em>caller-sensitive</em> method can behave differently depending on the
1398      * identity of its immediate caller.
1399      * <p>
1400      * If a method handle for a caller-sensitive method is requested,
1401      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1402      * but they take account of the lookup class in a special way.
1403      * The resulting method handle behaves as if it were called
1404      * from an instruction contained in the lookup class,
1405      * so that the caller-sensitive method detects the lookup class.
1406      * (By contrast, the invoker of the method handle is disregarded.)
1407      * Thus, in the case of caller-sensitive methods,
1408      * different lookup classes may give rise to
1409      * differently behaving method handles.
1410      * <p>
1411      * In cases where the lookup object is
1412      * {@link MethodHandles#publicLookup() publicLookup()},
1413      * or some other lookup object without the
1414      * {@linkplain #ORIGINAL original access},
1415      * the lookup class is disregarded.
1416      * In such cases, no caller-sensitive method handle can be created,
1417      * access is forbidden, and the lookup fails with an
1418      * {@code IllegalAccessException}.
1419      * <p style="font-size:smaller;">
1420      * <em>Discussion:</em>
1421      * For example, the caller-sensitive method
1422      * {@link java.lang.Class#forName(String) Class.forName(x)}
1423      * can return varying classes or throw varying exceptions,
1424      * depending on the class loader of the class that calls it.
1425      * A public lookup of {@code Class.forName} will fail, because
1426      * there is no reasonable way to determine its bytecode behavior.
1427      * <p style="font-size:smaller;">
1428      * If an application caches method handles for broad sharing,
1429      * it should use {@code publicLookup()} to create them.
1430      * If there is a lookup of {@code Class.forName}, it will fail,
1431      * and the application must take appropriate action in that case.
1432      * It may be that a later lookup, perhaps during the invocation of a
1433      * bootstrap method, can incorporate the specific identity
1434      * of the caller, making the method accessible.
1435      * <p style="font-size:smaller;">
1436      * The function {@code MethodHandles.lookup} is caller sensitive
1437      * so that there can be a secure foundation for lookups.
1438      * Nearly all other methods in the JSR 292 API rely on lookup
1439      * objects to check access requests.
1440      *
1441      * @revised 9
1442      */
1443     public static final
1444     class Lookup {
1445         /** The class on behalf of whom the lookup is being performed. */
1446         private final Class<?> lookupClass;
1447 
1448         /** previous lookup class */
1449         private final Class<?> prevLookupClass;
1450 
1451         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1452         private final int allowedModes;
1453 
1454         static {
1455             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1456         }
1457 
1458         /** A single-bit mask representing {@code public} access,
1459          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1460          *  The value, {@code 0x01}, happens to be the same as the value of the
1461          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1462          *  <p>
1463          *  A {@code Lookup} with this lookup mode performs cross-module access check
1464          *  with respect to the {@linkplain #lookupClass() lookup class} and
1465          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1466          */
1467         public static final int PUBLIC = Modifier.PUBLIC;
1468 
1469         /** A single-bit mask representing {@code private} access,
1470          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1471          *  The value, {@code 0x02}, happens to be the same as the value of the
1472          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1473          */
1474         public static final int PRIVATE = Modifier.PRIVATE;
1475 
1476         /** A single-bit mask representing {@code protected} access,
1477          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1478          *  The value, {@code 0x04}, happens to be the same as the value of the
1479          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1480          */
1481         public static final int PROTECTED = Modifier.PROTECTED;
1482 
1483         /** A single-bit mask representing {@code package} access (default access),
1484          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1485          *  The value is {@code 0x08}, which does not correspond meaningfully to
1486          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1487          */
1488         public static final int PACKAGE = Modifier.STATIC;
1489 
1490         /** A single-bit mask representing {@code module} access,
1491          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1492          *  The value is {@code 0x10}, which does not correspond meaningfully to
1493          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1494          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1495          *  with this lookup mode can access all public types in the module of the
1496          *  lookup class and public types in packages exported by other modules
1497          *  to the module of the lookup class.
1498          *  <p>
1499          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1500          *  previous lookup class} is always {@code null}.
1501          *
1502          *  @since 9
1503          */
1504         public static final int MODULE = PACKAGE << 1;
1505 
1506         /** A single-bit mask representing {@code unconditional} access
1507          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1508          *  The value is {@code 0x20}, which does not correspond meaningfully to
1509          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1510          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1511          *  java.lang.Module#canRead(java.lang.Module) readability}.
1512          *  This lookup mode can access all public members of public types
1513          *  of all modules when the type is in a package that is {@link
1514          *  java.lang.Module#isExported(String) exported unconditionally}.
1515          *
1516          *  <p>
1517          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1518          *  previous lookup class} is always {@code null}.
1519          *
1520          *  @since 9
1521          *  @see #publicLookup()
1522          */
1523         public static final int UNCONDITIONAL = PACKAGE << 2;
1524 
1525         /** A single-bit mask representing {@code original} access
1526          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1527          *  The value is {@code 0x40}, which does not correspond meaningfully to
1528          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1529          *
1530          *  <p>
1531          *  If this lookup mode is set, the {@code Lookup} object must be
1532          *  created by the original lookup class by calling
1533          *  {@link MethodHandles#lookup()} method or by a bootstrap method
1534          *  invoked by the VM.  The {@code Lookup} object with this lookup
1535          *  mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1536          *
1537          *  @since 16
1538          */
1539         public static final int ORIGINAL = PACKAGE << 3;
1540 
1541         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1542         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);   // with original access
1543         private static final int TRUSTED   = -1;
1544 
1545         /*
1546          * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1547          * Adjust 0 => PACKAGE
1548          */
1549         private static int fixmods(int mods) {
1550             mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1551             if (Modifier.isPublic(mods))
1552                 mods |= UNCONDITIONAL;
1553             return (mods != 0) ? mods : PACKAGE;
1554         }
1555 
1556         /** Tells which class is performing the lookup.  It is this class against
1557          *  which checks are performed for visibility and access permissions.
1558          *  <p>
1559          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1560          *  access checks are performed against both the lookup class and the previous lookup class.
1561          *  <p>
1562          *  The class implies a maximum level of access permission,
1563          *  but the permissions may be additionally limited by the bitmask
1564          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1565          *  can be accessed.
1566          *  @return the lookup class, on behalf of which this lookup object finds members
1567          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1568          */
1569         public Class<?> lookupClass() {
1570             return lookupClass;
1571         }
1572 
1573         /** Reports a lookup class in another module that this lookup object
1574          * was previously teleported from, or {@code null}.
1575          * <p>
1576          * A {@code Lookup} object produced by the factory methods, such as the
1577          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1578          * has {@code null} previous lookup class.
1579          * A {@code Lookup} object has a non-null previous lookup class
1580          * when this lookup was teleported from an old lookup class
1581          * in one module to a new lookup class in another module.
1582          *
1583          * @return the lookup class in another module that this lookup object was
1584          *         previously teleported from, or {@code null}
1585          * @since 14
1586          * @see #in(Class)
1587          * @see MethodHandles#privateLookupIn(Class, Lookup)
1588          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1589          */
1590         public Class<?> previousLookupClass() {
1591             return prevLookupClass;
1592         }
1593 
1594         // This is just for calling out to MethodHandleImpl.
1595         private Class<?> lookupClassOrNull() {
1596             return (allowedModes == TRUSTED) ? null : lookupClass;
1597         }
1598 
1599         /** Tells which access-protection classes of members this lookup object can produce.
1600          *  The result is a bit-mask of the bits
1601          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1602          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1603          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1604          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1605          *  {@linkplain #MODULE MODULE (0x10)},
1606          *  {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1607          *  and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1608          *  <p>
1609          *  A freshly-created lookup object
1610          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1611          *  all possible bits set, except {@code UNCONDITIONAL}.
1612          *  A lookup object on a new lookup class
1613          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1614          *  may have some mode bits set to zero.
1615          *  Mode bits can also be
1616          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1617          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1618          *  The purpose of this is to restrict access via the new lookup object,
1619          *  so that it can access only names which can be reached by the original
1620          *  lookup object, and also by the new lookup class.
1621          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1622          *  @see #in
1623          *  @see #dropLookupMode
1624          *
1625          *  @revised 9
1626          */
1627         public int lookupModes() {
1628             return allowedModes & ALL_MODES;
1629         }
1630 
1631         /** Embody the current class (the lookupClass) as a lookup class
1632          * for method handle creation.
1633          * Must be called by from a method in this package,
1634          * which in turn is called by a method not in this package.
1635          */
1636         Lookup(Class<?> lookupClass) {
1637             this(lookupClass, null, FULL_POWER_MODES);
1638         }
1639 
1640         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1641             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1642                     && prevLookupClass.getModule() != lookupClass.getModule());
1643             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1644             this.lookupClass = lookupClass;
1645             this.prevLookupClass = prevLookupClass;
1646             this.allowedModes = allowedModes;
1647         }
1648 
1649         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1650             // make sure we haven't accidentally picked up a privileged class:
1651             checkUnprivilegedlookupClass(lookupClass);
1652             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1653         }
1654 
1655         /**
1656          * Creates a lookup on the specified new lookup class.
1657          * The resulting object will report the specified
1658          * class as its own {@link #lookupClass() lookupClass}.
1659          *
1660          * <p>
1661          * However, the resulting {@code Lookup} object is guaranteed
1662          * to have no more access capabilities than the original.
1663          * In particular, access capabilities can be lost as follows:<ul>
1664          * <li>If the new lookup class is different from the old lookup class,
1665          * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1666          * <li>If the new lookup class is in a different module from the old one,
1667          * i.e. {@link #MODULE MODULE} access is lost.
1668          * <li>If the new lookup class is in a different package
1669          * than the old one, protected and default (package) members will not be accessible,
1670          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1671          * <li>If the new lookup class is not within the same package member
1672          * as the old one, private members will not be accessible, and protected members
1673          * will not be accessible by virtue of inheritance,
1674          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1675          * (Protected members may continue to be accessible because of package sharing.)
1676          * <li>If the new lookup class is not
1677          * {@linkplain #accessClass(Class) accessible} to this lookup,
1678          * then no members, not even public members, will be accessible
1679          * i.e. all access modes are lost.
1680          * <li>If the new lookup class, the old lookup class and the previous lookup class
1681          * are all in different modules i.e. teleporting to a third module,
1682          * all access modes are lost.
1683          * </ul>
1684          * <p>
1685          * The new previous lookup class is chosen as follows:
1686          * <ul>
1687          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1688          * the new previous lookup class is {@code null}.
1689          * <li>If the new lookup class is in the same module as the old lookup class,
1690          * the new previous lookup class is the old previous lookup class.
1691          * <li>If the new lookup class is in a different module from the old lookup class,
1692          * the new previous lookup class is the old lookup class.
1693          *</ul>
1694          * <p>
1695          * The resulting lookup's capabilities for loading classes
1696          * (used during {@link #findClass} invocations)
1697          * are determined by the lookup class' loader,
1698          * which may change due to this operation.
1699          *
1700          * @param requestedLookupClass the desired lookup class for the new lookup object
1701          * @return a lookup object which reports the desired lookup class, or the same object
1702          * if there is no change
1703          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1704          * @throws NullPointerException if the argument is null
1705          *
1706          * @revised 9
1707          * @see #accessClass(Class)
1708          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1709          */
1710         public Lookup in(Class<?> requestedLookupClass) {
1711             Objects.requireNonNull(requestedLookupClass);
1712             if (requestedLookupClass.isPrimitive())
1713                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1714             if (requestedLookupClass.isArray())
1715                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1716 
1717             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1718                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1719             if (requestedLookupClass == this.lookupClass)
1720                 return this;  // keep same capabilities
1721             int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1722             Module fromModule = this.lookupClass.getModule();
1723             Module targetModule = requestedLookupClass.getModule();
1724             Class<?> plc = this.previousLookupClass();
1725             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1726                 assert plc == null;
1727                 newModes = UNCONDITIONAL;
1728             } else if (fromModule != targetModule) {
1729                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1730                     // allow hopping back and forth between fromModule and plc's module
1731                     // but not the third module
1732                     newModes = 0;
1733                 }
1734                 // drop MODULE access
1735                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1736                 // teleport from this lookup class
1737                 plc = this.lookupClass;
1738             }
1739             if ((newModes & PACKAGE) != 0
1740                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1741                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1742             }
1743             // Allow nestmate lookups to be created without special privilege:
1744             if ((newModes & PRIVATE) != 0
1745                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1746                 newModes &= ~(PRIVATE|PROTECTED);
1747             }
1748             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1749                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1750                 // The requested class it not accessible from the lookup class.
1751                 // No permissions.
1752                 newModes = 0;
1753             }
1754             return newLookup(requestedLookupClass, plc, newModes);
1755         }
1756 
1757         /**
1758          * Creates a lookup on the same lookup class which this lookup object
1759          * finds members, but with a lookup mode that has lost the given lookup mode.
1760          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1761          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1762          * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1763          * {@link #UNCONDITIONAL UNCONDITIONAL}.
1764          *
1765          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1766          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1767          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1768          * lookup has no access.
1769          *
1770          * <p> If this lookup is not a public lookup, then the following applies
1771          * regardless of its {@linkplain #lookupModes() lookup modes}.
1772          * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1773          * dropped and so the resulting lookup mode will never have these access
1774          * capabilities. When dropping {@code PACKAGE}
1775          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1776          * access. When dropping {@code MODULE} then the resulting lookup will not
1777          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1778          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1779          *
1780          * @apiNote
1781          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1782          * delegate non-public access within the package of the lookup class without
1783          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1784          * A lookup with {@code MODULE} but not
1785          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1786          * the module of the lookup class without conferring package access.
1787          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1788          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1789          * to public classes accessible to both the module of the lookup class
1790          * and the module of the previous lookup class.
1791          *
1792          * @param modeToDrop the lookup mode to drop
1793          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1794          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1795          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1796          * or {@code UNCONDITIONAL}
1797          * @see MethodHandles#privateLookupIn
1798          * @since 9
1799          */
1800         public Lookup dropLookupMode(int modeToDrop) {
1801             int oldModes = lookupModes();
1802             int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1803             switch (modeToDrop) {
1804                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1805                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1806                 case PACKAGE: newModes &= ~(PRIVATE); break;
1807                 case PROTECTED:
1808                 case PRIVATE:
1809                 case ORIGINAL:
1810                 case UNCONDITIONAL: break;
1811                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1812             }
1813             if (newModes == oldModes) return this;  // return self if no change
1814             return newLookup(lookupClass(), previousLookupClass(), newModes);
1815         }
1816 
1817         /**
1818          * Creates and links a class or interface from {@code bytes}
1819          * with the same class loader and in the same runtime package and
1820          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1821          * {@linkplain #lookupClass() lookup class} as if calling
1822          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1823          * ClassLoader::defineClass}.
1824          *
1825          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1826          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1827          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1828          * that the lookup object was created by a caller in the runtime package (or derived
1829          * from a lookup originally created by suitably privileged code to a target class in
1830          * the runtime package). </p>
1831          *
1832          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1833          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1834          * same package as the lookup class. </p>
1835          *
1836          * <p> This method does not run the class initializer. The class initializer may
1837          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1838          * Specification</em>. </p>
1839          *
1840          * <p> If there is a security manager and this lookup does not have {@linkplain
1841          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1842          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1843          *
1844          * @param bytes the class bytes
1845          * @return the {@code Class} object for the class
1846          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1847          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1848          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1849          * than the lookup class or {@code bytes} is not a class or interface
1850          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1851          * @throws VerifyError if the newly created class cannot be verified
1852          * @throws LinkageError if the newly created class cannot be linked for any other reason
1853          * @throws SecurityException if a security manager is present and it
1854          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1855          * @throws NullPointerException if {@code bytes} is {@code null}
1856          * @since 9
1857          * @see Lookup#privateLookupIn
1858          * @see Lookup#dropLookupMode
1859          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1860          */
1861         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1862             ensureDefineClassPermission();
1863             if ((lookupModes() & PACKAGE) == 0)
1864                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1865             return makeClassDefiner(bytes.clone()).defineClass(false);
1866         }
1867 
1868         private void ensureDefineClassPermission() {
1869             if (allowedModes == TRUSTED)  return;
1870 
1871             if (!hasFullPrivilegeAccess()) {
1872                 @SuppressWarnings("removal")
1873                 SecurityManager sm = System.getSecurityManager();
1874                 if (sm != null)
1875                     sm.checkPermission(new RuntimePermission("defineClass"));
1876             }
1877         }
1878 
1879         /**
1880          * The set of class options that specify whether a hidden class created by
1881          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1882          * Lookup::defineHiddenClass} method is dynamically added as a new member
1883          * to the nest of a lookup class and/or whether a hidden class has
1884          * a strong relationship with the class loader marked as its defining loader.
1885          *
1886          * @since 15
1887          */
1888         public enum ClassOption {
1889             /**
1890              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1891              * of a lookup class as a nestmate.
1892              *
1893              * <p> A hidden nestmate class has access to the private members of all
1894              * classes and interfaces in the same nest.
1895              *
1896              * @see Class#getNestHost()
1897              */
1898             NESTMATE(NESTMATE_CLASS),
1899 
1900             /**
1901              * Specifies that a hidden class has a <em>strong</em>
1902              * relationship with the class loader marked as its defining loader,
1903              * as a normal class or interface has with its own defining loader.
1904              * This means that the hidden class may be unloaded if and only if
1905              * its defining loader is not reachable and thus may be reclaimed
1906              * by a garbage collector (JLS {@jls 12.7}).
1907              *
1908              * <p> By default, a hidden class or interface may be unloaded
1909              * even if the class loader that is marked as its defining loader is
1910              * <a href="../ref/package-summary.html#reachability">reachable</a>.
1911 
1912              *
1913              * @jls 12.7 Unloading of Classes and Interfaces
1914              */
1915             STRONG(STRONG_LOADER_LINK);
1916 
1917             /* the flag value is used by VM at define class time */
1918             private final int flag;
1919             ClassOption(int flag) {
1920                 this.flag = flag;
1921             }
1922 
1923             static int optionsToFlag(Set<ClassOption> options) {
1924                 int flags = 0;
1925                 for (ClassOption cp : options) {
1926                     flags |= cp.flag;
1927                 }
1928                 return flags;
1929             }
1930         }
1931 
1932         /**
1933          * Creates a <em>hidden</em> class or interface from {@code bytes},
1934          * returning a {@code Lookup} on the newly created class or interface.
1935          *
1936          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1937          * which either defines {@code C} directly or delegates to another class loader.
1938          * A class loader defines {@code C} directly by invoking
1939          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1940          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1941          * to derive {@code C} from a purported representation in {@code class} file format.
1942          * In situations where use of a class loader is undesirable, a class or interface
1943          * {@code C} can be created by this method instead. This method is capable of
1944          * defining {@code C}, and thereby creating it, without invoking
1945          * {@code ClassLoader::defineClass}.
1946          * Instead, this method defines {@code C} as if by arranging for
1947          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1948          * from a purported representation in {@code class} file format
1949          * using the following rules:
1950          *
1951          * <ol>
1952          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1953          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1954          * This level of access is needed to create {@code C} in the module
1955          * of the lookup class of this {@code Lookup}.</li>
1956          *
1957          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1958          * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1959          * The major and minor version may differ from the {@code class} file version
1960          * of the lookup class of this {@code Lookup}.</li>
1961          *
1962          * <li> The value of {@code this_class} must be a valid index in the
1963          * {@code constant_pool} table, and the entry at that index must be a valid
1964          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1965          * encoded in internal form that is specified by this structure. {@code N} must
1966          * denote a class or interface in the same package as the lookup class.</li>
1967          *
1968          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1969          * where {@code <suffix>} is an unqualified name.
1970          *
1971          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1972          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1973          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1974          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1975          * refers to the new {@code CONSTANT_Utf8_info} structure.
1976          *
1977          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1978          *
1979          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1980          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1981          * with the following adjustments:
1982          * <ul>
1983          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1984          * that includes a single {@code "."} character, even though this is not a valid
1985          * binary class or interface name in internal form.</li>
1986          *
1987          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1988          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1989          *
1990          * <li> {@code C} is considered to have the same runtime
1991          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1992          * and {@linkplain java.security.ProtectionDomain protection domain}
1993          * as the lookup class of this {@code Lookup}.
1994          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1995          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1996          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1997          * <ul>
1998          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1999          *      even though this is not a valid binary class or interface name.</li>
2000          * <li> {@link Class#descriptorString()} returns the string
2001          *      {@code "L" + N + "." + <suffix> + ";"},
2002          *      even though this is not a valid type descriptor name.</li>
2003          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
2004          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
2005          * </ul>
2006          * </ul>
2007          * </li>
2008          * </ol>
2009          *
2010          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
2011          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
2012          * <ul>
2013          * <li> During verification, whenever it is necessary to load the class named
2014          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
2015          * made of any class loader.</li>
2016          *
2017          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
2018          * by {@code this_class}, the symbolic reference is considered to be resolved to
2019          * {@code C} and resolution always succeeds immediately.</li>
2020          * </ul>
2021          *
2022          * <p> If the {@code initialize} parameter is {@code true},
2023          * then {@code C} is initialized by the Java Virtual Machine.
2024          *
2025          * <p> The newly created class or interface {@code C} serves as the
2026          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
2027          * returned by this method. {@code C} is <em>hidden</em> in the sense that
2028          * no other class or interface can refer to {@code C} via a constant pool entry.
2029          * That is, a hidden class or interface cannot be named as a supertype, a field type,
2030          * a method parameter type, or a method return type by any other class.
2031          * This is because a hidden class or interface does not have a binary name, so
2032          * there is no internal form available to record in any class's constant pool.
2033          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
2034          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
2035          * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class)
2036          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
2037          * JVM Tool Interface</a>.
2038          *
2039          * <p> A class or interface created by
2040          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
2041          * a class loader} has a strong relationship with that class loader.
2042          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
2043          * that {@linkplain Class#getClassLoader() defined it}.
2044          * This means that a class created by a class loader may be unloaded if and
2045          * only if its defining loader is not reachable and thus may be reclaimed
2046          * by a garbage collector (JLS {@jls 12.7}).
2047          *
2048          * By default, however, a hidden class or interface may be unloaded even if
2049          * the class loader that is marked as its defining loader is
2050          * <a href="../ref/package-summary.html#reachability">reachable</a>.
2051          * This behavior is useful when a hidden class or interface serves multiple
2052          * classes defined by arbitrary class loaders.  In other cases, a hidden
2053          * class or interface may be linked to a single class (or a small number of classes)
2054          * with the same defining loader as the hidden class or interface.
2055          * In such cases, where the hidden class or interface must be coterminous
2056          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
2057          * option may be passed in {@code options}.
2058          * This arranges for a hidden class to have the same strong relationship
2059          * with the class loader marked as its defining loader,
2060          * as a normal class or interface has with its own defining loader.
2061          *
2062          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
2063          * may still prevent a hidden class or interface from being
2064          * unloaded by ensuring that the {@code Class} object is reachable.
2065          *
2066          * <p> The unloading characteristics are set for each hidden class when it is
2067          * defined, and cannot be changed later.  An advantage of allowing hidden classes
2068          * to be unloaded independently of the class loader marked as their defining loader
2069          * is that a very large number of hidden classes may be created by an application.
2070          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
2071          * just as if normal classes were created by class loaders.
2072          *
2073          * <p> Classes and interfaces in a nest are allowed to have mutual access to
2074          * their private members.  The nest relationship is determined by
2075          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
2076          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
2077          * By default, a hidden class belongs to a nest consisting only of itself
2078          * because a hidden class has no binary name.
2079          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
2080          * to create a hidden class or interface {@code C} as a member of a nest.
2081          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
2082          * in the {@code ClassFile} structure from which {@code C} was derived.
2083          * Instead, the following rules determine the nest host of {@code C}:
2084          * <ul>
2085          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
2086          *     been determined, then let {@code H} be the nest host of the lookup class.
2087          *     Otherwise, the nest host of the lookup class is determined using the
2088          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
2089          * <li>The nest host of {@code C} is determined to be {@code H},
2090          *     the nest host of the lookup class.</li>
2091          * </ul>
2092          *
2093          * <p> A hidden class or interface may be serializable, but this requires a custom
2094          * serialization mechanism in order to ensure that instances are properly serialized
2095          * and deserialized. The default serialization mechanism supports only classes and
2096          * interfaces that are discoverable by their class name.
2097          *
2098          * @param bytes the bytes that make up the class data,
2099          * in the format of a valid {@code class} file as defined by
2100          * <cite>The Java Virtual Machine Specification</cite>.
2101          * @param initialize if {@code true} the class will be initialized.
2102          * @param options {@linkplain ClassOption class options}
2103          * @return the {@code Lookup} object on the hidden class,
2104          * with {@linkplain #ORIGINAL original} and
2105          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2106          *
2107          * @throws IllegalAccessException if this {@code Lookup} does not have
2108          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2109          * @throws SecurityException if a security manager is present and it
2110          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2111          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2112          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2113          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2114          * than the lookup class or {@code bytes} is not a class or interface
2115          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2116          * @throws IncompatibleClassChangeError if the class or interface named as
2117          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2118          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2119          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2120          * {@code C} is {@code C} itself
2121          * @throws VerifyError if the newly created class cannot be verified
2122          * @throws LinkageError if the newly created class cannot be linked for any other reason
2123          * @throws NullPointerException if any parameter is {@code null}
2124          *
2125          * @since 15
2126          * @see Class#isHidden()
2127          * @jvms 4.2.1 Binary Class and Interface Names
2128          * @jvms 4.2.2 Unqualified Names
2129          * @jvms 4.7.28 The {@code NestHost} Attribute
2130          * @jvms 4.7.29 The {@code NestMembers} Attribute
2131          * @jvms 5.4.3.1 Class and Interface Resolution
2132          * @jvms 5.4.4 Access Control
2133          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2134          * @jvms 5.4 Linking
2135          * @jvms 5.5 Initialization
2136          * @jls 12.7 Unloading of Classes and Interfaces
2137          */
2138         @SuppressWarnings("doclint:reference") // cross-module links
2139         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2140                 throws IllegalAccessException
2141         {
2142             Objects.requireNonNull(bytes);
2143             Objects.requireNonNull(options);
2144 
2145             ensureDefineClassPermission();
2146             if (!hasFullPrivilegeAccess()) {
2147                 throw new IllegalAccessException(this + " does not have full privilege access");
2148             }
2149 
2150             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
2151         }
2152 
2153         /**
2154          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2155          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2156          * returning a {@code Lookup} on the newly created class or interface.
2157          *
2158          * <p> This method is equivalent to calling
2159          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2160          * as if the hidden class is injected with a private static final <i>unnamed</i>
2161          * field which is initialized with the given {@code classData} at
2162          * the first instruction of the class initializer.
2163          * The newly created class is linked by the Java Virtual Machine.
2164          *
2165          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2166          * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2167          * methods can be used to retrieve the {@code classData}.
2168          *
2169          * @apiNote
2170          * A framework can create a hidden class with class data with one or more
2171          * objects and load the class data as dynamically-computed constant(s)
2172          * via a bootstrap method.  {@link MethodHandles#classData(Lookup, String, Class)
2173          * Class data} is accessible only to the lookup object created by the newly
2174          * defined hidden class but inaccessible to other members in the same nest
2175          * (unlike private static fields that are accessible to nestmates).
2176          * Care should be taken w.r.t. mutability for example when passing
2177          * an array or other mutable structure through the class data.
2178          * Changing any value stored in the class data at runtime may lead to
2179          * unpredictable behavior.
2180          * If the class data is a {@code List}, it is good practice to make it
2181          * unmodifiable for example via {@link List#of List::of}.
2182          *
2183          * @param bytes     the class bytes
2184          * @param classData pre-initialized class data
2185          * @param initialize if {@code true} the class will be initialized.
2186          * @param options   {@linkplain ClassOption class options}
2187          * @return the {@code Lookup} object on the hidden class,
2188          * with {@linkplain #ORIGINAL original} and
2189          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2190          *
2191          * @throws IllegalAccessException if this {@code Lookup} does not have
2192          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2193          * @throws SecurityException if a security manager is present and it
2194          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2195          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2196          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2197          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2198          * than the lookup class or {@code bytes} is not a class or interface
2199          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2200          * @throws IncompatibleClassChangeError if the class or interface named as
2201          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2202          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2203          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2204          * {@code C} is {@code C} itself
2205          * @throws VerifyError if the newly created class cannot be verified
2206          * @throws LinkageError if the newly created class cannot be linked for any other reason
2207          * @throws NullPointerException if any parameter is {@code null}
2208          *
2209          * @since 16
2210          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2211          * @see Class#isHidden()
2212          * @see MethodHandles#classData(Lookup, String, Class)
2213          * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2214          * @jvms 4.2.1 Binary Class and Interface Names
2215          * @jvms 4.2.2 Unqualified Names
2216          * @jvms 4.7.28 The {@code NestHost} Attribute
2217          * @jvms 4.7.29 The {@code NestMembers} Attribute
2218          * @jvms 5.4.3.1 Class and Interface Resolution
2219          * @jvms 5.4.4 Access Control
2220          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2221          * @jvms 5.4 Linking
2222          * @jvms 5.5 Initialization
2223          * @jls 12.7 Unloading of Classes and Interface
2224          */
2225         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2226                 throws IllegalAccessException
2227         {
2228             Objects.requireNonNull(bytes);
2229             Objects.requireNonNull(classData);
2230             Objects.requireNonNull(options);
2231 
2232             ensureDefineClassPermission();
2233             if (!hasFullPrivilegeAccess()) {
2234                 throw new IllegalAccessException(this + " does not have full privilege access");
2235             }
2236 
2237             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2238                        .defineClassAsLookup(initialize, classData);
2239         }
2240 
2241         // A default dumper for writing class files passed to Lookup::defineClass
2242         // and Lookup::defineHiddenClass to disk for debugging purposes.  To enable,
2243         // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or
2244         //     -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true
2245         //
2246         // This default dumper does not dump hidden classes defined by LambdaMetafactory
2247         // and LambdaForms and method handle internals.  They are dumped via
2248         // different ClassFileDumpers.
2249         private static ClassFileDumper defaultDumper() {
2250             return DEFAULT_DUMPER;
2251         }
2252 
2253         private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance(
2254                 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES");
2255 
2256         static class ClassFile {
2257             final String name;  // internal name
2258             final int accessFlags;
2259             final byte[] bytes;
2260             ClassFile(String name, int accessFlags, byte[] bytes) {
2261                 this.name = name;
2262                 this.accessFlags = accessFlags;
2263                 this.bytes = bytes;
2264             }
2265 
2266             static ClassFile newInstanceNoCheck(String name, byte[] bytes) {
2267                 return new ClassFile(name, 0, bytes);
2268             }
2269 
2270             /**
2271              * This method checks the class file version and the structure of `this_class`.
2272              * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2273              * that is in the named package.
2274              *
2275              * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2276              * or the class is not in the given package name.
2277              */
2278             static ClassFile newInstance(byte[] bytes, String pkgName) {
2279                 var cf = readClassFile(bytes);
2280 
2281                 // check if it's in the named package
2282                 int index = cf.name.lastIndexOf('/');
2283                 String pn = (index == -1) ? "" : cf.name.substring(0, index).replace('/', '.');
2284                 if (!pn.equals(pkgName)) {
2285                     throw newIllegalArgumentException(cf.name + " not in same package as lookup class");
2286                 }
2287                 return cf;
2288             }
2289 
2290             private static ClassFile readClassFile(byte[] bytes) {
2291                 int magic = readInt(bytes, 0);
2292                 if (magic != 0xCAFEBABE) {
2293                     throw new ClassFormatError("Incompatible magic value: " + magic);
2294                 }
2295                 int minor = readUnsignedShort(bytes, 4);
2296                 int major = readUnsignedShort(bytes, 6);
2297                 if (!VM.isSupportedClassFileVersion(major, minor)) {
2298                     throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2299                 }
2300 
2301                 String name;
2302                 int accessFlags;
2303                 try {
2304                     ClassReader reader = new ClassReader(bytes);
2305                     // ClassReader does not check if `this_class` is CONSTANT_Class_info
2306                     // workaround to read `this_class` using readConst and validate the value
2307                     int thisClass = reader.readUnsignedShort(reader.header + 2);
2308                     Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]);
2309                     if (!(constant instanceof Type type)) {
2310                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2311                     }
2312                     if (!type.getDescriptor().startsWith("L")) {
2313                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2314                     }
2315                     name = type.getInternalName();
2316                     accessFlags = reader.readUnsignedShort(reader.header);
2317                 } catch (RuntimeException e) {
2318                     // ASM exceptions are poorly specified
2319                     ClassFormatError cfe = new ClassFormatError();
2320                     cfe.initCause(e);
2321                     throw cfe;
2322                 }
2323                 // must be a class or interface
2324                 if ((accessFlags & Opcodes.ACC_MODULE) != 0) {
2325                     throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2326                 }
2327                 return new ClassFile(name, accessFlags, bytes);
2328             }
2329 
2330             private static int readInt(byte[] bytes, int offset) {
2331                 if ((offset+4) > bytes.length) {
2332                     throw new ClassFormatError("Invalid ClassFile structure");
2333                 }
2334                 return ((bytes[offset] & 0xFF) << 24)
2335                         | ((bytes[offset + 1] & 0xFF) << 16)
2336                         | ((bytes[offset + 2] & 0xFF) << 8)
2337                         | (bytes[offset + 3] & 0xFF);
2338             }
2339 
2340             private static int readUnsignedShort(byte[] bytes, int offset) {
2341                 if ((offset+2) > bytes.length) {
2342                     throw new ClassFormatError("Invalid ClassFile structure");
2343                 }
2344                 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2345             }
2346         }
2347 
2348         /*
2349          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2350          * from the given bytes.
2351          *
2352          * Caller should make a defensive copy of the arguments if needed
2353          * before calling this factory method.
2354          *
2355          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2356          * {@code bytes} denotes a class in a different package than the lookup class
2357          */
2358         private ClassDefiner makeClassDefiner(byte[] bytes) {
2359             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2360             return new ClassDefiner(this, cf, STRONG_LOADER_LINK, defaultDumper());
2361         }
2362 
2363         /**
2364          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2365          * from the given bytes.  No package name check on the given bytes.
2366          *
2367          * @param name    internal name
2368          * @param bytes   class bytes
2369          * @param dumper  dumper to write the given bytes to the dumper's output directory
2370          * @return ClassDefiner that defines a normal class of the given bytes.
2371          */
2372         ClassDefiner makeClassDefiner(String name, byte[] bytes, ClassFileDumper dumper) {
2373             // skip package name validation
2374             ClassFile cf = ClassFile.newInstanceNoCheck(name, bytes);
2375             return new ClassDefiner(this, cf, STRONG_LOADER_LINK, dumper);
2376         }
2377 
2378         /**
2379          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2380          * from the given bytes.  The name must be in the same package as the lookup class.
2381          *
2382          * Caller should make a defensive copy of the arguments if needed
2383          * before calling this factory method.
2384          *
2385          * @param bytes   class bytes
2386          * @param dumper dumper to write the given bytes to the dumper's output directory
2387          * @return ClassDefiner that defines a hidden class of the given bytes.
2388          *
2389          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2390          * {@code bytes} denotes a class in a different package than the lookup class
2391          */
2392         ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) {
2393             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2394             return makeHiddenClassDefiner(cf, Set.of(), false, dumper);
2395         }
2396 
2397         /**
2398          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2399          * from the given bytes and options.
2400          * The name must be in the same package as the lookup class.
2401          *
2402          * Caller should make a defensive copy of the arguments if needed
2403          * before calling this factory method.
2404          *
2405          * @param bytes   class bytes
2406          * @param options class options
2407          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2408          * @return ClassDefiner that defines a hidden class of the given bytes and options
2409          *
2410          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2411          * {@code bytes} denotes a class in a different package than the lookup class
2412          */
2413         private ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2414                                                     Set<ClassOption> options,
2415                                                     boolean accessVmAnnotations) {
2416             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2417             return makeHiddenClassDefiner(cf, options, accessVmAnnotations, defaultDumper());
2418         }
2419 
2420         /**
2421          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2422          * from the given bytes and the given options.  No package name check on the given bytes.
2423          *
2424          * @param name    internal name that specifies the prefix of the hidden class
2425          * @param bytes   class bytes
2426          * @param options class options
2427          * @param dumper  dumper to write the given bytes to the dumper's output directory
2428          * @return ClassDefiner that defines a hidden class of the given bytes and options.
2429          */
2430         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options, ClassFileDumper dumper) {
2431             Objects.requireNonNull(dumper);
2432             // skip name and access flags validation
2433             return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false, dumper);
2434         }
2435 
2436         /**
2437          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2438          * from the given class file and options.
2439          *
2440          * @param cf ClassFile
2441          * @param options class options
2442          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2443          * @param dumper dumper to write the given bytes to the dumper's output directory
2444          */
2445         private ClassDefiner makeHiddenClassDefiner(ClassFile cf,
2446                                                     Set<ClassOption> options,
2447                                                     boolean accessVmAnnotations,
2448                                                     ClassFileDumper dumper) {
2449             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2450             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2451                 // jdk.internal.vm.annotations are permitted for classes
2452                 // defined to boot loader and platform loader
2453                 flags |= ACCESS_VM_ANNOTATIONS;
2454             }
2455 
2456             return new ClassDefiner(this, cf, flags, dumper);
2457         }
2458 
2459         static class ClassDefiner {
2460             private final Lookup lookup;
2461             private final String name;  // internal name
2462             private final byte[] bytes;
2463             private final int classFlags;
2464             private final ClassFileDumper dumper;
2465 
2466             private ClassDefiner(Lookup lookup, ClassFile cf, int flags, ClassFileDumper dumper) {
2467                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2468                 this.lookup = lookup;
2469                 this.bytes = cf.bytes;
2470                 this.name = cf.name;
2471                 this.classFlags = flags;
2472                 this.dumper = dumper;
2473             }
2474 
2475             String internalName() {
2476                 return name;
2477             }
2478 
2479             Class<?> defineClass(boolean initialize) {
2480                 return defineClass(initialize, null);
2481             }
2482 
2483             Lookup defineClassAsLookup(boolean initialize) {
2484                 Class<?> c = defineClass(initialize, null);
2485                 return new Lookup(c, null, FULL_POWER_MODES);
2486             }
2487 
2488             /**
2489              * Defines the class of the given bytes and the given classData.
2490              * If {@code initialize} parameter is true, then the class will be initialized.
2491              *
2492              * @param initialize true if the class to be initialized
2493              * @param classData classData or null
2494              * @return the class
2495              *
2496              * @throws LinkageError linkage error
2497              */
2498             Class<?> defineClass(boolean initialize, Object classData) {
2499                 Class<?> lookupClass = lookup.lookupClass();
2500                 ClassLoader loader = lookupClass.getClassLoader();
2501                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2502                 Class<?> c = null;
2503                 try {
2504                     c = SharedSecrets.getJavaLangAccess()
2505                             .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2506                     assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2507                     return c;
2508                 } finally {
2509                     // dump the classfile for debugging
2510                     if (dumper.isEnabled()) {
2511                         String name = internalName();
2512                         if (c != null) {
2513                             dumper.dumpClass(name, c, bytes);
2514                         } else {
2515                             dumper.dumpFailedClass(name, bytes);
2516                         }
2517                     }
2518                 }
2519             }
2520 
2521             /**
2522              * Defines the class of the given bytes and the given classData.
2523              * If {@code initialize} parameter is true, then the class will be initialized.
2524              *
2525              * @param initialize true if the class to be initialized
2526              * @param classData classData or null
2527              * @return a Lookup for the defined class
2528              *
2529              * @throws LinkageError linkage error
2530              */
2531             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2532                 Class<?> c = defineClass(initialize, classData);
2533                 return new Lookup(c, null, FULL_POWER_MODES);
2534             }
2535 
2536             private boolean isNestmate() {
2537                 return (classFlags & NESTMATE_CLASS) != 0;
2538             }
2539         }
2540 
2541         private ProtectionDomain lookupClassProtectionDomain() {
2542             ProtectionDomain pd = cachedProtectionDomain;
2543             if (pd == null) {
2544                 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2545             }
2546             return pd;
2547         }
2548 
2549         // cached protection domain
2550         private volatile ProtectionDomain cachedProtectionDomain;
2551 
2552         // Make sure outer class is initialized first.
2553         static { IMPL_NAMES.getClass(); }
2554 
2555         /** Package-private version of lookup which is trusted. */
2556         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2557 
2558         /** Version of lookup which is trusted minimally.
2559          *  It can only be used to create method handles to publicly accessible
2560          *  members in packages that are exported unconditionally.
2561          */
2562         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2563 
2564         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2565             String name = lookupClass.getName();
2566             if (name.startsWith("java.lang.invoke."))
2567                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2568         }
2569 
2570         /**
2571          * Displays the name of the class from which lookups are to be made,
2572          * followed by "/" and the name of the {@linkplain #previousLookupClass()
2573          * previous lookup class} if present.
2574          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2575          * If there are restrictions on the access permitted to this lookup,
2576          * this is indicated by adding a suffix to the class name, consisting
2577          * of a slash and a keyword.  The keyword represents the strongest
2578          * allowed access, and is chosen as follows:
2579          * <ul>
2580          * <li>If no access is allowed, the suffix is "/noaccess".
2581          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2582          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2583          * <li>If only public and module access are allowed, the suffix is "/module".
2584          * <li>If public and package access are allowed, the suffix is "/package".
2585          * <li>If public, package, and private access are allowed, the suffix is "/private".
2586          * </ul>
2587          * If none of the above cases apply, it is the case that
2588          * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2589          * (public, module, package, private, and protected) is allowed.
2590          * In this case, no suffix is added.
2591          * This is true only of an object obtained originally from
2592          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2593          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2594          * always have restricted access, and will display a suffix.
2595          * <p>
2596          * (It may seem strange that protected access should be
2597          * stronger than private access.  Viewed independently from
2598          * package access, protected access is the first to be lost,
2599          * because it requires a direct subclass relationship between
2600          * caller and callee.)
2601          * @see #in
2602          *
2603          * @revised 9
2604          */
2605         @Override
2606         public String toString() {
2607             String cname = lookupClass.getName();
2608             if (prevLookupClass != null)
2609                 cname += "/" + prevLookupClass.getName();
2610             switch (allowedModes) {
2611             case 0:  // no privileges
2612                 return cname + "/noaccess";
2613             case UNCONDITIONAL:
2614                 return cname + "/publicLookup";
2615             case PUBLIC:
2616                 return cname + "/public";
2617             case PUBLIC|MODULE:
2618                 return cname + "/module";
2619             case PUBLIC|PACKAGE:
2620             case PUBLIC|MODULE|PACKAGE:
2621                 return cname + "/package";
2622             case PUBLIC|PACKAGE|PRIVATE:
2623             case PUBLIC|MODULE|PACKAGE|PRIVATE:
2624                     return cname + "/private";
2625             case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2626             case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2627             case FULL_POWER_MODES:
2628                     return cname;
2629             case TRUSTED:
2630                 return "/trusted";  // internal only; not exported
2631             default:  // Should not happen, but it's a bitfield...
2632                 cname = cname + "/" + Integer.toHexString(allowedModes);
2633                 assert(false) : cname;
2634                 return cname;
2635             }
2636         }
2637 
2638         /**
2639          * Produces a method handle for a static method.
2640          * The type of the method handle will be that of the method.
2641          * (Since static methods do not take receivers, there is no
2642          * additional receiver argument inserted into the method handle type,
2643          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2644          * The method and all its argument types must be accessible to the lookup object.
2645          * <p>
2646          * The returned method handle will have
2647          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2648          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2649          * <p>
2650          * If the returned method handle is invoked, the method's class will
2651          * be initialized, if it has not already been initialized.
2652          * <p><b>Example:</b>
2653          * {@snippet lang="java" :
2654 import static java.lang.invoke.MethodHandles.*;
2655 import static java.lang.invoke.MethodType.*;
2656 ...
2657 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2658   "asList", methodType(List.class, Object[].class));
2659 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2660          * }
2661          * @param refc the class from which the method is accessed
2662          * @param name the name of the method
2663          * @param type the type of the method
2664          * @return the desired method handle
2665          * @throws NoSuchMethodException if the method does not exist
2666          * @throws IllegalAccessException if access checking fails,
2667          *                                or if the method is not {@code static},
2668          *                                or if the method's variable arity modifier bit
2669          *                                is set and {@code asVarargsCollector} fails
2670          * @throws    SecurityException if a security manager is present and it
2671          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2672          * @throws NullPointerException if any argument is null
2673          */
2674         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2675             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2676             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2677         }
2678 
2679         /**
2680          * Produces a method handle for a virtual method.
2681          * The type of the method handle will be that of the method,
2682          * with the receiver type (usually {@code refc}) prepended.
2683          * The method and all its argument types must be accessible to the lookup object.
2684          * <p>
2685          * When called, the handle will treat the first argument as a receiver
2686          * and, for non-private methods, dispatch on the receiver's type to determine which method
2687          * implementation to enter.
2688          * For private methods the named method in {@code refc} will be invoked on the receiver.
2689          * (The dispatching action is identical with that performed by an
2690          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2691          * <p>
2692          * The first argument will be of type {@code refc} if the lookup
2693          * class has full privileges to access the member.  Otherwise
2694          * the member must be {@code protected} and the first argument
2695          * will be restricted in type to the lookup class.
2696          * <p>
2697          * The returned method handle will have
2698          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2699          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2700          * <p>
2701          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2702          * instructions and method handles produced by {@code findVirtual},
2703          * if the class is {@code MethodHandle} and the name string is
2704          * {@code invokeExact} or {@code invoke}, the resulting
2705          * method handle is equivalent to one produced by
2706          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2707          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2708          * with the same {@code type} argument.
2709          * <p>
2710          * If the class is {@code VarHandle} and the name string corresponds to
2711          * the name of a signature-polymorphic access mode method, the resulting
2712          * method handle is equivalent to one produced by
2713          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2714          * the access mode corresponding to the name string and with the same
2715          * {@code type} arguments.
2716          * <p>
2717          * <b>Example:</b>
2718          * {@snippet lang="java" :
2719 import static java.lang.invoke.MethodHandles.*;
2720 import static java.lang.invoke.MethodType.*;
2721 ...
2722 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2723   "concat", methodType(String.class, String.class));
2724 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2725   "hashCode", methodType(int.class));
2726 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2727   "hashCode", methodType(int.class));
2728 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2729 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2730 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2731 // interface method:
2732 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2733   "subSequence", methodType(CharSequence.class, int.class, int.class));
2734 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2735 // constructor "internal method" must be accessed differently:
2736 MethodType MT_newString = methodType(void.class); //()V for new String()
2737 try { assertEquals("impossible", lookup()
2738         .findVirtual(String.class, "<init>", MT_newString));
2739  } catch (NoSuchMethodException ex) { } // OK
2740 MethodHandle MH_newString = publicLookup()
2741   .findConstructor(String.class, MT_newString);
2742 assertEquals("", (String) MH_newString.invokeExact());
2743          * }
2744          *
2745          * @param refc the class or interface from which the method is accessed
2746          * @param name the name of the method
2747          * @param type the type of the method, with the receiver argument omitted
2748          * @return the desired method handle
2749          * @throws NoSuchMethodException if the method does not exist
2750          * @throws IllegalAccessException if access checking fails,
2751          *                                or if the method is {@code static},
2752          *                                or if the method's variable arity modifier bit
2753          *                                is set and {@code asVarargsCollector} fails
2754          * @throws    SecurityException if a security manager is present and it
2755          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2756          * @throws NullPointerException if any argument is null
2757          */
2758         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2759             if (refc == MethodHandle.class) {
2760                 MethodHandle mh = findVirtualForMH(name, type);
2761                 if (mh != null)  return mh;
2762             } else if (refc == VarHandle.class) {
2763                 MethodHandle mh = findVirtualForVH(name, type);
2764                 if (mh != null)  return mh;
2765             }
2766             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2767             MemberName method = resolveOrFail(refKind, refc, name, type);
2768             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2769         }
2770         private MethodHandle findVirtualForMH(String name, MethodType type) {
2771             // these names require special lookups because of the implicit MethodType argument
2772             if ("invoke".equals(name))
2773                 return invoker(type);
2774             if ("invokeExact".equals(name))
2775                 return exactInvoker(type);
2776             assert(!MemberName.isMethodHandleInvokeName(name));
2777             return null;
2778         }
2779         private MethodHandle findVirtualForVH(String name, MethodType type) {
2780             try {
2781                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2782             } catch (IllegalArgumentException e) {
2783                 return null;
2784             }
2785         }
2786 
2787         /**
2788          * Produces a method handle which creates an object and initializes it, using
2789          * the constructor of the specified type.
2790          * The parameter types of the method handle will be those of the constructor,
2791          * while the return type will be a reference to the constructor's class.
2792          * The constructor and all its argument types must be accessible to the lookup object.
2793          * <p>
2794          * The requested type must have a return type of {@code void}.
2795          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2796          * <p>
2797          * The returned method handle will have
2798          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2799          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2800          * <p>
2801          * If the returned method handle is invoked, the constructor's class will
2802          * be initialized, if it has not already been initialized.
2803          * <p><b>Example:</b>
2804          * {@snippet lang="java" :
2805 import static java.lang.invoke.MethodHandles.*;
2806 import static java.lang.invoke.MethodType.*;
2807 ...
2808 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2809   ArrayList.class, methodType(void.class, Collection.class));
2810 Collection orig = Arrays.asList("x", "y");
2811 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2812 assert(orig != copy);
2813 assertEquals(orig, copy);
2814 // a variable-arity constructor:
2815 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2816   ProcessBuilder.class, methodType(void.class, String[].class));
2817 ProcessBuilder pb = (ProcessBuilder)
2818   MH_newProcessBuilder.invoke("x", "y", "z");
2819 assertEquals("[x, y, z]", pb.command().toString());
2820          * }
2821          * @param refc the class or interface from which the method is accessed
2822          * @param type the type of the method, with the receiver argument omitted, and a void return type
2823          * @return the desired method handle
2824          * @throws NoSuchMethodException if the constructor does not exist
2825          * @throws IllegalAccessException if access checking fails
2826          *                                or if the method's variable arity modifier bit
2827          *                                is set and {@code asVarargsCollector} fails
2828          * @throws    SecurityException if a security manager is present and it
2829          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2830          * @throws NullPointerException if any argument is null
2831          */
2832         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2833             if (refc.isArray()) {
2834                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2835             }
2836             String name = ConstantDescs.INIT_NAME;
2837             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2838             return getDirectConstructor(refc, ctor);
2839         }
2840 
2841         /**
2842          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2843          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2844          * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2845          * and then determines whether the class is accessible to this lookup object.
2846          * <p>
2847          * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}.
2848          * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences
2849          * of {@code '['} and followed by the element type as encoded in the
2850          * {@linkplain Class##nameFormat table} specified in {@link Class#getName}.
2851          * <p>
2852          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2853          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2854          *
2855          * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class
2856          *                   or the string representing an array class
2857          * @return the requested class.
2858          * @throws SecurityException if a security manager is present and it
2859          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2860          * @throws LinkageError if the linkage fails
2861          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2862          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2863          * modes.
2864          * @throws NullPointerException if {@code targetName} is null
2865          * @since 9
2866          * @jvms 5.4.3.1 Class and Interface Resolution
2867          */
2868         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2869             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2870             return accessClass(targetClass);
2871         }
2872 
2873         /**
2874          * Ensures that {@code targetClass} has been initialized. The class
2875          * to be initialized must be {@linkplain #accessClass accessible}
2876          * to this {@code Lookup} object.  This method causes {@code targetClass}
2877          * to be initialized if it has not been already initialized,
2878          * as specified in JVMS {@jvms 5.5}.
2879          *
2880          * <p>
2881          * This method returns when {@code targetClass} is fully initialized, or
2882          * when {@code targetClass} is being initialized by the current thread.
2883          *
2884          * @param <T> the type of the class to be initialized
2885          * @param targetClass the class to be initialized
2886          * @return {@code targetClass} that has been initialized, or that is being
2887          *         initialized by the current thread.
2888          *
2889          * @throws  IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2890          *          or array class
2891          * @throws  IllegalAccessException if {@code targetClass} is not
2892          *          {@linkplain #accessClass accessible} to this lookup
2893          * @throws  ExceptionInInitializerError if the class initialization provoked
2894          *          by this method fails
2895          * @throws  SecurityException if a security manager is present and it
2896          *          <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2897          * @since 15
2898          * @jvms 5.5 Initialization
2899          */
2900         public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException {
2901             if (targetClass.isPrimitive())
2902                 throw new IllegalArgumentException(targetClass + " is a primitive class");
2903             if (targetClass.isArray())
2904                 throw new IllegalArgumentException(targetClass + " is an array class");
2905 
2906             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2907                 throw makeAccessException(targetClass);
2908             }
2909             checkSecurityManager(targetClass);
2910 
2911             // ensure class initialization
2912             Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2913             return targetClass;
2914         }
2915 
2916         /*
2917          * Returns IllegalAccessException due to access violation to the given targetClass.
2918          *
2919          * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2920          * which verifies access to a class rather a member.
2921          */
2922         private IllegalAccessException makeAccessException(Class<?> targetClass) {
2923             String message = "access violation: "+ targetClass;
2924             if (this == MethodHandles.publicLookup()) {
2925                 message += ", from public Lookup";
2926             } else {
2927                 Module m = lookupClass().getModule();
2928                 message += ", from " + lookupClass() + " (" + m + ")";
2929                 if (prevLookupClass != null) {
2930                     message += ", previous lookup " +
2931                             prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2932                 }
2933             }
2934             return new IllegalAccessException(message);
2935         }
2936 
2937         /**
2938          * Determines if a class can be accessed from the lookup context defined by
2939          * this {@code Lookup} object. The static initializer of the class is not run.
2940          * If {@code targetClass} is an array class, {@code targetClass} is accessible
2941          * if the element type of the array class is accessible.  Otherwise,
2942          * {@code targetClass} is determined as accessible as follows.
2943          *
2944          * <p>
2945          * If {@code targetClass} is in the same module as the lookup class,
2946          * the lookup class is {@code LC} in module {@code M1} and
2947          * the previous lookup class is in module {@code M0} or
2948          * {@code null} if not present,
2949          * {@code targetClass} is accessible if and only if one of the following is true:
2950          * <ul>
2951          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2952          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2953          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2954          *     in the same runtime package of {@code LC}.</li>
2955          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2956          *     a public type in {@code M1}.</li>
2957          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2958          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2959          *     if the previous lookup class is present; otherwise, {@code targetClass}
2960          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2961          * </ul>
2962          *
2963          * <p>
2964          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2965          * can access public types in all modules when the type is in a package
2966          * that is exported unconditionally.
2967          * <p>
2968          * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2969          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2970          * is inaccessible.
2971          * <p>
2972          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2973          * {@code M1} is the module containing {@code lookupClass} and
2974          * {@code M2} is the module containing {@code targetClass},
2975          * then {@code targetClass} is accessible if and only if
2976          * <ul>
2977          * <li>{@code M1} reads {@code M2}, and
2978          * <li>{@code targetClass} is public and in a package exported by
2979          *     {@code M2} at least to {@code M1}.
2980          * </ul>
2981          * <p>
2982          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2983          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2984          * containing the previous lookup class, then {@code targetClass} is accessible
2985          * if and only if one of the following is true:
2986          * <ul>
2987          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2988          *     {@linkplain Module#reads reads} {@code M0} and the type is
2989          *     in a package that is exported to at least {@code M1}.
2990          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2991          *     {@linkplain Module#reads reads} {@code M1} and the type is
2992          *     in a package that is exported to at least {@code M0}.
2993          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2994          *     and {@code M1} reads {@code M2} and the type is in a package
2995          *     that is exported to at least both {@code M0} and {@code M2}.
2996          * </ul>
2997          * <p>
2998          * Otherwise, {@code targetClass} is not accessible.
2999          *
3000          * @param <T> the type of the class to be access-checked
3001          * @param targetClass the class to be access-checked
3002          * @return {@code targetClass} that has been access-checked
3003          * @throws IllegalAccessException if the class is not accessible from the lookup class
3004          * and previous lookup class, if present, using the allowed access modes.
3005          * @throws SecurityException if a security manager is present and it
3006          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3007          * @throws NullPointerException if {@code targetClass} is {@code null}
3008          * @since 9
3009          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
3010          */
3011         public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException {
3012             if (!isClassAccessible(targetClass)) {
3013                 throw makeAccessException(targetClass);
3014             }
3015             checkSecurityManager(targetClass);
3016             return targetClass;
3017         }
3018 
3019         /**
3020          * Produces an early-bound method handle for a virtual method.
3021          * It will bypass checks for overriding methods on the receiver,
3022          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3023          * instruction from within the explicitly specified {@code specialCaller}.
3024          * The type of the method handle will be that of the method,
3025          * with a suitably restricted receiver type prepended.
3026          * (The receiver type will be {@code specialCaller} or a subtype.)
3027          * The method and all its argument types must be accessible
3028          * to the lookup object.
3029          * <p>
3030          * Before method resolution,
3031          * if the explicitly specified caller class is not identical with the
3032          * lookup class, or if this lookup object does not have
3033          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3034          * privileges, the access fails.
3035          * <p>
3036          * The returned method handle will have
3037          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3038          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3039          * <p style="font-size:smaller;">
3040          * <em>(Note:  JVM internal methods named {@value ConstantDescs#INIT_NAME}
3041          * are not visible to this API,
3042          * even though the {@code invokespecial} instruction can refer to them
3043          * in special circumstances.  Use {@link #findConstructor findConstructor}
3044          * to access instance initialization methods in a safe manner.)</em>
3045          * <p><b>Example:</b>
3046          * {@snippet lang="java" :
3047 import static java.lang.invoke.MethodHandles.*;
3048 import static java.lang.invoke.MethodType.*;
3049 ...
3050 static class Listie extends ArrayList {
3051   public String toString() { return "[wee Listie]"; }
3052   static Lookup lookup() { return MethodHandles.lookup(); }
3053 }
3054 ...
3055 // no access to constructor via invokeSpecial:
3056 MethodHandle MH_newListie = Listie.lookup()
3057   .findConstructor(Listie.class, methodType(void.class));
3058 Listie l = (Listie) MH_newListie.invokeExact();
3059 try { assertEquals("impossible", Listie.lookup().findSpecial(
3060         Listie.class, "<init>", methodType(void.class), Listie.class));
3061  } catch (NoSuchMethodException ex) { } // OK
3062 // access to super and self methods via invokeSpecial:
3063 MethodHandle MH_super = Listie.lookup().findSpecial(
3064   ArrayList.class, "toString" , methodType(String.class), Listie.class);
3065 MethodHandle MH_this = Listie.lookup().findSpecial(
3066   Listie.class, "toString" , methodType(String.class), Listie.class);
3067 MethodHandle MH_duper = Listie.lookup().findSpecial(
3068   Object.class, "toString" , methodType(String.class), Listie.class);
3069 assertEquals("[]", (String) MH_super.invokeExact(l));
3070 assertEquals(""+l, (String) MH_this.invokeExact(l));
3071 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
3072 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
3073         String.class, "toString", methodType(String.class), Listie.class));
3074  } catch (IllegalAccessException ex) { } // OK
3075 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
3076 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
3077          * }
3078          *
3079          * @param refc the class or interface from which the method is accessed
3080          * @param name the name of the method (which must not be "&lt;init&gt;")
3081          * @param type the type of the method, with the receiver argument omitted
3082          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
3083          * @return the desired method handle
3084          * @throws NoSuchMethodException if the method does not exist
3085          * @throws IllegalAccessException if access checking fails,
3086          *                                or if the method is {@code static},
3087          *                                or if the method's variable arity modifier bit
3088          *                                is set and {@code asVarargsCollector} fails
3089          * @throws    SecurityException if a security manager is present and it
3090          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3091          * @throws NullPointerException if any argument is null
3092          */
3093         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
3094                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
3095             checkSpecialCaller(specialCaller, refc);
3096             Lookup specialLookup = this.in(specialCaller);
3097             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
3098             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
3099         }
3100 
3101         /**
3102          * Produces a method handle giving read access to a non-static field.
3103          * The type of the method handle will have a return type of the field's
3104          * value type.
3105          * The method handle's single argument will be the instance containing
3106          * the field.
3107          * Access checking is performed immediately on behalf of the lookup class.
3108          * @param refc the class or interface from which the method is accessed
3109          * @param name the field's name
3110          * @param type the field's type
3111          * @return a method handle which can load values from the field
3112          * @throws NoSuchFieldException if the field does not exist
3113          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3114          * @throws    SecurityException if a security manager is present and it
3115          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3116          * @throws NullPointerException if any argument is null
3117          * @see #findVarHandle(Class, String, Class)
3118          */
3119         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3120             MemberName field = resolveOrFail(REF_getField, refc, name, type);
3121             return getDirectField(REF_getField, refc, field);
3122         }
3123 
3124         /**
3125          * Produces a method handle giving write access to a non-static field.
3126          * The type of the method handle will have a void return type.
3127          * The method handle will take two arguments, the instance containing
3128          * the field, and the value to be stored.
3129          * The second argument will be of the field's value type.
3130          * Access checking is performed immediately on behalf of the lookup class.
3131          * @param refc the class or interface from which the method is accessed
3132          * @param name the field's name
3133          * @param type the field's type
3134          * @return a method handle which can store values into the field
3135          * @throws NoSuchFieldException if the field does not exist
3136          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3137          *                                or {@code final}
3138          * @throws    SecurityException if a security manager is present and it
3139          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3140          * @throws NullPointerException if any argument is null
3141          * @see #findVarHandle(Class, String, Class)
3142          */
3143         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3144             MemberName field = resolveOrFail(REF_putField, refc, name, type);
3145             return getDirectField(REF_putField, refc, field);
3146         }
3147 
3148         /**
3149          * Produces a VarHandle giving access to a non-static field {@code name}
3150          * of type {@code type} declared in a class of type {@code recv}.
3151          * The VarHandle's variable type is {@code type} and it has one
3152          * coordinate type, {@code recv}.
3153          * <p>
3154          * Access checking is performed immediately on behalf of the lookup
3155          * class.
3156          * <p>
3157          * Certain access modes of the returned VarHandle are unsupported under
3158          * the following conditions:
3159          * <ul>
3160          * <li>if the field is declared {@code final}, then the write, atomic
3161          *     update, numeric atomic update, and bitwise atomic update access
3162          *     modes are unsupported.
3163          * <li>if the field type is anything other than {@code byte},
3164          *     {@code short}, {@code char}, {@code int}, {@code long},
3165          *     {@code float}, or {@code double} then numeric atomic update
3166          *     access modes are unsupported.
3167          * <li>if the field type is anything other than {@code boolean},
3168          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3169          *     {@code long} then bitwise atomic update access modes are
3170          *     unsupported.
3171          * </ul>
3172          * <p>
3173          * If the field is declared {@code volatile} then the returned VarHandle
3174          * will override access to the field (effectively ignore the
3175          * {@code volatile} declaration) in accordance to its specified
3176          * access modes.
3177          * <p>
3178          * If the field type is {@code float} or {@code double} then numeric
3179          * and atomic update access modes compare values using their bitwise
3180          * representation (see {@link Float#floatToRawIntBits} and
3181          * {@link Double#doubleToRawLongBits}, respectively).
3182          * @apiNote
3183          * Bitwise comparison of {@code float} values or {@code double} values,
3184          * as performed by the numeric and atomic update access modes, differ
3185          * from the primitive {@code ==} operator and the {@link Float#equals}
3186          * and {@link Double#equals} methods, specifically with respect to
3187          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3188          * Care should be taken when performing a compare and set or a compare
3189          * and exchange operation with such values since the operation may
3190          * unexpectedly fail.
3191          * There are many possible NaN values that are considered to be
3192          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3193          * provided by Java can distinguish between them.  Operation failure can
3194          * occur if the expected or witness value is a NaN value and it is
3195          * transformed (perhaps in a platform specific manner) into another NaN
3196          * value, and thus has a different bitwise representation (see
3197          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3198          * details).
3199          * The values {@code -0.0} and {@code +0.0} have different bitwise
3200          * representations but are considered equal when using the primitive
3201          * {@code ==} operator.  Operation failure can occur if, for example, a
3202          * numeric algorithm computes an expected value to be say {@code -0.0}
3203          * and previously computed the witness value to be say {@code +0.0}.
3204          * @param recv the receiver class, of type {@code R}, that declares the
3205          * non-static field
3206          * @param name the field's name
3207          * @param type the field's type, of type {@code T}
3208          * @return a VarHandle giving access to non-static fields.
3209          * @throws NoSuchFieldException if the field does not exist
3210          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3211          * @throws    SecurityException if a security manager is present and it
3212          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3213          * @throws NullPointerException if any argument is null
3214          * @since 9
3215          */
3216         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3217             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3218             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3219             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3220         }
3221 
3222         /**
3223          * Produces a method handle giving read access to a static field.
3224          * The type of the method handle will have a return type of the field's
3225          * value type.
3226          * The method handle will take no arguments.
3227          * Access checking is performed immediately on behalf of the lookup class.
3228          * <p>
3229          * If the returned method handle is invoked, the field's class will
3230          * be initialized, if it has not already been initialized.
3231          * @param refc the class or interface from which the method is accessed
3232          * @param name the field's name
3233          * @param type the field's type
3234          * @return a method handle which can load values from the field
3235          * @throws NoSuchFieldException if the field does not exist
3236          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3237          * @throws    SecurityException if a security manager is present and it
3238          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3239          * @throws NullPointerException if any argument is null
3240          */
3241         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3242             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3243             return getDirectField(REF_getStatic, refc, field);
3244         }
3245 
3246         /**
3247          * Produces a method handle giving write access to a static field.
3248          * The type of the method handle will have a void return type.
3249          * The method handle will take a single
3250          * argument, of the field's value type, the value to be stored.
3251          * Access checking is performed immediately on behalf of the lookup class.
3252          * <p>
3253          * If the returned method handle is invoked, the field's class will
3254          * be initialized, if it has not already been initialized.
3255          * @param refc the class or interface from which the method is accessed
3256          * @param name the field's name
3257          * @param type the field's type
3258          * @return a method handle which can store values into the field
3259          * @throws NoSuchFieldException if the field does not exist
3260          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3261          *                                or is {@code final}
3262          * @throws    SecurityException if a security manager is present and it
3263          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3264          * @throws NullPointerException if any argument is null
3265          */
3266         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3267             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3268             return getDirectField(REF_putStatic, refc, field);
3269         }
3270 
3271         /**
3272          * Produces a VarHandle giving access to a static field {@code name} of
3273          * type {@code type} declared in a class of type {@code decl}.
3274          * The VarHandle's variable type is {@code type} and it has no
3275          * coordinate types.
3276          * <p>
3277          * Access checking is performed immediately on behalf of the lookup
3278          * class.
3279          * <p>
3280          * If the returned VarHandle is operated on, the declaring class will be
3281          * initialized, if it has not already been initialized.
3282          * <p>
3283          * Certain access modes of the returned VarHandle are unsupported under
3284          * the following conditions:
3285          * <ul>
3286          * <li>if the field is declared {@code final}, then the write, atomic
3287          *     update, numeric atomic update, and bitwise atomic update access
3288          *     modes are unsupported.
3289          * <li>if the field type is anything other than {@code byte},
3290          *     {@code short}, {@code char}, {@code int}, {@code long},
3291          *     {@code float}, or {@code double}, then numeric atomic update
3292          *     access modes are unsupported.
3293          * <li>if the field type is anything other than {@code boolean},
3294          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3295          *     {@code long} then bitwise atomic update access modes are
3296          *     unsupported.
3297          * </ul>
3298          * <p>
3299          * If the field is declared {@code volatile} then the returned VarHandle
3300          * will override access to the field (effectively ignore the
3301          * {@code volatile} declaration) in accordance to its specified
3302          * access modes.
3303          * <p>
3304          * If the field type is {@code float} or {@code double} then numeric
3305          * and atomic update access modes compare values using their bitwise
3306          * representation (see {@link Float#floatToRawIntBits} and
3307          * {@link Double#doubleToRawLongBits}, respectively).
3308          * @apiNote
3309          * Bitwise comparison of {@code float} values or {@code double} values,
3310          * as performed by the numeric and atomic update access modes, differ
3311          * from the primitive {@code ==} operator and the {@link Float#equals}
3312          * and {@link Double#equals} methods, specifically with respect to
3313          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3314          * Care should be taken when performing a compare and set or a compare
3315          * and exchange operation with such values since the operation may
3316          * unexpectedly fail.
3317          * There are many possible NaN values that are considered to be
3318          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3319          * provided by Java can distinguish between them.  Operation failure can
3320          * occur if the expected or witness value is a NaN value and it is
3321          * transformed (perhaps in a platform specific manner) into another NaN
3322          * value, and thus has a different bitwise representation (see
3323          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3324          * details).
3325          * The values {@code -0.0} and {@code +0.0} have different bitwise
3326          * representations but are considered equal when using the primitive
3327          * {@code ==} operator.  Operation failure can occur if, for example, a
3328          * numeric algorithm computes an expected value to be say {@code -0.0}
3329          * and previously computed the witness value to be say {@code +0.0}.
3330          * @param decl the class that declares the static field
3331          * @param name the field's name
3332          * @param type the field's type, of type {@code T}
3333          * @return a VarHandle giving access to a static field
3334          * @throws NoSuchFieldException if the field does not exist
3335          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3336          * @throws    SecurityException if a security manager is present and it
3337          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3338          * @throws NullPointerException if any argument is null
3339          * @since 9
3340          */
3341         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3342             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3343             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3344             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3345         }
3346 
3347         /**
3348          * Produces an early-bound method handle for a non-static method.
3349          * The receiver must have a supertype {@code defc} in which a method
3350          * of the given name and type is accessible to the lookup class.
3351          * The method and all its argument types must be accessible to the lookup object.
3352          * The type of the method handle will be that of the method,
3353          * without any insertion of an additional receiver parameter.
3354          * The given receiver will be bound into the method handle,
3355          * so that every call to the method handle will invoke the
3356          * requested method on the given receiver.
3357          * <p>
3358          * The returned method handle will have
3359          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3360          * the method's variable arity modifier bit ({@code 0x0080}) is set
3361          * <em>and</em> the trailing array argument is not the only argument.
3362          * (If the trailing array argument is the only argument,
3363          * the given receiver value will be bound to it.)
3364          * <p>
3365          * This is almost equivalent to the following code, with some differences noted below:
3366          * {@snippet lang="java" :
3367 import static java.lang.invoke.MethodHandles.*;
3368 import static java.lang.invoke.MethodType.*;
3369 ...
3370 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3371 MethodHandle mh1 = mh0.bindTo(receiver);
3372 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3373 return mh1;
3374          * }
3375          * where {@code defc} is either {@code receiver.getClass()} or a super
3376          * type of that class, in which the requested method is accessible
3377          * to the lookup class.
3378          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3379          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3380          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3381          * the receiver is restricted by {@code findVirtual} to the lookup class.)
3382          * @param receiver the object from which the method is accessed
3383          * @param name the name of the method
3384          * @param type the type of the method, with the receiver argument omitted
3385          * @return the desired method handle
3386          * @throws NoSuchMethodException if the method does not exist
3387          * @throws IllegalAccessException if access checking fails
3388          *                                or if the method's variable arity modifier bit
3389          *                                is set and {@code asVarargsCollector} fails
3390          * @throws    SecurityException if a security manager is present and it
3391          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3392          * @throws NullPointerException if any argument is null
3393          * @see MethodHandle#bindTo
3394          * @see #findVirtual
3395          */
3396         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3397             Class<? extends Object> refc = receiver.getClass(); // may get NPE
3398             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3399             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3400             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3401                 throw new IllegalAccessException("The restricted defining class " +
3402                                                  mh.type().leadingReferenceParameter().getName() +
3403                                                  " is not assignable from receiver class " +
3404                                                  receiver.getClass().getName());
3405             }
3406             return mh.bindArgumentL(0, receiver).setVarargs(method);
3407         }
3408 
3409         /**
3410          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3411          * to <i>m</i>, if the lookup class has permission.
3412          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3413          * If <i>m</i> is virtual, overriding is respected on every call.
3414          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3415          * The type of the method handle will be that of the method,
3416          * with the receiver type prepended (but only if it is non-static).
3417          * If the method's {@code accessible} flag is not set,
3418          * access checking is performed immediately on behalf of the lookup class.
3419          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3420          * <p>
3421          * The returned method handle will have
3422          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3423          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3424          * <p>
3425          * If <i>m</i> is static, and
3426          * if the returned method handle is invoked, the method's class will
3427          * be initialized, if it has not already been initialized.
3428          * @param m the reflected method
3429          * @return a method handle which can invoke the reflected method
3430          * @throws IllegalAccessException if access checking fails
3431          *                                or if the method's variable arity modifier bit
3432          *                                is set and {@code asVarargsCollector} fails
3433          * @throws NullPointerException if the argument is null
3434          */
3435         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3436             if (m.getDeclaringClass() == MethodHandle.class) {
3437                 MethodHandle mh = unreflectForMH(m);
3438                 if (mh != null)  return mh;
3439             }
3440             if (m.getDeclaringClass() == VarHandle.class) {
3441                 MethodHandle mh = unreflectForVH(m);
3442                 if (mh != null)  return mh;
3443             }
3444             MemberName method = new MemberName(m);
3445             byte refKind = method.getReferenceKind();
3446             if (refKind == REF_invokeSpecial)
3447                 refKind = REF_invokeVirtual;
3448             assert(method.isMethod());
3449             @SuppressWarnings("deprecation")
3450             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3451             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3452         }
3453         private MethodHandle unreflectForMH(Method m) {
3454             // these names require special lookups because they throw UnsupportedOperationException
3455             if (MemberName.isMethodHandleInvokeName(m.getName()))
3456                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3457             return null;
3458         }
3459         private MethodHandle unreflectForVH(Method m) {
3460             // these names require special lookups because they throw UnsupportedOperationException
3461             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3462                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3463             return null;
3464         }
3465 
3466         /**
3467          * Produces a method handle for a reflected method.
3468          * It will bypass checks for overriding methods on the receiver,
3469          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3470          * instruction from within the explicitly specified {@code specialCaller}.
3471          * The type of the method handle will be that of the method,
3472          * with a suitably restricted receiver type prepended.
3473          * (The receiver type will be {@code specialCaller} or a subtype.)
3474          * If the method's {@code accessible} flag is not set,
3475          * access checking is performed immediately on behalf of the lookup class,
3476          * as if {@code invokespecial} instruction were being linked.
3477          * <p>
3478          * Before method resolution,
3479          * if the explicitly specified caller class is not identical with the
3480          * lookup class, or if this lookup object does not have
3481          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3482          * privileges, the access fails.
3483          * <p>
3484          * The returned method handle will have
3485          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3486          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3487          * @param m the reflected method
3488          * @param specialCaller the class nominally calling the method
3489          * @return a method handle which can invoke the reflected method
3490          * @throws IllegalAccessException if access checking fails,
3491          *                                or if the method is {@code static},
3492          *                                or if the method's variable arity modifier bit
3493          *                                is set and {@code asVarargsCollector} fails
3494          * @throws NullPointerException if any argument is null
3495          */
3496         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3497             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3498             Lookup specialLookup = this.in(specialCaller);
3499             MemberName method = new MemberName(m, true);
3500             assert(method.isMethod());
3501             // ignore m.isAccessible:  this is a new kind of access
3502             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3503         }
3504 
3505         /**
3506          * Produces a method handle for a reflected constructor.
3507          * The type of the method handle will be that of the constructor,
3508          * with the return type changed to the declaring class.
3509          * The method handle will perform a {@code newInstance} operation,
3510          * creating a new instance of the constructor's class on the
3511          * arguments passed to the method handle.
3512          * <p>
3513          * If the constructor's {@code accessible} flag is not set,
3514          * access checking is performed immediately on behalf of the lookup class.
3515          * <p>
3516          * The returned method handle will have
3517          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3518          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3519          * <p>
3520          * If the returned method handle is invoked, the constructor's class will
3521          * be initialized, if it has not already been initialized.
3522          * @param c the reflected constructor
3523          * @return a method handle which can invoke the reflected constructor
3524          * @throws IllegalAccessException if access checking fails
3525          *                                or if the method's variable arity modifier bit
3526          *                                is set and {@code asVarargsCollector} fails
3527          * @throws NullPointerException if the argument is null
3528          */
3529         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3530             MemberName ctor = new MemberName(c);
3531             assert(ctor.isConstructor());
3532             @SuppressWarnings("deprecation")
3533             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3534             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
3535         }
3536 
3537         /**
3538          * Produces a method handle giving read access to a reflected field.
3539          * The type of the method handle will have a return type of the field's
3540          * value type.
3541          * If the field is {@code static}, the method handle will take no arguments.
3542          * Otherwise, its single argument will be the instance containing
3543          * the field.
3544          * If the {@code Field} object's {@code accessible} flag is not set,
3545          * access checking is performed immediately on behalf of the lookup class.
3546          * <p>
3547          * If the field is static, and
3548          * if the returned method handle is invoked, the field's class will
3549          * be initialized, if it has not already been initialized.
3550          * @param f the reflected field
3551          * @return a method handle which can load values from the reflected field
3552          * @throws IllegalAccessException if access checking fails
3553          * @throws NullPointerException if the argument is null
3554          */
3555         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3556             return unreflectField(f, false);
3557         }
3558 
3559         /**
3560          * Produces a method handle giving write access to a reflected field.
3561          * The type of the method handle will have a void return type.
3562          * If the field is {@code static}, the method handle will take a single
3563          * argument, of the field's value type, the value to be stored.
3564          * Otherwise, the two arguments will be the instance containing
3565          * the field, and the value to be stored.
3566          * If the {@code Field} object's {@code accessible} flag is not set,
3567          * access checking is performed immediately on behalf of the lookup class.
3568          * <p>
3569          * If the field is {@code final}, write access will not be
3570          * allowed and access checking will fail, except under certain
3571          * narrow circumstances documented for {@link Field#set Field.set}.
3572          * A method handle is returned only if a corresponding call to
3573          * the {@code Field} object's {@code set} method could return
3574          * normally.  In particular, fields which are both {@code static}
3575          * and {@code final} may never be set.
3576          * <p>
3577          * If the field is {@code static}, and
3578          * if the returned method handle is invoked, the field's class will
3579          * be initialized, if it has not already been initialized.
3580          * @param f the reflected field
3581          * @return a method handle which can store values into the reflected field
3582          * @throws IllegalAccessException if access checking fails,
3583          *         or if the field is {@code final} and write access
3584          *         is not enabled on the {@code Field} object
3585          * @throws NullPointerException if the argument is null
3586          */
3587         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3588             return unreflectField(f, true);
3589         }
3590 
3591         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3592             MemberName field = new MemberName(f, isSetter);
3593             if (isSetter && field.isFinal()) {
3594                 if (field.isTrustedFinalField()) {
3595                     String msg = field.isStatic() ? "static final field has no write access"
3596                                                   : "final field has no write access";
3597                     throw field.makeAccessException(msg, this);
3598                 }
3599             }
3600             assert(isSetter
3601                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3602                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3603             @SuppressWarnings("deprecation")
3604             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3605             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3606         }
3607 
3608         /**
3609          * Produces a VarHandle giving access to a reflected field {@code f}
3610          * of type {@code T} declared in a class of type {@code R}.
3611          * The VarHandle's variable type is {@code T}.
3612          * If the field is non-static the VarHandle has one coordinate type,
3613          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3614          * coordinate types.
3615          * <p>
3616          * Access checking is performed immediately on behalf of the lookup
3617          * class, regardless of the value of the field's {@code accessible}
3618          * flag.
3619          * <p>
3620          * If the field is static, and if the returned VarHandle is operated
3621          * on, the field's declaring class will be initialized, if it has not
3622          * already been initialized.
3623          * <p>
3624          * Certain access modes of the returned VarHandle are unsupported under
3625          * the following conditions:
3626          * <ul>
3627          * <li>if the field is declared {@code final}, then the write, atomic
3628          *     update, numeric atomic update, and bitwise atomic update access
3629          *     modes are unsupported.
3630          * <li>if the field type is anything other than {@code byte},
3631          *     {@code short}, {@code char}, {@code int}, {@code long},
3632          *     {@code float}, or {@code double} then numeric atomic update
3633          *     access modes are unsupported.
3634          * <li>if the field type is anything other than {@code boolean},
3635          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3636          *     {@code long} then bitwise atomic update access modes are
3637          *     unsupported.
3638          * </ul>
3639          * <p>
3640          * If the field is declared {@code volatile} then the returned VarHandle
3641          * will override access to the field (effectively ignore the
3642          * {@code volatile} declaration) in accordance to its specified
3643          * access modes.
3644          * <p>
3645          * If the field type is {@code float} or {@code double} then numeric
3646          * and atomic update access modes compare values using their bitwise
3647          * representation (see {@link Float#floatToRawIntBits} and
3648          * {@link Double#doubleToRawLongBits}, respectively).
3649          * @apiNote
3650          * Bitwise comparison of {@code float} values or {@code double} values,
3651          * as performed by the numeric and atomic update access modes, differ
3652          * from the primitive {@code ==} operator and the {@link Float#equals}
3653          * and {@link Double#equals} methods, specifically with respect to
3654          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3655          * Care should be taken when performing a compare and set or a compare
3656          * and exchange operation with such values since the operation may
3657          * unexpectedly fail.
3658          * There are many possible NaN values that are considered to be
3659          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3660          * provided by Java can distinguish between them.  Operation failure can
3661          * occur if the expected or witness value is a NaN value and it is
3662          * transformed (perhaps in a platform specific manner) into another NaN
3663          * value, and thus has a different bitwise representation (see
3664          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3665          * details).
3666          * The values {@code -0.0} and {@code +0.0} have different bitwise
3667          * representations but are considered equal when using the primitive
3668          * {@code ==} operator.  Operation failure can occur if, for example, a
3669          * numeric algorithm computes an expected value to be say {@code -0.0}
3670          * and previously computed the witness value to be say {@code +0.0}.
3671          * @param f the reflected field, with a field of type {@code T}, and
3672          * a declaring class of type {@code R}
3673          * @return a VarHandle giving access to non-static fields or a static
3674          * field
3675          * @throws IllegalAccessException if access checking fails
3676          * @throws NullPointerException if the argument is null
3677          * @since 9
3678          */
3679         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3680             MemberName getField = new MemberName(f, false);
3681             MemberName putField = new MemberName(f, true);
3682             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
3683                                                       f.getDeclaringClass(), getField, putField);
3684         }
3685 
3686         /**
3687          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3688          * created by this lookup object or a similar one.
3689          * Security and access checks are performed to ensure that this lookup object
3690          * is capable of reproducing the target method handle.
3691          * This means that the cracking may fail if target is a direct method handle
3692          * but was created by an unrelated lookup object.
3693          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3694          * and was created by a lookup object for a different class.
3695          * @param target a direct method handle to crack into symbolic reference components
3696          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3697          * @throws    SecurityException if a security manager is present and it
3698          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3699          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3700          * @throws    NullPointerException if the target is {@code null}
3701          * @see MethodHandleInfo
3702          * @since 1.8
3703          */
3704         public MethodHandleInfo revealDirect(MethodHandle target) {
3705             if (!target.isCrackable()) {
3706                 throw newIllegalArgumentException("not a direct method handle");
3707             }
3708             MemberName member = target.internalMemberName();
3709             Class<?> defc = member.getDeclaringClass();
3710             byte refKind = member.getReferenceKind();
3711             assert(MethodHandleNatives.refKindIsValid(refKind));
3712             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3713                 // Devirtualized method invocation is usually formally virtual.
3714                 // To avoid creating extra MemberName objects for this common case,
3715                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3716                 refKind = REF_invokeVirtual;
3717             if (refKind == REF_invokeVirtual && defc.isInterface())
3718                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3719                 refKind = REF_invokeInterface;
3720             // Check SM permissions and member access before cracking.
3721             try {
3722                 checkAccess(refKind, defc, member);
3723                 checkSecurityManager(defc, member);
3724             } catch (IllegalAccessException ex) {
3725                 throw new IllegalArgumentException(ex);
3726             }
3727             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3728                 Class<?> callerClass = target.internalCallerClass();
3729                 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3730                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3731             }
3732             // Produce the handle to the results.
3733             return new InfoFromMemberName(this, member, refKind);
3734         }
3735 
3736         /// Helper methods, all package-private.
3737 
3738         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3739             checkSymbolicClass(refc);  // do this before attempting to resolve
3740             Objects.requireNonNull(name);
3741             Objects.requireNonNull(type);
3742             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3743                                             NoSuchFieldException.class);
3744         }
3745 
3746         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3747             checkSymbolicClass(refc);  // do this before attempting to resolve
3748             Objects.requireNonNull(type);
3749             checkMethodName(refKind, name);  // implicit null-check of name
3750             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3751                                             NoSuchMethodException.class);
3752         }
3753 
3754         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3755             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3756             Objects.requireNonNull(member.getName());
3757             Objects.requireNonNull(member.getType());
3758             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3759                                             ReflectiveOperationException.class);
3760         }
3761 
3762         MemberName resolveOrNull(byte refKind, MemberName member) {
3763             // do this before attempting to resolve
3764             if (!isClassAccessible(member.getDeclaringClass())) {
3765                 return null;
3766             }
3767             Objects.requireNonNull(member.getName());
3768             Objects.requireNonNull(member.getType());
3769             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3770         }
3771 
3772         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3773             // do this before attempting to resolve
3774             if (!isClassAccessible(refc)) {
3775                 return null;
3776             }
3777             Objects.requireNonNull(type);
3778             // implicit null-check of name
3779             if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3780                 return null;
3781             }
3782             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3783         }
3784 
3785         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3786             if (!isClassAccessible(refc)) {
3787                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3788             }
3789         }
3790 
3791         boolean isClassAccessible(Class<?> refc) {
3792             Objects.requireNonNull(refc);
3793             Class<?> caller = lookupClassOrNull();
3794             Class<?> type = refc;
3795             while (type.isArray()) {
3796                 type = type.getComponentType();
3797             }
3798             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3799         }
3800 
3801         /** Check name for an illegal leading "&lt;" character. */
3802         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3803             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
3804                 throw new NoSuchMethodException("illegal method name: "+name);
3805         }
3806 
3807         /**
3808          * Find my trustable caller class if m is a caller sensitive method.
3809          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3810          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3811          */
3812         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3813             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3814                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3815                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3816             }
3817             return this;
3818         }
3819 
3820         /**
3821          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3822          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3823          *
3824          * @deprecated This method was originally designed to test {@code PRIVATE} access
3825          * that implies full privilege access but {@code MODULE} access has since become
3826          * independent of {@code PRIVATE} access.  It is recommended to call
3827          * {@link #hasFullPrivilegeAccess()} instead.
3828          * @since 9
3829          */
3830         @Deprecated(since="14")
3831         public boolean hasPrivateAccess() {
3832             return hasFullPrivilegeAccess();
3833         }
3834 
3835         /**
3836          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3837          * i.e. {@code PRIVATE} and {@code MODULE} access.
3838          * A {@code Lookup} object must have full privilege access in order to
3839          * access all members that are allowed to the
3840          * {@linkplain #lookupClass() lookup class}.
3841          *
3842          * @return {@code true} if this lookup has full privilege access.
3843          * @since 14
3844          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3845          */
3846         public boolean hasFullPrivilegeAccess() {
3847             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3848         }
3849 
3850         /**
3851          * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a>
3852          * for ensureInitialized, findClass or accessClass.
3853          */
3854         void checkSecurityManager(Class<?> refc) {
3855             if (allowedModes == TRUSTED)  return;
3856 
3857             @SuppressWarnings("removal")
3858             SecurityManager smgr = System.getSecurityManager();
3859             if (smgr == null)  return;
3860 
3861             // Step 1:
3862             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3863             if (!fullPrivilegeLookup ||
3864                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3865                 ReflectUtil.checkPackageAccess(refc);
3866             }
3867 
3868             // Step 2b:
3869             if (!fullPrivilegeLookup) {
3870                 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
3871             }
3872         }
3873 
3874         /**
3875          * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
3876          * Determines a trustable caller class to compare with refc, the symbolic reference class.
3877          * If this lookup object has full privilege access except original access,
3878          * then the caller class is the lookupClass.
3879          *
3880          * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)}
3881          * from the same module skips the security permission check.
3882          */
3883         void checkSecurityManager(Class<?> refc, MemberName m) {
3884             Objects.requireNonNull(refc);
3885             Objects.requireNonNull(m);
3886 
3887             if (allowedModes == TRUSTED)  return;
3888 
3889             @SuppressWarnings("removal")
3890             SecurityManager smgr = System.getSecurityManager();
3891             if (smgr == null)  return;
3892 
3893             // Step 1:
3894             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3895             if (!fullPrivilegeLookup ||
3896                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3897                 ReflectUtil.checkPackageAccess(refc);
3898             }
3899 
3900             // Step 2a:
3901             if (m.isPublic()) return;
3902             if (!fullPrivilegeLookup) {
3903                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3904             }
3905 
3906             // Step 3:
3907             Class<?> defc = m.getDeclaringClass();
3908             if (!fullPrivilegeLookup && defc != refc) {
3909                 ReflectUtil.checkPackageAccess(defc);
3910             }
3911         }
3912 
3913         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3914             boolean wantStatic = (refKind == REF_invokeStatic);
3915             String message;
3916             if (m.isConstructor())
3917                 message = "expected a method, not a constructor";
3918             else if (!m.isMethod())
3919                 message = "expected a method";
3920             else if (wantStatic != m.isStatic())
3921                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3922             else
3923                 { checkAccess(refKind, refc, m); return; }
3924             throw m.makeAccessException(message, this);
3925         }
3926 
3927         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3928             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3929             String message;
3930             if (wantStatic != m.isStatic())
3931                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3932             else
3933                 { checkAccess(refKind, refc, m); return; }
3934             throw m.makeAccessException(message, this);
3935         }
3936 
3937         private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) {
3938             return Modifier.isProtected(m.getModifiers()) &&
3939                     refKind == REF_invokeVirtual &&
3940                     m.getDeclaringClass() == Object.class &&
3941                     m.getName().equals("clone") &&
3942                     refc.isArray();
3943         }
3944 
3945         /** Check public/protected/private bits on the symbolic reference class and its member. */
3946         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3947             assert(m.referenceKindIsConsistentWith(refKind) &&
3948                    MethodHandleNatives.refKindIsValid(refKind) &&
3949                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3950             int allowedModes = this.allowedModes;
3951             if (allowedModes == TRUSTED)  return;
3952             int mods = m.getModifiers();
3953             if (isArrayClone(refKind, refc, m)) {
3954                 // The JVM does this hack also.
3955                 // (See ClassVerifier::verify_invoke_instructions
3956                 // and LinkResolver::check_method_accessability.)
3957                 // Because the JVM does not allow separate methods on array types,
3958                 // there is no separate method for int[].clone.
3959                 // All arrays simply inherit Object.clone.
3960                 // But for access checking logic, we make Object.clone
3961                 // (normally protected) appear to be public.
3962                 // Later on, when the DirectMethodHandle is created,
3963                 // its leading argument will be restricted to the
3964                 // requested array type.
3965                 // N.B. The return type is not adjusted, because
3966                 // that is *not* the bytecode behavior.
3967                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3968             }
3969             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3970                 // cannot "new" a protected ctor in a different package
3971                 mods ^= Modifier.PROTECTED;
3972             }
3973             if (Modifier.isFinal(mods) &&
3974                     MethodHandleNatives.refKindIsSetter(refKind))
3975                 throw m.makeAccessException("unexpected set of a final field", this);
3976             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3977             if ((requestedModes & allowedModes) != 0) {
3978                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3979                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3980                     return;
3981             } else {
3982                 // Protected members can also be checked as if they were package-private.
3983                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
3984                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
3985                     return;
3986             }
3987             throw m.makeAccessException(accessFailedMessage(refc, m), this);
3988         }
3989 
3990         String accessFailedMessage(Class<?> refc, MemberName m) {
3991             Class<?> defc = m.getDeclaringClass();
3992             int mods = m.getModifiers();
3993             // check the class first:
3994             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
3995                                (defc == refc ||
3996                                 Modifier.isPublic(refc.getModifiers())));
3997             if (!classOK && (allowedModes & PACKAGE) != 0) {
3998                 // ignore previous lookup class to check if default package access
3999                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
4000                            (defc == refc ||
4001                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
4002             }
4003             if (!classOK)
4004                 return "class is not public";
4005             if (Modifier.isPublic(mods))
4006                 return "access to public member failed";  // (how?, module not readable?)
4007             if (Modifier.isPrivate(mods))
4008                 return "member is private";
4009             if (Modifier.isProtected(mods))
4010                 return "member is protected";
4011             return "member is private to package";
4012         }
4013 
4014         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
4015             int allowedModes = this.allowedModes;
4016             if (allowedModes == TRUSTED)  return;
4017             if ((lookupModes() & PRIVATE) == 0
4018                 || (specialCaller != lookupClass()
4019                        // ensure non-abstract methods in superinterfaces can be special-invoked
4020                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
4021                 throw new MemberName(specialCaller).
4022                     makeAccessException("no private access for invokespecial", this);
4023         }
4024 
4025         private boolean restrictProtectedReceiver(MemberName method) {
4026             // The accessing class only has the right to use a protected member
4027             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
4028             if (!method.isProtected() || method.isStatic()
4029                 || allowedModes == TRUSTED
4030                 || method.getDeclaringClass() == lookupClass()
4031                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
4032                 return false;
4033             return true;
4034         }
4035         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
4036             assert(!method.isStatic());
4037             // receiver type of mh is too wide; narrow to caller
4038             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
4039                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
4040             }
4041             MethodType rawType = mh.type();
4042             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
4043             MethodType narrowType = rawType.changeParameterType(0, caller);
4044             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
4045             assert(mh.viewAsTypeChecks(narrowType, true));
4046             return mh.copyWith(narrowType, mh.form);
4047         }
4048 
4049         /** Check access and get the requested method. */
4050         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4051             final boolean doRestrict    = true;
4052             final boolean checkSecurity = true;
4053             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4054         }
4055         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
4056         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4057             final boolean doRestrict    = false;
4058             final boolean checkSecurity = true;
4059             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
4060         }
4061         /** Check access and get the requested method, eliding security manager checks. */
4062         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4063             final boolean doRestrict    = true;
4064             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4065             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4066         }
4067         /** Common code for all methods; do not call directly except from immediately above. */
4068         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
4069                                                    boolean checkSecurity,
4070                                                    boolean doRestrict,
4071                                                    Lookup boundCaller) throws IllegalAccessException {
4072             checkMethod(refKind, refc, method);
4073             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4074             if (checkSecurity)
4075                 checkSecurityManager(refc, method);
4076             assert(!method.isMethodHandleInvoke());
4077 
4078             if (refKind == REF_invokeSpecial &&
4079                 refc != lookupClass() &&
4080                 !refc.isInterface() && !lookupClass().isInterface() &&
4081                 refc != lookupClass().getSuperclass() &&
4082                 refc.isAssignableFrom(lookupClass())) {
4083                 assert(!method.getName().equals(ConstantDescs.INIT_NAME));  // not this code path
4084 
4085                 // Per JVMS 6.5, desc. of invokespecial instruction:
4086                 // If the method is in a superclass of the LC,
4087                 // and if our original search was above LC.super,
4088                 // repeat the search (symbolic lookup) from LC.super
4089                 // and continue with the direct superclass of that class,
4090                 // and so forth, until a match is found or no further superclasses exist.
4091                 // FIXME: MemberName.resolve should handle this instead.
4092                 Class<?> refcAsSuper = lookupClass();
4093                 MemberName m2;
4094                 do {
4095                     refcAsSuper = refcAsSuper.getSuperclass();
4096                     m2 = new MemberName(refcAsSuper,
4097                                         method.getName(),
4098                                         method.getMethodType(),
4099                                         REF_invokeSpecial);
4100                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
4101                 } while (m2 == null &&         // no method is found yet
4102                          refc != refcAsSuper); // search up to refc
4103                 if (m2 == null)  throw new InternalError(method.toString());
4104                 method = m2;
4105                 refc = refcAsSuper;
4106                 // redo basic checks
4107                 checkMethod(refKind, refc, method);
4108             }
4109             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
4110             MethodHandle mh = dmh;
4111             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
4112             if ((doRestrict && refKind == REF_invokeSpecial) ||
4113                     (MethodHandleNatives.refKindHasReceiver(refKind) &&
4114                             restrictProtectedReceiver(method) &&
4115                             // All arrays simply inherit the protected Object.clone method.
4116                             // The leading argument is already restricted to the requested
4117                             // array type (not the lookup class).
4118                             !isArrayClone(refKind, refc, method))) {
4119                 mh = restrictReceiver(method, dmh, lookupClass());
4120             }
4121             mh = maybeBindCaller(method, mh, boundCaller);
4122             mh = mh.setVarargs(method);
4123             return mh;
4124         }
4125         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
4126                                              throws IllegalAccessException {
4127             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
4128                 return mh;
4129 
4130             // boundCaller must have full privilege access.
4131             // It should have been checked by findBoundCallerLookup. Safe to check this again.
4132             if ((boundCaller.lookupModes() & ORIGINAL) == 0)
4133                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
4134 
4135             assert boundCaller.hasFullPrivilegeAccess();
4136 
4137             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
4138             // Note: caller will apply varargs after this step happens.
4139             return cbmh;
4140         }
4141 
4142         /** Check access and get the requested field. */
4143         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4144             final boolean checkSecurity = true;
4145             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4146         }
4147         /** Check access and get the requested field, eliding security manager checks. */
4148         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4149             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4150             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4151         }
4152         /** Common code for all fields; do not call directly except from immediately above. */
4153         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
4154                                                   boolean checkSecurity) throws IllegalAccessException {
4155             checkField(refKind, refc, field);
4156             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4157             if (checkSecurity)
4158                 checkSecurityManager(refc, field);
4159             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
4160             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
4161                                     restrictProtectedReceiver(field));
4162             if (doRestrict)
4163                 return restrictReceiver(field, dmh, lookupClass());
4164             return dmh;
4165         }
4166         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
4167                                             Class<?> refc, MemberName getField, MemberName putField)
4168                 throws IllegalAccessException {
4169             final boolean checkSecurity = true;
4170             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4171         }
4172         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
4173                                                              Class<?> refc, MemberName getField, MemberName putField)
4174                 throws IllegalAccessException {
4175             final boolean checkSecurity = false;
4176             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4177         }
4178         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
4179                                                   Class<?> refc, MemberName getField, MemberName putField,
4180                                                   boolean checkSecurity) throws IllegalAccessException {
4181             assert getField.isStatic() == putField.isStatic();
4182             assert getField.isGetter() && putField.isSetter();
4183             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
4184             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
4185 
4186             checkField(getRefKind, refc, getField);
4187             if (checkSecurity)
4188                 checkSecurityManager(refc, getField);
4189 
4190             if (!putField.isFinal()) {
4191                 // A VarHandle does not support updates to final fields, any
4192                 // such VarHandle to a final field will be read-only and
4193                 // therefore the following write-based accessibility checks are
4194                 // only required for non-final fields
4195                 checkField(putRefKind, refc, putField);
4196                 if (checkSecurity)
4197                     checkSecurityManager(refc, putField);
4198             }
4199 
4200             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
4201                                   restrictProtectedReceiver(getField));
4202             if (doRestrict) {
4203                 assert !getField.isStatic();
4204                 // receiver type of VarHandle is too wide; narrow to caller
4205                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
4206                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4207                 }
4208                 refc = lookupClass();
4209             }
4210             return VarHandles.makeFieldHandle(getField, refc,
4211                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4212         }
4213         /** Check access and get the requested constructor. */
4214         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4215             final boolean checkSecurity = true;
4216             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4217         }
4218         /** Check access and get the requested constructor, eliding security manager checks. */
4219         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4220             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4221             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4222         }
4223         /** Common code for all constructors; do not call directly except from immediately above. */
4224         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4225                                                   boolean checkSecurity) throws IllegalAccessException {
4226             assert(ctor.isConstructor());
4227             checkAccess(REF_newInvokeSpecial, refc, ctor);
4228             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4229             if (checkSecurity)
4230                 checkSecurityManager(refc, ctor);
4231             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4232             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4233         }
4234 
4235         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4236          */
4237         /*non-public*/
4238         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4239                 throws ReflectiveOperationException {
4240             if (!(type instanceof Class || type instanceof MethodType))
4241                 throw new InternalError("unresolved MemberName");
4242             MemberName member = new MemberName(refKind, defc, name, type);
4243             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4244             if (mh != null) {
4245                 checkSymbolicClass(defc);
4246                 return mh;
4247             }
4248             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
4249                 // Treat MethodHandle.invoke and invokeExact specially.
4250                 mh = findVirtualForMH(member.getName(), member.getMethodType());
4251                 if (mh != null) {
4252                     return mh;
4253                 }
4254             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4255                 // Treat signature-polymorphic methods on VarHandle specially.
4256                 mh = findVirtualForVH(member.getName(), member.getMethodType());
4257                 if (mh != null) {
4258                     return mh;
4259                 }
4260             }
4261             MemberName resolved = resolveOrFail(refKind, member);
4262             mh = getDirectMethodForConstant(refKind, defc, resolved);
4263             if (mh instanceof DirectMethodHandle dmh
4264                     && canBeCached(refKind, defc, resolved)) {
4265                 MemberName key = mh.internalMemberName();
4266                 if (key != null) {
4267                     key = key.asNormalOriginal();
4268                 }
4269                 if (member.equals(key)) {  // better safe than sorry
4270                     LOOKASIDE_TABLE.put(key, dmh);
4271                 }
4272             }
4273             return mh;
4274         }
4275         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4276             if (refKind == REF_invokeSpecial) {
4277                 return false;
4278             }
4279             if (!Modifier.isPublic(defc.getModifiers()) ||
4280                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4281                     !member.isPublic() ||
4282                     member.isCallerSensitive()) {
4283                 return false;
4284             }
4285             ClassLoader loader = defc.getClassLoader();
4286             if (loader != null) {
4287                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4288                 boolean found = false;
4289                 while (sysl != null) {
4290                     if (loader == sysl) { found = true; break; }
4291                     sysl = sysl.getParent();
4292                 }
4293                 if (!found) {
4294                     return false;
4295                 }
4296             }
4297             try {
4298                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4299                     new MemberName(refKind, defc, member.getName(), member.getType()));
4300                 if (resolved2 == null) {
4301                     return false;
4302                 }
4303                 checkSecurityManager(defc, resolved2);
4304             } catch (SecurityException ex) {
4305                 return false;
4306             }
4307             return true;
4308         }
4309         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4310                 throws ReflectiveOperationException {
4311             if (MethodHandleNatives.refKindIsField(refKind)) {
4312                 return getDirectFieldNoSecurityManager(refKind, defc, member);
4313             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4314                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
4315             } else if (refKind == REF_newInvokeSpecial) {
4316                 return getDirectConstructorNoSecurityManager(defc, member);
4317             }
4318             // oops
4319             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4320         }
4321 
4322         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4323     }
4324 
4325     /**
4326      * Produces a method handle constructing arrays of a desired type,
4327      * as if by the {@code anewarray} bytecode.
4328      * The return type of the method handle will be the array type.
4329      * The type of its sole argument will be {@code int}, which specifies the size of the array.
4330      *
4331      * <p> If the returned method handle is invoked with a negative
4332      * array size, a {@code NegativeArraySizeException} will be thrown.
4333      *
4334      * @param arrayClass an array type
4335      * @return a method handle which can create arrays of the given type
4336      * @throws NullPointerException if the argument is {@code null}
4337      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4338      * @see java.lang.reflect.Array#newInstance(Class, int)
4339      * @jvms 6.5 {@code anewarray} Instruction
4340      * @since 9
4341      */
4342     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4343         if (!arrayClass.isArray()) {
4344             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4345         }
4346         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4347                 bindTo(arrayClass.getComponentType());
4348         return ani.asType(ani.type().changeReturnType(arrayClass));
4349     }
4350 
4351     /**
4352      * Produces a method handle returning the length of an array,
4353      * as if by the {@code arraylength} bytecode.
4354      * The type of the method handle will have {@code int} as return type,
4355      * and its sole argument will be the array type.
4356      *
4357      * <p> If the returned method handle is invoked with a {@code null}
4358      * array reference, a {@code NullPointerException} will be thrown.
4359      *
4360      * @param arrayClass an array type
4361      * @return a method handle which can retrieve the length of an array of the given array type
4362      * @throws NullPointerException if the argument is {@code null}
4363      * @throws IllegalArgumentException if arrayClass is not an array type
4364      * @jvms 6.5 {@code arraylength} Instruction
4365      * @since 9
4366      */
4367     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4368         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4369     }
4370 
4371     /**
4372      * Produces a method handle giving read access to elements of an array,
4373      * as if by the {@code aaload} bytecode.
4374      * The type of the method handle will have a return type of the array's
4375      * element type.  Its first argument will be the array type,
4376      * and the second will be {@code int}.
4377      *
4378      * <p> When the returned method handle is invoked,
4379      * the array reference and array index are checked.
4380      * A {@code NullPointerException} will be thrown if the array reference
4381      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4382      * thrown if the index is negative or if it is greater than or equal to
4383      * the length of the array.
4384      *
4385      * @param arrayClass an array type
4386      * @return a method handle which can load values from the given array type
4387      * @throws NullPointerException if the argument is null
4388      * @throws  IllegalArgumentException if arrayClass is not an array type
4389      * @jvms 6.5 {@code aaload} Instruction
4390      */
4391     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4392         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4393     }
4394 
4395     /**
4396      * Produces a method handle giving write access to elements of an array,
4397      * as if by the {@code astore} bytecode.
4398      * The type of the method handle will have a void return type.
4399      * Its last argument will be the array's element type.
4400      * The first and second arguments will be the array type and int.
4401      *
4402      * <p> When the returned method handle is invoked,
4403      * the array reference and array index are checked.
4404      * A {@code NullPointerException} will be thrown if the array reference
4405      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4406      * thrown if the index is negative or if it is greater than or equal to
4407      * the length of the array.
4408      *
4409      * @param arrayClass the class of an array
4410      * @return a method handle which can store values into the array type
4411      * @throws NullPointerException if the argument is null
4412      * @throws IllegalArgumentException if arrayClass is not an array type
4413      * @jvms 6.5 {@code aastore} Instruction
4414      */
4415     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4416         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4417     }
4418 
4419     /**
4420      * Produces a VarHandle giving access to elements of an array of type
4421      * {@code arrayClass}.  The VarHandle's variable type is the component type
4422      * of {@code arrayClass} and the list of coordinate types is
4423      * {@code (arrayClass, int)}, where the {@code int} coordinate type
4424      * corresponds to an argument that is an index into an array.
4425      * <p>
4426      * Certain access modes of the returned VarHandle are unsupported under
4427      * the following conditions:
4428      * <ul>
4429      * <li>if the component type is anything other than {@code byte},
4430      *     {@code short}, {@code char}, {@code int}, {@code long},
4431      *     {@code float}, or {@code double} then numeric atomic update access
4432      *     modes are unsupported.
4433      * <li>if the component type is anything other than {@code boolean},
4434      *     {@code byte}, {@code short}, {@code char}, {@code int} or
4435      *     {@code long} then bitwise atomic update access modes are
4436      *     unsupported.
4437      * </ul>
4438      * <p>
4439      * If the component type is {@code float} or {@code double} then numeric
4440      * and atomic update access modes compare values using their bitwise
4441      * representation (see {@link Float#floatToRawIntBits} and
4442      * {@link Double#doubleToRawLongBits}, respectively).
4443      *
4444      * <p> When the returned {@code VarHandle} is invoked,
4445      * the array reference and array index are checked.
4446      * A {@code NullPointerException} will be thrown if the array reference
4447      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4448      * thrown if the index is negative or if it is greater than or equal to
4449      * the length of the array.
4450      *
4451      * @apiNote
4452      * Bitwise comparison of {@code float} values or {@code double} values,
4453      * as performed by the numeric and atomic update access modes, differ
4454      * from the primitive {@code ==} operator and the {@link Float#equals}
4455      * and {@link Double#equals} methods, specifically with respect to
4456      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4457      * Care should be taken when performing a compare and set or a compare
4458      * and exchange operation with such values since the operation may
4459      * unexpectedly fail.
4460      * There are many possible NaN values that are considered to be
4461      * {@code NaN} in Java, although no IEEE 754 floating-point operation
4462      * provided by Java can distinguish between them.  Operation failure can
4463      * occur if the expected or witness value is a NaN value and it is
4464      * transformed (perhaps in a platform specific manner) into another NaN
4465      * value, and thus has a different bitwise representation (see
4466      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4467      * details).
4468      * The values {@code -0.0} and {@code +0.0} have different bitwise
4469      * representations but are considered equal when using the primitive
4470      * {@code ==} operator.  Operation failure can occur if, for example, a
4471      * numeric algorithm computes an expected value to be say {@code -0.0}
4472      * and previously computed the witness value to be say {@code +0.0}.
4473      * @param arrayClass the class of an array, of type {@code T[]}
4474      * @return a VarHandle giving access to elements of an array
4475      * @throws NullPointerException if the arrayClass is null
4476      * @throws IllegalArgumentException if arrayClass is not an array type
4477      * @since 9
4478      */
4479     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4480         return VarHandles.makeArrayElementHandle(arrayClass);
4481     }
4482 
4483     /**
4484      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4485      * viewed as if it were a different primitive array type, such as
4486      * {@code int[]} or {@code long[]}.
4487      * The VarHandle's variable type is the component type of
4488      * {@code viewArrayClass} and the list of coordinate types is
4489      * {@code (byte[], int)}, where the {@code int} coordinate type
4490      * corresponds to an argument that is an index into a {@code byte[]} array.
4491      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4492      * array, composing bytes to or from a value of the component type of
4493      * {@code viewArrayClass} according to the given endianness.
4494      * <p>
4495      * The supported component types (variables types) are {@code short},
4496      * {@code char}, {@code int}, {@code long}, {@code float} and
4497      * {@code double}.
4498      * <p>
4499      * Access of bytes at a given index will result in an
4500      * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4501      * or greater than the {@code byte[]} array length minus the size (in bytes)
4502      * of {@code T}.
4503      * <p>
4504      * Access of bytes at an index may be aligned or misaligned for {@code T},
4505      * with respect to the underlying memory address, {@code A} say, associated
4506      * with the array and index.
4507      * If access is misaligned then access for anything other than the
4508      * {@code get} and {@code set} access modes will result in an
4509      * {@code IllegalStateException}.  In such cases atomic access is only
4510      * guaranteed with respect to the largest power of two that divides the GCD
4511      * of {@code A} and the size (in bytes) of {@code T}.
4512      * If access is aligned then following access modes are supported and are
4513      * guaranteed to support atomic access:
4514      * <ul>
4515      * <li>read write access modes for all {@code T}, with the exception of
4516      *     access modes {@code get} and {@code set} for {@code long} and
4517      *     {@code double} on 32-bit platforms.
4518      * <li>atomic update access modes for {@code int}, {@code long},
4519      *     {@code float} or {@code double}.
4520      *     (Future major platform releases of the JDK may support additional
4521      *     types for certain currently unsupported access modes.)
4522      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4523      *     (Future major platform releases of the JDK may support additional
4524      *     numeric types for certain currently unsupported access modes.)
4525      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4526      *     (Future major platform releases of the JDK may support additional
4527      *     numeric types for certain currently unsupported access modes.)
4528      * </ul>
4529      * <p>
4530      * Misaligned access, and therefore atomicity guarantees, may be determined
4531      * for {@code byte[]} arrays without operating on a specific array.  Given
4532      * an {@code index}, {@code T} and its corresponding boxed type,
4533      * {@code T_BOX}, misalignment may be determined as follows:
4534      * <pre>{@code
4535      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4536      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
4537      *     alignmentOffset(0, sizeOfT);
4538      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
4539      * boolean isMisaligned = misalignedAtIndex != 0;
4540      * }</pre>
4541      * <p>
4542      * If the variable type is {@code float} or {@code double} then atomic
4543      * update access modes compare values using their bitwise representation
4544      * (see {@link Float#floatToRawIntBits} and
4545      * {@link Double#doubleToRawLongBits}, respectively).
4546      * @param viewArrayClass the view array class, with a component type of
4547      * type {@code T}
4548      * @param byteOrder the endianness of the view array elements, as
4549      * stored in the underlying {@code byte} array
4550      * @return a VarHandle giving access to elements of a {@code byte[]} array
4551      * viewed as if elements corresponding to the components type of the view
4552      * array class
4553      * @throws NullPointerException if viewArrayClass or byteOrder is null
4554      * @throws IllegalArgumentException if viewArrayClass is not an array type
4555      * @throws UnsupportedOperationException if the component type of
4556      * viewArrayClass is not supported as a variable type
4557      * @since 9
4558      */
4559     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4560                                      ByteOrder byteOrder) throws IllegalArgumentException {
4561         Objects.requireNonNull(byteOrder);
4562         return VarHandles.byteArrayViewHandle(viewArrayClass,
4563                                               byteOrder == ByteOrder.BIG_ENDIAN);
4564     }
4565 
4566     /**
4567      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4568      * viewed as if it were an array of elements of a different primitive
4569      * component type to that of {@code byte}, such as {@code int[]} or
4570      * {@code long[]}.
4571      * The VarHandle's variable type is the component type of
4572      * {@code viewArrayClass} and the list of coordinate types is
4573      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4574      * corresponds to an argument that is an index into a {@code byte[]} array.
4575      * The returned VarHandle accesses bytes at an index in a
4576      * {@code ByteBuffer}, composing bytes to or from a value of the component
4577      * type of {@code viewArrayClass} according to the given endianness.
4578      * <p>
4579      * The supported component types (variables types) are {@code short},
4580      * {@code char}, {@code int}, {@code long}, {@code float} and
4581      * {@code double}.
4582      * <p>
4583      * Access will result in a {@code ReadOnlyBufferException} for anything
4584      * other than the read access modes if the {@code ByteBuffer} is read-only.
4585      * <p>
4586      * Access of bytes at a given index will result in an
4587      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4588      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4589      * {@code T}.
4590      * <p>
4591      * Access of bytes at an index may be aligned or misaligned for {@code T},
4592      * with respect to the underlying memory address, {@code A} say, associated
4593      * with the {@code ByteBuffer} and index.
4594      * If access is misaligned then access for anything other than the
4595      * {@code get} and {@code set} access modes will result in an
4596      * {@code IllegalStateException}.  In such cases atomic access is only
4597      * guaranteed with respect to the largest power of two that divides the GCD
4598      * of {@code A} and the size (in bytes) of {@code T}.
4599      * If access is aligned then following access modes are supported and are
4600      * guaranteed to support atomic access:
4601      * <ul>
4602      * <li>read write access modes for all {@code T}, with the exception of
4603      *     access modes {@code get} and {@code set} for {@code long} and
4604      *     {@code double} on 32-bit platforms.
4605      * <li>atomic update access modes for {@code int}, {@code long},
4606      *     {@code float} or {@code double}.
4607      *     (Future major platform releases of the JDK may support additional
4608      *     types for certain currently unsupported access modes.)
4609      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4610      *     (Future major platform releases of the JDK may support additional
4611      *     numeric types for certain currently unsupported access modes.)
4612      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4613      *     (Future major platform releases of the JDK may support additional
4614      *     numeric types for certain currently unsupported access modes.)
4615      * </ul>
4616      * <p>
4617      * Misaligned access, and therefore atomicity guarantees, may be determined
4618      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4619      * {@code index}, {@code T} and its corresponding boxed type,
4620      * {@code T_BOX}, as follows:
4621      * <pre>{@code
4622      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4623      * ByteBuffer bb = ...
4624      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4625      * boolean isMisaligned = misalignedAtIndex != 0;
4626      * }</pre>
4627      * <p>
4628      * If the variable type is {@code float} or {@code double} then atomic
4629      * update access modes compare values using their bitwise representation
4630      * (see {@link Float#floatToRawIntBits} and
4631      * {@link Double#doubleToRawLongBits}, respectively).
4632      * @param viewArrayClass the view array class, with a component type of
4633      * type {@code T}
4634      * @param byteOrder the endianness of the view array elements, as
4635      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4636      * endianness of a {@code ByteBuffer})
4637      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4638      * viewed as if elements corresponding to the components type of the view
4639      * array class
4640      * @throws NullPointerException if viewArrayClass or byteOrder is null
4641      * @throws IllegalArgumentException if viewArrayClass is not an array type
4642      * @throws UnsupportedOperationException if the component type of
4643      * viewArrayClass is not supported as a variable type
4644      * @since 9
4645      */
4646     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4647                                       ByteOrder byteOrder) throws IllegalArgumentException {
4648         Objects.requireNonNull(byteOrder);
4649         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4650                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4651     }
4652 
4653 
4654     /// method handle invocation (reflective style)
4655 
4656     /**
4657      * Produces a method handle which will invoke any method handle of the
4658      * given {@code type}, with a given number of trailing arguments replaced by
4659      * a single trailing {@code Object[]} array.
4660      * The resulting invoker will be a method handle with the following
4661      * arguments:
4662      * <ul>
4663      * <li>a single {@code MethodHandle} target
4664      * <li>zero or more leading values (counted by {@code leadingArgCount})
4665      * <li>an {@code Object[]} array containing trailing arguments
4666      * </ul>
4667      * <p>
4668      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4669      * the indicated {@code type}.
4670      * That is, if the target is exactly of the given {@code type}, it will behave
4671      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4672      * is used to convert the target to the required {@code type}.
4673      * <p>
4674      * The type of the returned invoker will not be the given {@code type}, but rather
4675      * will have all parameters except the first {@code leadingArgCount}
4676      * replaced by a single array of type {@code Object[]}, which will be
4677      * the final parameter.
4678      * <p>
4679      * Before invoking its target, the invoker will spread the final array, apply
4680      * reference casts as necessary, and unbox and widen primitive arguments.
4681      * If, when the invoker is called, the supplied array argument does
4682      * not have the correct number of elements, the invoker will throw
4683      * an {@link IllegalArgumentException} instead of invoking the target.
4684      * <p>
4685      * This method is equivalent to the following code (though it may be more efficient):
4686      * {@snippet lang="java" :
4687 MethodHandle invoker = MethodHandles.invoker(type);
4688 int spreadArgCount = type.parameterCount() - leadingArgCount;
4689 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4690 return invoker;
4691      * }
4692      * This method throws no reflective or security exceptions.
4693      * @param type the desired target type
4694      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4695      * @return a method handle suitable for invoking any method handle of the given type
4696      * @throws NullPointerException if {@code type} is null
4697      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4698      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4699      *                  or if the resulting method handle's type would have
4700      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4701      */
4702     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4703         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4704             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4705         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4706         return type.invokers().spreadInvoker(leadingArgCount);
4707     }
4708 
4709     /**
4710      * Produces a special <em>invoker method handle</em> which can be used to
4711      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4712      * The resulting invoker will have a type which is
4713      * exactly equal to the desired type, except that it will accept
4714      * an additional leading argument of type {@code MethodHandle}.
4715      * <p>
4716      * This method is equivalent to the following code (though it may be more efficient):
4717      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4718      *
4719      * <p style="font-size:smaller;">
4720      * <em>Discussion:</em>
4721      * Invoker method handles can be useful when working with variable method handles
4722      * of unknown types.
4723      * For example, to emulate an {@code invokeExact} call to a variable method
4724      * handle {@code M}, extract its type {@code T},
4725      * look up the invoker method {@code X} for {@code T},
4726      * and call the invoker method, as {@code X.invoke(T, A...)}.
4727      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4728      * is unknown.)
4729      * If spreading, collecting, or other argument transformations are required,
4730      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4731      * method handle values, as long as they are compatible with the type of {@code X}.
4732      * <p style="font-size:smaller;">
4733      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4734      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4735      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4736      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4737      * <p>
4738      * This method throws no reflective or security exceptions.
4739      * @param type the desired target type
4740      * @return a method handle suitable for invoking any method handle of the given type
4741      * @throws IllegalArgumentException if the resulting method handle's type would have
4742      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4743      */
4744     public static MethodHandle exactInvoker(MethodType type) {
4745         return type.invokers().exactInvoker();
4746     }
4747 
4748     /**
4749      * Produces a special <em>invoker method handle</em> which can be used to
4750      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4751      * The resulting invoker will have a type which is
4752      * exactly equal to the desired type, except that it will accept
4753      * an additional leading argument of type {@code MethodHandle}.
4754      * <p>
4755      * Before invoking its target, if the target differs from the expected type,
4756      * the invoker will apply reference casts as
4757      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4758      * Similarly, the return value will be converted as necessary.
4759      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4760      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4761      * <p>
4762      * This method is equivalent to the following code (though it may be more efficient):
4763      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4764      * <p style="font-size:smaller;">
4765      * <em>Discussion:</em>
4766      * A {@linkplain MethodType#genericMethodType general method type} is one which
4767      * mentions only {@code Object} arguments and return values.
4768      * An invoker for such a type is capable of calling any method handle
4769      * of the same arity as the general type.
4770      * <p style="font-size:smaller;">
4771      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4772      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4773      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4774      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4775      * <p>
4776      * This method throws no reflective or security exceptions.
4777      * @param type the desired target type
4778      * @return a method handle suitable for invoking any method handle convertible to the given type
4779      * @throws IllegalArgumentException if the resulting method handle's type would have
4780      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4781      */
4782     public static MethodHandle invoker(MethodType type) {
4783         return type.invokers().genericInvoker();
4784     }
4785 
4786     /**
4787      * Produces a special <em>invoker method handle</em> which can be used to
4788      * invoke a signature-polymorphic access mode method on any VarHandle whose
4789      * associated access mode type is compatible with the given type.
4790      * The resulting invoker will have a type which is exactly equal to the
4791      * desired given type, except that it will accept an additional leading
4792      * argument of type {@code VarHandle}.
4793      *
4794      * @param accessMode the VarHandle access mode
4795      * @param type the desired target type
4796      * @return a method handle suitable for invoking an access mode method of
4797      *         any VarHandle whose access mode type is of the given type.
4798      * @since 9
4799      */
4800     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4801         return type.invokers().varHandleMethodExactInvoker(accessMode);
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      * <p>
4812      * Before invoking its target, if the access mode type differs from the
4813      * desired given type, the invoker will apply reference casts as necessary
4814      * and box, unbox, or widen primitive values, as if by
4815      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4816      * converted as necessary.
4817      * <p>
4818      * This method is equivalent to the following code (though it may be more
4819      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4820      *
4821      * @param accessMode the VarHandle access mode
4822      * @param type the desired target type
4823      * @return a method handle suitable for invoking an access mode method of
4824      *         any VarHandle whose access mode type is convertible to the given
4825      *         type.
4826      * @since 9
4827      */
4828     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4829         return type.invokers().varHandleMethodInvoker(accessMode);
4830     }
4831 
4832     /*non-public*/
4833     static MethodHandle basicInvoker(MethodType type) {
4834         return type.invokers().basicInvoker();
4835     }
4836 
4837      /// method handle modification (creation from other method handles)
4838 
4839     /**
4840      * Produces a method handle which adapts the type of the
4841      * given method handle to a new type by pairwise argument and return type conversion.
4842      * The original type and new type must have the same number of arguments.
4843      * The resulting method handle is guaranteed to report a type
4844      * which is equal to the desired new type.
4845      * <p>
4846      * If the original type and new type are equal, returns target.
4847      * <p>
4848      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4849      * and some additional conversions are also applied if those conversions fail.
4850      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4851      * if possible, before or instead of any conversions done by {@code asType}:
4852      * <ul>
4853      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4854      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4855      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4856      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4857      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4858      *     (This treatment follows the usage of the bytecode verifier.)
4859      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4860      *     <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}),
4861      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4862      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4863      *     then a Java casting conversion (JLS {@jls 5.5}) is applied.
4864      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4865      *     widening and/or narrowing.)
4866      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4867      *     conversion will be applied at runtime, possibly followed
4868      *     by a Java casting conversion (JLS {@jls 5.5}) on the primitive value,
4869      *     possibly followed by a conversion from byte to boolean by testing
4870      *     the low-order bit.
4871      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4872      *     and if the reference is null at runtime, a zero value is introduced.
4873      * </ul>
4874      * @param target the method handle to invoke after arguments are retyped
4875      * @param newType the expected type of the new method handle
4876      * @return a method handle which delegates to the target after performing
4877      *           any necessary argument conversions, and arranges for any
4878      *           necessary return value conversions
4879      * @throws NullPointerException if either argument is null
4880      * @throws WrongMethodTypeException if the conversion cannot be made
4881      * @see MethodHandle#asType
4882      */
4883     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4884         explicitCastArgumentsChecks(target, newType);
4885         // use the asTypeCache when possible:
4886         MethodType oldType = target.type();
4887         if (oldType == newType)  return target;
4888         if (oldType.explicitCastEquivalentToAsType(newType)) {
4889             return target.asFixedArity().asType(newType);
4890         }
4891         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4892     }
4893 
4894     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4895         if (target.type().parameterCount() != newType.parameterCount()) {
4896             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4897         }
4898     }
4899 
4900     /**
4901      * Produces a method handle which adapts the calling sequence of the
4902      * given method handle to a new type, by reordering the arguments.
4903      * The resulting method handle is guaranteed to report a type
4904      * which is equal to the desired new type.
4905      * <p>
4906      * The given array controls the reordering.
4907      * Call {@code #I} the number of incoming parameters (the value
4908      * {@code newType.parameterCount()}, and call {@code #O} the number
4909      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4910      * Then the length of the reordering array must be {@code #O},
4911      * and each element must be a non-negative number less than {@code #I}.
4912      * For every {@code N} less than {@code #O}, the {@code N}-th
4913      * outgoing argument will be taken from the {@code I}-th incoming
4914      * argument, where {@code I} is {@code reorder[N]}.
4915      * <p>
4916      * No argument or return value conversions are applied.
4917      * The type of each incoming argument, as determined by {@code newType},
4918      * must be identical to the type of the corresponding outgoing parameter
4919      * or parameters in the target method handle.
4920      * The return type of {@code newType} must be identical to the return
4921      * type of the original target.
4922      * <p>
4923      * The reordering array need not specify an actual permutation.
4924      * An incoming argument will be duplicated if its index appears
4925      * more than once in the array, and an incoming argument will be dropped
4926      * if its index does not appear in the array.
4927      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4928      * incoming arguments which are not mentioned in the reordering array
4929      * may be of any type, as determined only by {@code newType}.
4930      * {@snippet lang="java" :
4931 import static java.lang.invoke.MethodHandles.*;
4932 import static java.lang.invoke.MethodType.*;
4933 ...
4934 MethodType intfn1 = methodType(int.class, int.class);
4935 MethodType intfn2 = methodType(int.class, int.class, int.class);
4936 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4937 assert(sub.type().equals(intfn2));
4938 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4939 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4940 assert((int)rsub.invokeExact(1, 100) == 99);
4941 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4942 assert(add.type().equals(intfn2));
4943 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4944 assert(twice.type().equals(intfn1));
4945 assert((int)twice.invokeExact(21) == 42);
4946      * }
4947      * <p>
4948      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4949      * variable-arity method handle}, even if the original target method handle was.
4950      * @param target the method handle to invoke after arguments are reordered
4951      * @param newType the expected type of the new method handle
4952      * @param reorder an index array which controls the reordering
4953      * @return a method handle which delegates to the target after it
4954      *           drops unused arguments and moves and/or duplicates the other arguments
4955      * @throws NullPointerException if any argument is null
4956      * @throws IllegalArgumentException if the index array length is not equal to
4957      *                  the arity of the target, or if any index array element
4958      *                  not a valid index for a parameter of {@code newType},
4959      *                  or if two corresponding parameter types in
4960      *                  {@code target.type()} and {@code newType} are not identical,
4961      */
4962     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4963         reorder = reorder.clone();  // get a private copy
4964         MethodType oldType = target.type();
4965         permuteArgumentChecks(reorder, newType, oldType);
4966         // first detect dropped arguments and handle them separately
4967         int[] originalReorder = reorder;
4968         BoundMethodHandle result = target.rebind();
4969         LambdaForm form = result.form;
4970         int newArity = newType.parameterCount();
4971         // Normalize the reordering into a real permutation,
4972         // by removing duplicates and adding dropped elements.
4973         // This somewhat improves lambda form caching, as well
4974         // as simplifying the transform by breaking it up into steps.
4975         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4976             if (ddIdx > 0) {
4977                 // We found a duplicated entry at reorder[ddIdx].
4978                 // Example:  (x,y,z)->asList(x,y,z)
4979                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4980                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4981                 // The starred element corresponds to the argument
4982                 // deleted by the dupArgumentForm transform.
4983                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
4984                 boolean killFirst = false;
4985                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
4986                     // Set killFirst if the dup is larger than an intervening position.
4987                     // This will remove at least one inversion from the permutation.
4988                     if (dupVal > val) killFirst = true;
4989                 }
4990                 if (!killFirst) {
4991                     srcPos = dstPos;
4992                     dstPos = ddIdx;
4993                 }
4994                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
4995                 assert (reorder[srcPos] == reorder[dstPos]);
4996                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
4997                 // contract the reordering by removing the element at dstPos
4998                 int tailPos = dstPos + 1;
4999                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
5000                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
5001             } else {
5002                 int dropVal = ~ddIdx, insPos = 0;
5003                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
5004                     // Find first element of reorder larger than dropVal.
5005                     // This is where we will insert the dropVal.
5006                     insPos += 1;
5007                 }
5008                 Class<?> ptype = newType.parameterType(dropVal);
5009                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
5010                 oldType = oldType.insertParameterTypes(insPos, ptype);
5011                 // expand the reordering by inserting an element at insPos
5012                 int tailPos = insPos + 1;
5013                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
5014                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
5015                 reorder[insPos] = dropVal;
5016             }
5017             assert (permuteArgumentChecks(reorder, newType, oldType));
5018         }
5019         assert (reorder.length == newArity);  // a perfect permutation
5020         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
5021         form = form.editor().permuteArgumentsForm(1, reorder);
5022         if (newType == result.type() && form == result.internalForm())
5023             return result;
5024         return result.copyWith(newType, form);
5025     }
5026 
5027     /**
5028      * Return an indication of any duplicate or omission in reorder.
5029      * If the reorder contains a duplicate entry, return the index of the second occurrence.
5030      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
5031      * Otherwise, return zero.
5032      * If an element not in [0..newArity-1] is encountered, return reorder.length.
5033      */
5034     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
5035         final int BIT_LIMIT = 63;  // max number of bits in bit mask
5036         if (newArity < BIT_LIMIT) {
5037             long mask = 0;
5038             for (int i = 0; i < reorder.length; i++) {
5039                 int arg = reorder[i];
5040                 if (arg >= newArity) {
5041                     return reorder.length;
5042                 }
5043                 long bit = 1L << arg;
5044                 if ((mask & bit) != 0) {
5045                     return i;  // >0 indicates a dup
5046                 }
5047                 mask |= bit;
5048             }
5049             if (mask == (1L << newArity) - 1) {
5050                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
5051                 return 0;
5052             }
5053             // find first zero
5054             long zeroBit = Long.lowestOneBit(~mask);
5055             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
5056             assert(zeroPos <= newArity);
5057             if (zeroPos == newArity) {
5058                 return 0;
5059             }
5060             return ~zeroPos;
5061         } else {
5062             // same algorithm, different bit set
5063             BitSet mask = new BitSet(newArity);
5064             for (int i = 0; i < reorder.length; i++) {
5065                 int arg = reorder[i];
5066                 if (arg >= newArity) {
5067                     return reorder.length;
5068                 }
5069                 if (mask.get(arg)) {
5070                     return i;  // >0 indicates a dup
5071                 }
5072                 mask.set(arg);
5073             }
5074             int zeroPos = mask.nextClearBit(0);
5075             assert(zeroPos <= newArity);
5076             if (zeroPos == newArity) {
5077                 return 0;
5078             }
5079             return ~zeroPos;
5080         }
5081     }
5082 
5083     static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
5084         if (newType.returnType() != oldType.returnType())
5085             throw newIllegalArgumentException("return types do not match",
5086                     oldType, newType);
5087         if (reorder.length != oldType.parameterCount())
5088             throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
5089                     oldType, Arrays.toString(reorder));
5090 
5091         int limit = newType.parameterCount();
5092         for (int j = 0; j < reorder.length; j++) {
5093             int i = reorder[j];
5094             if (i < 0 || i >= limit) {
5095                 throw newIllegalArgumentException("index is out of bounds for new type",
5096                         i, newType);
5097             }
5098             Class<?> src = newType.parameterType(i);
5099             Class<?> dst = oldType.parameterType(j);
5100             if (src != dst)
5101                 throw newIllegalArgumentException("parameter types do not match after reorder",
5102                         oldType, newType);
5103         }
5104         return true;
5105     }
5106 
5107     /**
5108      * Produces a method handle of the requested return type which returns the given
5109      * constant value every time it is invoked.
5110      * <p>
5111      * Before the method handle is returned, the passed-in value is converted to the requested type.
5112      * If the requested type is primitive, widening primitive conversions are attempted,
5113      * else reference conversions are attempted.
5114      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5115      * @param type the return type of the desired method handle
5116      * @param value the value to return
5117      * @return a method handle of the given return type and no arguments, which always returns the given value
5118      * @throws NullPointerException if the {@code type} argument is null
5119      * @throws ClassCastException if the value cannot be converted to the required return type
5120      * @throws IllegalArgumentException if the given type is {@code void.class}
5121      */
5122     public static MethodHandle constant(Class<?> type, Object value) {
5123         if (type.isPrimitive()) {
5124             if (type == void.class)
5125                 throw newIllegalArgumentException("void type");
5126             Wrapper w = Wrapper.forPrimitiveType(type);
5127             value = w.convert(value, type);
5128             if (w.zero().equals(value))
5129                 return zero(w, type);
5130             return insertArguments(identity(type), 0, value);
5131         } else {
5132             if (value == null)
5133                 return zero(Wrapper.OBJECT, type);
5134             return identity(type).bindTo(value);
5135         }
5136     }
5137 
5138     /**
5139      * Produces a method handle which returns its sole argument when invoked.
5140      * @param type the type of the sole parameter and return value of the desired method handle
5141      * @return a unary method handle which accepts and returns the given type
5142      * @throws NullPointerException if the argument is null
5143      * @throws IllegalArgumentException if the given type is {@code void.class}
5144      */
5145     public static MethodHandle identity(Class<?> type) {
5146         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5147         int pos = btw.ordinal();
5148         MethodHandle ident = IDENTITY_MHS[pos];
5149         if (ident == null) {
5150             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5151         }
5152         if (ident.type().returnType() == type)
5153             return ident;
5154         // something like identity(Foo.class); do not bother to intern these
5155         assert (btw == Wrapper.OBJECT);
5156         return makeIdentity(type);
5157     }
5158 
5159     /**
5160      * Produces a constant method handle of the requested return type which
5161      * returns the default value for that type every time it is invoked.
5162      * The resulting constant method handle will have no side effects.
5163      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5164      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5165      * since {@code explicitCastArguments} converts {@code null} to default values.
5166      * @param type the expected return type of the desired method handle
5167      * @return a constant method handle that takes no arguments
5168      *         and returns the default value of the given type (or void, if the type is void)
5169      * @throws NullPointerException if the argument is null
5170      * @see MethodHandles#constant
5171      * @see MethodHandles#empty
5172      * @see MethodHandles#explicitCastArguments
5173      * @since 9
5174      */
5175     public static MethodHandle zero(Class<?> type) {
5176         Objects.requireNonNull(type);
5177         return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
5178     }
5179 
5180     private static MethodHandle identityOrVoid(Class<?> type) {
5181         return type == void.class ? zero(type) : identity(type);
5182     }
5183 
5184     /**
5185      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5186      * and returns a suitable default depending on the return type.
5187      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
5188      * <p>The returned method handle is equivalent to
5189      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5190      *
5191      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5192      * {@code guardWithTest(pred, target, empty(target.type())}.
5193      * @param type the type of the desired method handle
5194      * @return a constant method handle of the given type, which returns a default value of the given return type
5195      * @throws NullPointerException if the argument is null
5196      * @see MethodHandles#zero
5197      * @see MethodHandles#constant
5198      * @since 9
5199      */
5200     public static  MethodHandle empty(MethodType type) {
5201         Objects.requireNonNull(type);
5202         return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes());
5203     }
5204 
5205     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5206     private static MethodHandle makeIdentity(Class<?> ptype) {
5207         MethodType mtype = methodType(ptype, ptype);
5208         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5209         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5210     }
5211 
5212     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5213         int pos = btw.ordinal();
5214         MethodHandle zero = ZERO_MHS[pos];
5215         if (zero == null) {
5216             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5217         }
5218         if (zero.type().returnType() == rtype)
5219             return zero;
5220         assert(btw == Wrapper.OBJECT);
5221         return makeZero(rtype);
5222     }
5223     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5224     private static MethodHandle makeZero(Class<?> rtype) {
5225         MethodType mtype = methodType(rtype);
5226         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5227         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
5228     }
5229 
5230     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
5231         // Simulate a CAS, to avoid racy duplication of results.
5232         MethodHandle prev = cache[pos];
5233         if (prev != null) return prev;
5234         return cache[pos] = value;
5235     }
5236 
5237     /**
5238      * Provides a target method handle with one or more <em>bound arguments</em>
5239      * in advance of the method handle's invocation.
5240      * The formal parameters to the target corresponding to the bound
5241      * arguments are called <em>bound parameters</em>.
5242      * Returns a new method handle which saves away the bound arguments.
5243      * When it is invoked, it receives arguments for any non-bound parameters,
5244      * binds the saved arguments to their corresponding parameters,
5245      * and calls the original target.
5246      * <p>
5247      * The type of the new method handle will drop the types for the bound
5248      * parameters from the original target type, since the new method handle
5249      * will no longer require those arguments to be supplied by its callers.
5250      * <p>
5251      * Each given argument object must match the corresponding bound parameter type.
5252      * If a bound parameter type is a primitive, the argument object
5253      * must be a wrapper, and will be unboxed to produce the primitive value.
5254      * <p>
5255      * The {@code pos} argument selects which parameters are to be bound.
5256      * It may range between zero and <i>N-L</i> (inclusively),
5257      * where <i>N</i> is the arity of the target method handle
5258      * and <i>L</i> is the length of the values array.
5259      * <p>
5260      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5261      * variable-arity method handle}, even if the original target method handle was.
5262      * @param target the method handle to invoke after the argument is inserted
5263      * @param pos where to insert the argument (zero for the first)
5264      * @param values the series of arguments to insert
5265      * @return a method handle which inserts an additional argument,
5266      *         before calling the original method handle
5267      * @throws NullPointerException if the target or the {@code values} array is null
5268      * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than
5269      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
5270      *         is the length of the values array.
5271      * @throws ClassCastException if an argument does not match the corresponding bound parameter
5272      *         type.
5273      * @see MethodHandle#bindTo
5274      */
5275     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
5276         int insCount = values.length;
5277         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
5278         if (insCount == 0)  return target;
5279         BoundMethodHandle result = target.rebind();
5280         for (int i = 0; i < insCount; i++) {
5281             Object value = values[i];
5282             Class<?> ptype = ptypes[pos+i];
5283             if (ptype.isPrimitive()) {
5284                 result = insertArgumentPrimitive(result, pos, ptype, value);
5285             } else {
5286                 value = ptype.cast(value);  // throw CCE if needed
5287                 result = result.bindArgumentL(pos, value);
5288             }
5289         }
5290         return result;
5291     }
5292 
5293     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5294                                                              Class<?> ptype, Object value) {
5295         Wrapper w = Wrapper.forPrimitiveType(ptype);
5296         // perform unboxing and/or primitive conversion
5297         value = w.convert(value, ptype);
5298         return switch (w) {
5299             case INT    -> result.bindArgumentI(pos, (int) value);
5300             case LONG   -> result.bindArgumentJ(pos, (long) value);
5301             case FLOAT  -> result.bindArgumentF(pos, (float) value);
5302             case DOUBLE -> result.bindArgumentD(pos, (double) value);
5303             default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5304         };
5305     }
5306 
5307     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5308         MethodType oldType = target.type();
5309         int outargs = oldType.parameterCount();
5310         int inargs  = outargs - insCount;
5311         if (inargs < 0)
5312             throw newIllegalArgumentException("too many values to insert");
5313         if (pos < 0 || pos > inargs)
5314             throw newIllegalArgumentException("no argument type to append");
5315         return oldType.ptypes();
5316     }
5317 
5318     /**
5319      * Produces a method handle which will discard some dummy arguments
5320      * before calling some other specified <i>target</i> method handle.
5321      * The type of the new method handle will be the same as the target's type,
5322      * except it will also include the dummy argument types,
5323      * at some given position.
5324      * <p>
5325      * The {@code pos} argument may range between zero and <i>N</i>,
5326      * where <i>N</i> is the arity of the target.
5327      * If {@code pos} is zero, the dummy arguments will precede
5328      * the target's real arguments; if {@code pos} is <i>N</i>
5329      * they will come after.
5330      * <p>
5331      * <b>Example:</b>
5332      * {@snippet lang="java" :
5333 import static java.lang.invoke.MethodHandles.*;
5334 import static java.lang.invoke.MethodType.*;
5335 ...
5336 MethodHandle cat = lookup().findVirtual(String.class,
5337   "concat", methodType(String.class, String.class));
5338 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5339 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5340 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5341 assertEquals(bigType, d0.type());
5342 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5343      * }
5344      * <p>
5345      * This method is also equivalent to the following code:
5346      * <blockquote><pre>
5347      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5348      * </pre></blockquote>
5349      * @param target the method handle to invoke after the arguments are dropped
5350      * @param pos position of first argument to drop (zero for the leftmost)
5351      * @param valueTypes the type(s) of the argument(s) to drop
5352      * @return a method handle which drops arguments of the given types,
5353      *         before calling the original method handle
5354      * @throws NullPointerException if the target is null,
5355      *                              or if the {@code valueTypes} list or any of its elements is null
5356      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5357      *                  or if {@code pos} is negative or greater than the arity of the target,
5358      *                  or if the new method handle's type would have too many parameters
5359      */
5360     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5361         return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone());
5362     }
5363 
5364     static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) {
5365         MethodType oldType = target.type();  // get NPE
5366         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5367         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5368         if (dropped == 0)  return target;
5369         BoundMethodHandle result = target.rebind();
5370         LambdaForm lform = result.form;
5371         int insertFormArg = 1 + pos;
5372         for (Class<?> ptype : valueTypes) {
5373             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5374         }
5375         result = result.copyWith(newType, lform);
5376         return result;
5377     }
5378 
5379     private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) {
5380         int dropped = valueTypes.length;
5381         MethodType.checkSlotCount(dropped);
5382         int outargs = oldType.parameterCount();
5383         int inargs  = outargs + dropped;
5384         if (pos < 0 || pos > outargs)
5385             throw newIllegalArgumentException("no argument type to remove"
5386                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5387                     );
5388         return dropped;
5389     }
5390 
5391     /**
5392      * Produces a method handle which will discard some dummy arguments
5393      * before calling some other specified <i>target</i> method handle.
5394      * The type of the new method handle will be the same as the target's type,
5395      * except it will also include the dummy argument types,
5396      * at some given position.
5397      * <p>
5398      * The {@code pos} argument may range between zero and <i>N</i>,
5399      * where <i>N</i> is the arity of the target.
5400      * If {@code pos} is zero, the dummy arguments will precede
5401      * the target's real arguments; if {@code pos} is <i>N</i>
5402      * they will come after.
5403      * @apiNote
5404      * {@snippet lang="java" :
5405 import static java.lang.invoke.MethodHandles.*;
5406 import static java.lang.invoke.MethodType.*;
5407 ...
5408 MethodHandle cat = lookup().findVirtual(String.class,
5409   "concat", methodType(String.class, String.class));
5410 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5411 MethodHandle d0 = dropArguments(cat, 0, String.class);
5412 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5413 MethodHandle d1 = dropArguments(cat, 1, String.class);
5414 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5415 MethodHandle d2 = dropArguments(cat, 2, String.class);
5416 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5417 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5418 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5419      * }
5420      * <p>
5421      * This method is also equivalent to the following code:
5422      * <blockquote><pre>
5423      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5424      * </pre></blockquote>
5425      * @param target the method handle to invoke after the arguments are dropped
5426      * @param pos position of first argument to drop (zero for the leftmost)
5427      * @param valueTypes the type(s) of the argument(s) to drop
5428      * @return a method handle which drops arguments of the given types,
5429      *         before calling the original method handle
5430      * @throws NullPointerException if the target is null,
5431      *                              or if the {@code valueTypes} array or any of its elements is null
5432      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5433      *                  or if {@code pos} is negative or greater than the arity of the target,
5434      *                  or if the new method handle's type would have
5435      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
5436      */
5437     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5438         return dropArgumentsTrusted(target, pos, valueTypes.clone());
5439     }
5440 
5441     /* Convenience overloads for trusting internal low-arity call-sites */
5442     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) {
5443         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 });
5444     }
5445     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) {
5446         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 });
5447     }
5448 
5449     // private version which allows caller some freedom with error handling
5450     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos,
5451                                       boolean nullOnFailure) {
5452         Class<?>[] oldTypes = target.type().ptypes();
5453         int match = oldTypes.length;
5454         if (skip != 0) {
5455             if (skip < 0 || skip > match) {
5456                 throw newIllegalArgumentException("illegal skip", skip, target);
5457             }
5458             oldTypes = Arrays.copyOfRange(oldTypes, skip, match);
5459             match -= skip;
5460         }
5461         Class<?>[] addTypes = newTypes;
5462         int add = addTypes.length;
5463         if (pos != 0) {
5464             if (pos < 0 || pos > add) {
5465                 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes));
5466             }
5467             addTypes = Arrays.copyOfRange(addTypes, pos, add);
5468             add -= pos;
5469             assert(addTypes.length == add);
5470         }
5471         // Do not add types which already match the existing arguments.
5472         if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) {
5473             if (nullOnFailure) {
5474                 return null;
5475             }
5476             throw newIllegalArgumentException("argument lists do not match",
5477                 Arrays.toString(oldTypes), Arrays.toString(newTypes));
5478         }
5479         addTypes = Arrays.copyOfRange(addTypes, match, add);
5480         add -= match;
5481         assert(addTypes.length == add);
5482         // newTypes:     (   P*[pos], M*[match], A*[add] )
5483         // target: ( S*[skip],        M*[match]  )
5484         MethodHandle adapter = target;
5485         if (add > 0) {
5486             adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes);
5487         }
5488         // adapter: (S*[skip],        M*[match], A*[add] )
5489         if (pos > 0) {
5490             adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos));
5491         }
5492         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5493         return adapter;
5494     }
5495 
5496     /**
5497      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5498      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5499      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5500      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5501      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5502      * {@link #dropArguments(MethodHandle, int, Class[])}.
5503      * <p>
5504      * The resulting handle will have the same return type as the target handle.
5505      * <p>
5506      * In more formal terms, assume these two type lists:<ul>
5507      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5508      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5509      * {@code newTypes}.
5510      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5511      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5512      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5513      * sub-list.
5514      * </ul>
5515      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5516      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5517      * {@link #dropArguments(MethodHandle, int, Class[])}.
5518      *
5519      * @apiNote
5520      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5521      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5522      * {@snippet lang="java" :
5523 import static java.lang.invoke.MethodHandles.*;
5524 import static java.lang.invoke.MethodType.*;
5525 ...
5526 ...
5527 MethodHandle h0 = constant(boolean.class, true);
5528 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5529 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5530 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5531 if (h1.type().parameterCount() < h2.type().parameterCount())
5532     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5533 else
5534     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5535 MethodHandle h3 = guardWithTest(h0, h1, h2);
5536 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5537      * }
5538      * @param target the method handle to adapt
5539      * @param skip number of targets parameters to disregard (they will be unchanged)
5540      * @param newTypes the list of types to match {@code target}'s parameter type list to
5541      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5542      * @return a possibly adapted method handle
5543      * @throws NullPointerException if either argument is null
5544      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5545      *         or if {@code skip} is negative or greater than the arity of the target,
5546      *         or if {@code pos} is negative or greater than the newTypes list size,
5547      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5548      *         {@code pos}.
5549      * @since 9
5550      */
5551     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5552         Objects.requireNonNull(target);
5553         Objects.requireNonNull(newTypes);
5554         return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false);
5555     }
5556 
5557     /**
5558      * Drop the return value of the target handle (if any).
5559      * The returned method handle will have a {@code void} return type.
5560      *
5561      * @param target the method handle to adapt
5562      * @return a possibly adapted method handle
5563      * @throws NullPointerException if {@code target} is null
5564      * @since 16
5565      */
5566     public static MethodHandle dropReturn(MethodHandle target) {
5567         Objects.requireNonNull(target);
5568         MethodType oldType = target.type();
5569         Class<?> oldReturnType = oldType.returnType();
5570         if (oldReturnType == void.class)
5571             return target;
5572         MethodType newType = oldType.changeReturnType(void.class);
5573         BoundMethodHandle result = target.rebind();
5574         LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5575         result = result.copyWith(newType, lform);
5576         return result;
5577     }
5578 
5579     /**
5580      * Adapts a target method handle by pre-processing
5581      * one or more of its arguments, each with its own unary filter function,
5582      * and then calling the target with each pre-processed argument
5583      * replaced by the result of its corresponding filter function.
5584      * <p>
5585      * The pre-processing is performed by one or more method handles,
5586      * specified in the elements of the {@code filters} array.
5587      * The first element of the filter array corresponds to the {@code pos}
5588      * argument of the target, and so on in sequence.
5589      * The filter functions are invoked in left to right order.
5590      * <p>
5591      * Null arguments in the array are treated as identity functions,
5592      * and the corresponding arguments left unchanged.
5593      * (If there are no non-null elements in the array, the original target is returned.)
5594      * Each filter is applied to the corresponding argument of the adapter.
5595      * <p>
5596      * If a filter {@code F} applies to the {@code N}th argument of
5597      * the target, then {@code F} must be a method handle which
5598      * takes exactly one argument.  The type of {@code F}'s sole argument
5599      * replaces the corresponding argument type of the target
5600      * in the resulting adapted method handle.
5601      * The return type of {@code F} must be identical to the corresponding
5602      * parameter type of the target.
5603      * <p>
5604      * It is an error if there are elements of {@code filters}
5605      * (null or not)
5606      * which do not correspond to argument positions in the target.
5607      * <p><b>Example:</b>
5608      * {@snippet lang="java" :
5609 import static java.lang.invoke.MethodHandles.*;
5610 import static java.lang.invoke.MethodType.*;
5611 ...
5612 MethodHandle cat = lookup().findVirtual(String.class,
5613   "concat", methodType(String.class, String.class));
5614 MethodHandle upcase = lookup().findVirtual(String.class,
5615   "toUpperCase", methodType(String.class));
5616 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5617 MethodHandle f0 = filterArguments(cat, 0, upcase);
5618 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5619 MethodHandle f1 = filterArguments(cat, 1, upcase);
5620 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5621 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5622 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5623      * }
5624      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5625      * denotes the return type of both the {@code target} and resulting adapter.
5626      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5627      * of the parameters and arguments that precede and follow the filter position
5628      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5629      * values of the filtered parameters and arguments; they also represent the
5630      * return types of the {@code filter[i]} handles. The latter accept arguments
5631      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5632      * the resulting adapter.
5633      * {@snippet lang="java" :
5634      * T target(P... p, A[i]... a[i], B... b);
5635      * A[i] filter[i](V[i]);
5636      * T adapter(P... p, V[i]... v[i], B... b) {
5637      *   return target(p..., filter[i](v[i])..., b...);
5638      * }
5639      * }
5640      * <p>
5641      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5642      * variable-arity method handle}, even if the original target method handle was.
5643      *
5644      * @param target the method handle to invoke after arguments are filtered
5645      * @param pos the position of the first argument to filter
5646      * @param filters method handles to call initially on filtered arguments
5647      * @return method handle which incorporates the specified argument filtering logic
5648      * @throws NullPointerException if the target is null
5649      *                              or if the {@code filters} array is null
5650      * @throws IllegalArgumentException if a non-null element of {@code filters}
5651      *          does not match a corresponding argument type of target as described above,
5652      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5653      *          or if the resulting method handle's type would have
5654      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5655      */
5656     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5657         // In method types arguments start at index 0, while the LF
5658         // editor have the MH receiver at position 0 - adjust appropriately.
5659         final int MH_RECEIVER_OFFSET = 1;
5660         filterArgumentsCheckArity(target, pos, filters);
5661         MethodHandle adapter = target;
5662 
5663         // keep track of currently matched filters, as to optimize repeated filters
5664         int index = 0;
5665         int[] positions = new int[filters.length];
5666         MethodHandle filter = null;
5667 
5668         // process filters in reverse order so that the invocation of
5669         // the resulting adapter will invoke the filters in left-to-right order
5670         for (int i = filters.length - 1; i >= 0; --i) {
5671             MethodHandle newFilter = filters[i];
5672             if (newFilter == null) continue;  // ignore null elements of filters
5673 
5674             // flush changes on update
5675             if (filter != newFilter) {
5676                 if (filter != null) {
5677                     if (index > 1) {
5678                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5679                     } else {
5680                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5681                     }
5682                 }
5683                 filter = newFilter;
5684                 index = 0;
5685             }
5686 
5687             filterArgumentChecks(target, pos + i, newFilter);
5688             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5689         }
5690         if (index > 1) {
5691             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5692         } else if (index == 1) {
5693             adapter = filterArgument(adapter, positions[0] - 1, filter);
5694         }
5695         return adapter;
5696     }
5697 
5698     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5699         MethodType targetType = adapter.type();
5700         MethodType filterType = filter.type();
5701         BoundMethodHandle result = adapter.rebind();
5702         Class<?> newParamType = filterType.parameterType(0);
5703 
5704         Class<?>[] ptypes = targetType.ptypes().clone();
5705         for (int pos : positions) {
5706             ptypes[pos - 1] = newParamType;
5707         }
5708         MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true);
5709 
5710         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5711         return result.copyWithExtendL(newType, lform, filter);
5712     }
5713 
5714     /*non-public*/
5715     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5716         filterArgumentChecks(target, pos, filter);
5717         MethodType targetType = target.type();
5718         MethodType filterType = filter.type();
5719         BoundMethodHandle result = target.rebind();
5720         Class<?> newParamType = filterType.parameterType(0);
5721         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5722         MethodType newType = targetType.changeParameterType(pos, newParamType);
5723         result = result.copyWithExtendL(newType, lform, filter);
5724         return result;
5725     }
5726 
5727     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5728         MethodType targetType = target.type();
5729         int maxPos = targetType.parameterCount();
5730         if (pos + filters.length > maxPos)
5731             throw newIllegalArgumentException("too many filters");
5732     }
5733 
5734     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5735         MethodType targetType = target.type();
5736         MethodType filterType = filter.type();
5737         if (filterType.parameterCount() != 1
5738             || filterType.returnType() != targetType.parameterType(pos))
5739             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5740     }
5741 
5742     /**
5743      * Adapts a target method handle by pre-processing
5744      * a sub-sequence of its arguments with a filter (another method handle).
5745      * The pre-processed arguments are replaced by the result (if any) of the
5746      * filter function.
5747      * The target is then called on the modified (usually shortened) argument list.
5748      * <p>
5749      * If the filter returns a value, the target must accept that value as
5750      * its argument in position {@code pos}, preceded and/or followed by
5751      * any arguments not passed to the filter.
5752      * If the filter returns void, the target must accept all arguments
5753      * not passed to the filter.
5754      * No arguments are reordered, and a result returned from the filter
5755      * replaces (in order) the whole subsequence of arguments originally
5756      * passed to the adapter.
5757      * <p>
5758      * The argument types (if any) of the filter
5759      * replace zero or one argument types of the target, at position {@code pos},
5760      * in the resulting adapted method handle.
5761      * The return type of the filter (if any) must be identical to the
5762      * argument type of the target at position {@code pos}, and that target argument
5763      * is supplied by the return value of the filter.
5764      * <p>
5765      * In all cases, {@code pos} must be greater than or equal to zero, and
5766      * {@code pos} must also be less than or equal to the target's arity.
5767      * <p><b>Example:</b>
5768      * {@snippet lang="java" :
5769 import static java.lang.invoke.MethodHandles.*;
5770 import static java.lang.invoke.MethodType.*;
5771 ...
5772 MethodHandle deepToString = publicLookup()
5773   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5774 
5775 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5776 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5777 
5778 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5779 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5780 
5781 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5782 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5783 assertEquals("[top, [up, down], strange]",
5784              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5785 
5786 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5787 assertEquals("[top, [up, down], [strange]]",
5788              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5789 
5790 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5791 assertEquals("[top, [[up, down, strange], charm], bottom]",
5792              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5793      * }
5794      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5795      * represents the return type of the {@code target} and resulting adapter.
5796      * {@code V}/{@code v} stand for the return type and value of the
5797      * {@code filter}, which are also found in the signature and arguments of
5798      * the {@code target}, respectively, unless {@code V} is {@code void}.
5799      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5800      * and values preceding and following the collection position, {@code pos},
5801      * in the {@code target}'s signature. They also turn up in the resulting
5802      * adapter's signature and arguments, where they surround
5803      * {@code B}/{@code b}, which represent the parameter types and arguments
5804      * to the {@code filter} (if any).
5805      * {@snippet lang="java" :
5806      * T target(A...,V,C...);
5807      * V filter(B...);
5808      * T adapter(A... a,B... b,C... c) {
5809      *   V v = filter(b...);
5810      *   return target(a...,v,c...);
5811      * }
5812      * // and if the filter has no arguments:
5813      * T target2(A...,V,C...);
5814      * V filter2();
5815      * T adapter2(A... a,C... c) {
5816      *   V v = filter2();
5817      *   return target2(a...,v,c...);
5818      * }
5819      * // and if the filter has a void return:
5820      * T target3(A...,C...);
5821      * void filter3(B...);
5822      * T adapter3(A... a,B... b,C... c) {
5823      *   filter3(b...);
5824      *   return target3(a...,c...);
5825      * }
5826      * }
5827      * <p>
5828      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5829      * one which first "folds" the affected arguments, and then drops them, in separate
5830      * steps as follows:
5831      * {@snippet lang="java" :
5832      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5833      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5834      * }
5835      * If the target method handle consumes no arguments besides than the result
5836      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5837      * is equivalent to {@code filterReturnValue(coll, mh)}.
5838      * If the filter method handle {@code coll} consumes one argument and produces
5839      * a non-void result, then {@code collectArguments(mh, N, coll)}
5840      * is equivalent to {@code filterArguments(mh, N, coll)}.
5841      * Other equivalences are possible but would require argument permutation.
5842      * <p>
5843      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5844      * variable-arity method handle}, even if the original target method handle was.
5845      *
5846      * @param target the method handle to invoke after filtering the subsequence of arguments
5847      * @param pos the position of the first adapter argument to pass to the filter,
5848      *            and/or the target argument which receives the result of the filter
5849      * @param filter method handle to call on the subsequence of arguments
5850      * @return method handle which incorporates the specified argument subsequence filtering logic
5851      * @throws NullPointerException if either argument is null
5852      * @throws IllegalArgumentException if the return type of {@code filter}
5853      *          is non-void and is not the same as the {@code pos} argument of the target,
5854      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5855      *          or if the resulting method handle's type would have
5856      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5857      * @see MethodHandles#foldArguments
5858      * @see MethodHandles#filterArguments
5859      * @see MethodHandles#filterReturnValue
5860      */
5861     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5862         MethodType newType = collectArgumentsChecks(target, pos, filter);
5863         MethodType collectorType = filter.type();
5864         BoundMethodHandle result = target.rebind();
5865         LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5866         return result.copyWithExtendL(newType, lform, filter);
5867     }
5868 
5869     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5870         MethodType targetType = target.type();
5871         MethodType filterType = filter.type();
5872         Class<?> rtype = filterType.returnType();
5873         Class<?>[] filterArgs = filterType.ptypes();
5874         if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5875                        (rtype != void.class && pos >= targetType.parameterCount())) {
5876             throw newIllegalArgumentException("position is out of range for target", target, pos);
5877         }
5878         if (rtype == void.class) {
5879             return targetType.insertParameterTypes(pos, filterArgs);
5880         }
5881         if (rtype != targetType.parameterType(pos)) {
5882             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5883         }
5884         return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs);
5885     }
5886 
5887     /**
5888      * Adapts a target method handle by post-processing
5889      * its return value (if any) with a filter (another method handle).
5890      * The result of the filter is returned from the adapter.
5891      * <p>
5892      * If the target returns a value, the filter must accept that value as
5893      * its only argument.
5894      * If the target returns void, the filter must accept no arguments.
5895      * <p>
5896      * The return type of the filter
5897      * replaces the return type of the target
5898      * in the resulting adapted method handle.
5899      * The argument type of the filter (if any) must be identical to the
5900      * return type of the target.
5901      * <p><b>Example:</b>
5902      * {@snippet lang="java" :
5903 import static java.lang.invoke.MethodHandles.*;
5904 import static java.lang.invoke.MethodType.*;
5905 ...
5906 MethodHandle cat = lookup().findVirtual(String.class,
5907   "concat", methodType(String.class, String.class));
5908 MethodHandle length = lookup().findVirtual(String.class,
5909   "length", methodType(int.class));
5910 System.out.println((String) cat.invokeExact("x", "y")); // xy
5911 MethodHandle f0 = filterReturnValue(cat, length);
5912 System.out.println((int) f0.invokeExact("x", "y")); // 2
5913      * }
5914      * <p>Here is pseudocode for the resulting adapter. In the code,
5915      * {@code T}/{@code t} represent the result type and value of the
5916      * {@code target}; {@code V}, the result type of the {@code filter}; and
5917      * {@code A}/{@code a}, the types and values of the parameters and arguments
5918      * of the {@code target} as well as the resulting adapter.
5919      * {@snippet lang="java" :
5920      * T target(A...);
5921      * V filter(T);
5922      * V adapter(A... a) {
5923      *   T t = target(a...);
5924      *   return filter(t);
5925      * }
5926      * // and if the target has a void return:
5927      * void target2(A...);
5928      * V filter2();
5929      * V adapter2(A... a) {
5930      *   target2(a...);
5931      *   return filter2();
5932      * }
5933      * // and if the filter has a void return:
5934      * T target3(A...);
5935      * void filter3(V);
5936      * void adapter3(A... a) {
5937      *   T t = target3(a...);
5938      *   filter3(t);
5939      * }
5940      * }
5941      * <p>
5942      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5943      * variable-arity method handle}, even if the original target method handle was.
5944      * @param target the method handle to invoke before filtering the return value
5945      * @param filter method handle to call on the return value
5946      * @return method handle which incorporates the specified return value filtering logic
5947      * @throws NullPointerException if either argument is null
5948      * @throws IllegalArgumentException if the argument list of {@code filter}
5949      *          does not match the return type of target as described above
5950      */
5951     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5952         MethodType targetType = target.type();
5953         MethodType filterType = filter.type();
5954         filterReturnValueChecks(targetType, filterType);
5955         BoundMethodHandle result = target.rebind();
5956         BasicType rtype = BasicType.basicType(filterType.returnType());
5957         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5958         MethodType newType = targetType.changeReturnType(filterType.returnType());
5959         result = result.copyWithExtendL(newType, lform, filter);
5960         return result;
5961     }
5962 
5963     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5964         Class<?> rtype = targetType.returnType();
5965         int filterValues = filterType.parameterCount();
5966         if (filterValues == 0
5967                 ? (rtype != void.class)
5968                 : (rtype != filterType.parameterType(0) || filterValues != 1))
5969             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5970     }
5971 
5972     /**
5973      * Filter the return value of a target method handle with a filter function. The filter function is
5974      * applied to the return value of the original handle; if the filter specifies more than one parameters,
5975      * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5976      * as follows:
5977      * {@snippet lang="java" :
5978      * T target(A...)
5979      * V filter(B... , T)
5980      * V adapter(A... a, B... b) {
5981      *     T t = target(a...);
5982      *     return filter(b..., t);
5983      * }
5984      * }
5985      * <p>
5986      * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
5987      *
5988      * @param target the target method handle
5989      * @param filter the filter method handle
5990      * @return the adapter method handle
5991      */
5992     /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
5993         MethodType targetType = target.type();
5994         MethodType filterType = filter.type();
5995         BoundMethodHandle result = target.rebind();
5996         LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
5997         MethodType newType = targetType.changeReturnType(filterType.returnType());
5998         if (filterType.parameterCount() > 1) {
5999             for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
6000                 newType = newType.appendParameterTypes(filterType.parameterType(i));
6001             }
6002         }
6003         result = result.copyWithExtendL(newType, lform, filter);
6004         return result;
6005     }
6006 
6007     /**
6008      * Adapts a target method handle by pre-processing
6009      * some of its arguments, and then calling the target with
6010      * the result of the pre-processing, inserted into the original
6011      * sequence of arguments.
6012      * <p>
6013      * The pre-processing is performed by {@code combiner}, a second method handle.
6014      * Of the arguments passed to the adapter, the first {@code N} arguments
6015      * are copied to the combiner, which is then called.
6016      * (Here, {@code N} is defined as the parameter count of the combiner.)
6017      * After this, control passes to the target, with any result
6018      * from the combiner inserted before the original {@code N} incoming
6019      * arguments.
6020      * <p>
6021      * If the combiner returns a value, the first parameter type of the target
6022      * must be identical with the return type of the combiner, and the next
6023      * {@code N} parameter types of the target must exactly match the parameters
6024      * of the combiner.
6025      * <p>
6026      * If the combiner has a void return, no result will be inserted,
6027      * and the first {@code N} parameter types of the target
6028      * must exactly match the parameters of the combiner.
6029      * <p>
6030      * The resulting adapter is the same type as the target, except that the
6031      * first parameter type is dropped,
6032      * if it corresponds to the result of the combiner.
6033      * <p>
6034      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
6035      * that either the combiner or the target does not wish to receive.
6036      * If some of the incoming arguments are destined only for the combiner,
6037      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
6038      * arguments will not need to be live on the stack on entry to the
6039      * target.)
6040      * <p><b>Example:</b>
6041      * {@snippet lang="java" :
6042 import static java.lang.invoke.MethodHandles.*;
6043 import static java.lang.invoke.MethodType.*;
6044 ...
6045 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6046   "println", methodType(void.class, String.class))
6047     .bindTo(System.out);
6048 MethodHandle cat = lookup().findVirtual(String.class,
6049   "concat", methodType(String.class, String.class));
6050 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6051 MethodHandle catTrace = foldArguments(cat, trace);
6052 // also prints "boo":
6053 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6054      * }
6055      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6056      * represents the result type of the {@code target} and resulting adapter.
6057      * {@code V}/{@code v} represent the type and value of the parameter and argument
6058      * of {@code target} that precedes the folding position; {@code V} also is
6059      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6060      * types and values of the {@code N} parameters and arguments at the folding
6061      * position. {@code B}/{@code b} represent the types and values of the
6062      * {@code target} parameters and arguments that follow the folded parameters
6063      * and arguments.
6064      * {@snippet lang="java" :
6065      * // there are N arguments in A...
6066      * T target(V, A[N]..., B...);
6067      * V combiner(A...);
6068      * T adapter(A... a, B... b) {
6069      *   V v = combiner(a...);
6070      *   return target(v, a..., b...);
6071      * }
6072      * // and if the combiner has a void return:
6073      * T target2(A[N]..., B...);
6074      * void combiner2(A...);
6075      * T adapter2(A... a, B... b) {
6076      *   combiner2(a...);
6077      *   return target2(a..., b...);
6078      * }
6079      * }
6080      * <p>
6081      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6082      * variable-arity method handle}, even if the original target method handle was.
6083      * @param target the method handle to invoke after arguments are combined
6084      * @param combiner method handle to call initially on the incoming arguments
6085      * @return method handle which incorporates the specified argument folding logic
6086      * @throws NullPointerException if either argument is null
6087      * @throws IllegalArgumentException if {@code combiner}'s return type
6088      *          is non-void and not the same as the first argument type of
6089      *          the target, or if the initial {@code N} argument types
6090      *          of the target
6091      *          (skipping one matching the {@code combiner}'s return type)
6092      *          are not identical with the argument types of {@code combiner}
6093      */
6094     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
6095         return foldArguments(target, 0, combiner);
6096     }
6097 
6098     /**
6099      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
6100      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
6101      * before the folded arguments.
6102      * <p>
6103      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
6104      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
6105      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
6106      * 0.
6107      *
6108      * @apiNote Example:
6109      * {@snippet lang="java" :
6110     import static java.lang.invoke.MethodHandles.*;
6111     import static java.lang.invoke.MethodType.*;
6112     ...
6113     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6114     "println", methodType(void.class, String.class))
6115     .bindTo(System.out);
6116     MethodHandle cat = lookup().findVirtual(String.class,
6117     "concat", methodType(String.class, String.class));
6118     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6119     MethodHandle catTrace = foldArguments(cat, 1, trace);
6120     // also prints "jum":
6121     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6122      * }
6123      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6124      * represents the result type of the {@code target} and resulting adapter.
6125      * {@code V}/{@code v} represent the type and value of the parameter and argument
6126      * of {@code target} that precedes the folding position; {@code V} also is
6127      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6128      * types and values of the {@code N} parameters and arguments at the folding
6129      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
6130      * and values of the {@code target} parameters and arguments that precede and
6131      * follow the folded parameters and arguments starting at {@code pos},
6132      * respectively.
6133      * {@snippet lang="java" :
6134      * // there are N arguments in A...
6135      * T target(Z..., V, A[N]..., B...);
6136      * V combiner(A...);
6137      * T adapter(Z... z, A... a, B... b) {
6138      *   V v = combiner(a...);
6139      *   return target(z..., v, a..., b...);
6140      * }
6141      * // and if the combiner has a void return:
6142      * T target2(Z..., A[N]..., B...);
6143      * void combiner2(A...);
6144      * T adapter2(Z... z, A... a, B... b) {
6145      *   combiner2(a...);
6146      *   return target2(z..., a..., b...);
6147      * }
6148      * }
6149      * <p>
6150      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6151      * variable-arity method handle}, even if the original target method handle was.
6152      *
6153      * @param target the method handle to invoke after arguments are combined
6154      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
6155      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6156      * @param combiner method handle to call initially on the incoming arguments
6157      * @return method handle which incorporates the specified argument folding logic
6158      * @throws NullPointerException if either argument is null
6159      * @throws IllegalArgumentException if either of the following two conditions holds:
6160      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6161      *              {@code pos} of the target signature;
6162      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
6163      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
6164      *
6165      * @see #foldArguments(MethodHandle, MethodHandle)
6166      * @since 9
6167      */
6168     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
6169         MethodType targetType = target.type();
6170         MethodType combinerType = combiner.type();
6171         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
6172         BoundMethodHandle result = target.rebind();
6173         boolean dropResult = rtype == void.class;
6174         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
6175         MethodType newType = targetType;
6176         if (!dropResult) {
6177             newType = newType.dropParameterTypes(pos, pos + 1);
6178         }
6179         result = result.copyWithExtendL(newType, lform, combiner);
6180         return result;
6181     }
6182 
6183     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
6184         int foldArgs   = combinerType.parameterCount();
6185         Class<?> rtype = combinerType.returnType();
6186         int foldVals = rtype == void.class ? 0 : 1;
6187         int afterInsertPos = foldPos + foldVals;
6188         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
6189         if (ok) {
6190             for (int i = 0; i < foldArgs; i++) {
6191                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
6192                     ok = false;
6193                     break;
6194                 }
6195             }
6196         }
6197         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
6198             ok = false;
6199         if (!ok)
6200             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6201         return rtype;
6202     }
6203 
6204     /**
6205      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
6206      * of the pre-processing replacing the argument at the given position.
6207      *
6208      * @param target the method handle to invoke after arguments are combined
6209      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6210      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6211      * @param combiner method handle to call initially on the incoming arguments
6212      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6213      * @return method handle which incorporates the specified argument folding logic
6214      * @throws NullPointerException if either argument is null
6215      * @throws IllegalArgumentException if either of the following two conditions holds:
6216      *          (1) {@code combiner}'s return type is not the same as the argument type at position
6217      *              {@code pos} of the target signature;
6218      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
6219      *              not identical with the argument types of {@code combiner}.
6220      */
6221     /*non-public*/
6222     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6223         return argumentsWithCombiner(true, target, position, combiner, argPositions);
6224     }
6225 
6226     /**
6227      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
6228      * the pre-processing inserted into the original sequence of arguments at the given position.
6229      *
6230      * @param target the method handle to invoke after arguments are combined
6231      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6232      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6233      * @param combiner method handle to call initially on the incoming arguments
6234      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6235      * @return method handle which incorporates the specified argument folding logic
6236      * @throws NullPointerException if either argument is null
6237      * @throws IllegalArgumentException if either of the following two conditions holds:
6238      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6239      *              {@code pos} of the target signature;
6240      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
6241      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
6242      *              with the argument types of {@code combiner}.
6243      */
6244     /*non-public*/
6245     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6246         return argumentsWithCombiner(false, target, position, combiner, argPositions);
6247     }
6248 
6249     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6250         MethodType targetType = target.type();
6251         MethodType combinerType = combiner.type();
6252         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
6253         BoundMethodHandle result = target.rebind();
6254 
6255         MethodType newType = targetType;
6256         LambdaForm lform;
6257         if (filter) {
6258             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
6259         } else {
6260             boolean dropResult = rtype == void.class;
6261             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
6262             if (!dropResult) {
6263                 newType = newType.dropParameterTypes(position, position + 1);
6264             }
6265         }
6266         result = result.copyWithExtendL(newType, lform, combiner);
6267         return result;
6268     }
6269 
6270     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
6271         int combinerArgs = combinerType.parameterCount();
6272         if (argPos.length != combinerArgs) {
6273             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
6274         }
6275         Class<?> rtype = combinerType.returnType();
6276 
6277         for (int i = 0; i < combinerArgs; i++) {
6278             int arg = argPos[i];
6279             if (arg < 0 || arg > targetType.parameterCount()) {
6280                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
6281             }
6282             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
6283                 throw newIllegalArgumentException("target argument type at position " + arg
6284                         + " must match combiner argument type at index " + i + ": " + targetType
6285                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6286             }
6287         }
6288         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6289             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6290         }
6291         return rtype;
6292     }
6293 
6294     /**
6295      * Makes a method handle which adapts a target method handle,
6296      * by guarding it with a test, a boolean-valued method handle.
6297      * If the guard fails, a fallback handle is called instead.
6298      * All three method handles must have the same corresponding
6299      * argument and return types, except that the return type
6300      * of the test must be boolean, and the test is allowed
6301      * to have fewer arguments than the other two method handles.
6302      * <p>
6303      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6304      * represents the uniform result type of the three involved handles;
6305      * {@code A}/{@code a}, the types and values of the {@code target}
6306      * parameters and arguments that are consumed by the {@code test}; and
6307      * {@code B}/{@code b}, those types and values of the {@code target}
6308      * parameters and arguments that are not consumed by the {@code test}.
6309      * {@snippet lang="java" :
6310      * boolean test(A...);
6311      * T target(A...,B...);
6312      * T fallback(A...,B...);
6313      * T adapter(A... a,B... b) {
6314      *   if (test(a...))
6315      *     return target(a..., b...);
6316      *   else
6317      *     return fallback(a..., b...);
6318      * }
6319      * }
6320      * Note that the test arguments ({@code a...} in the pseudocode) cannot
6321      * be modified by execution of the test, and so are passed unchanged
6322      * from the caller to the target or fallback as appropriate.
6323      * @param test method handle used for test, must return boolean
6324      * @param target method handle to call if test passes
6325      * @param fallback method handle to call if test fails
6326      * @return method handle which incorporates the specified if/then/else logic
6327      * @throws NullPointerException if any argument is null
6328      * @throws IllegalArgumentException if {@code test} does not return boolean,
6329      *          or if all three method types do not match (with the return
6330      *          type of {@code test} changed to match that of the target).
6331      */
6332     public static MethodHandle guardWithTest(MethodHandle test,
6333                                MethodHandle target,
6334                                MethodHandle fallback) {
6335         MethodType gtype = test.type();
6336         MethodType ttype = target.type();
6337         MethodType ftype = fallback.type();
6338         if (!ttype.equals(ftype))
6339             throw misMatchedTypes("target and fallback types", ttype, ftype);
6340         if (gtype.returnType() != boolean.class)
6341             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6342 
6343         test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true);
6344         if (test == null) {
6345             throw misMatchedTypes("target and test types", ttype, gtype);
6346         }
6347         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6348     }
6349 
6350     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6351         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6352     }
6353 
6354     /**
6355      * Makes a method handle which adapts a target method handle,
6356      * by running it inside an exception handler.
6357      * If the target returns normally, the adapter returns that value.
6358      * If an exception matching the specified type is thrown, the fallback
6359      * handle is called instead on the exception, plus the original arguments.
6360      * <p>
6361      * The target and handler must have the same corresponding
6362      * argument and return types, except that handler may omit trailing arguments
6363      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6364      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6365      * <p>
6366      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6367      * represents the return type of the {@code target} and {@code handler},
6368      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6369      * the types and values of arguments to the resulting handle consumed by
6370      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6371      * resulting handle discarded by {@code handler}.
6372      * {@snippet lang="java" :
6373      * T target(A..., B...);
6374      * T handler(ExType, A...);
6375      * T adapter(A... a, B... b) {
6376      *   try {
6377      *     return target(a..., b...);
6378      *   } catch (ExType ex) {
6379      *     return handler(ex, a...);
6380      *   }
6381      * }
6382      * }
6383      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6384      * be modified by execution of the target, and so are passed unchanged
6385      * from the caller to the handler, if the handler is invoked.
6386      * <p>
6387      * The target and handler must return the same type, even if the handler
6388      * always throws.  (This might happen, for instance, because the handler
6389      * is simulating a {@code finally} clause).
6390      * To create such a throwing handler, compose the handler creation logic
6391      * with {@link #throwException throwException},
6392      * in order to create a method handle of the correct return type.
6393      * @param target method handle to call
6394      * @param exType the type of exception which the handler will catch
6395      * @param handler method handle to call if a matching exception is thrown
6396      * @return method handle which incorporates the specified try/catch logic
6397      * @throws NullPointerException if any argument is null
6398      * @throws IllegalArgumentException if {@code handler} does not accept
6399      *          the given exception type, or if the method handle types do
6400      *          not match in their return types and their
6401      *          corresponding parameters
6402      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6403      */
6404     public static MethodHandle catchException(MethodHandle target,
6405                                 Class<? extends Throwable> exType,
6406                                 MethodHandle handler) {
6407         MethodType ttype = target.type();
6408         MethodType htype = handler.type();
6409         if (!Throwable.class.isAssignableFrom(exType))
6410             throw new ClassCastException(exType.getName());
6411         if (htype.parameterCount() < 1 ||
6412             !htype.parameterType(0).isAssignableFrom(exType))
6413             throw newIllegalArgumentException("handler does not accept exception type "+exType);
6414         if (htype.returnType() != ttype.returnType())
6415             throw misMatchedTypes("target and handler return types", ttype, htype);
6416         handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true);
6417         if (handler == null) {
6418             throw misMatchedTypes("target and handler types", ttype, htype);
6419         }
6420         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6421     }
6422 
6423     /**
6424      * Produces a method handle which will throw exceptions of the given {@code exType}.
6425      * The method handle will accept a single argument of {@code exType},
6426      * and immediately throw it as an exception.
6427      * The method type will nominally specify a return of {@code returnType}.
6428      * The return type may be anything convenient:  It doesn't matter to the
6429      * method handle's behavior, since it will never return normally.
6430      * @param returnType the return type of the desired method handle
6431      * @param exType the parameter type of the desired method handle
6432      * @return method handle which can throw the given exceptions
6433      * @throws NullPointerException if either argument is null
6434      */
6435     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6436         if (!Throwable.class.isAssignableFrom(exType))
6437             throw new ClassCastException(exType.getName());
6438         return MethodHandleImpl.throwException(methodType(returnType, exType));
6439     }
6440 
6441     /**
6442      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6443      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6444      * delivers the loop's result, which is the return value of the resulting handle.
6445      * <p>
6446      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6447      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6448      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6449      * terms of method handles, each clause will specify up to four independent actions:<ul>
6450      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6451      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6452      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6453      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6454      * </ul>
6455      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6456      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
6457      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6458      * <p>
6459      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6460      * this case. See below for a detailed description.
6461      * <p>
6462      * <em>Parameters optional everywhere:</em>
6463      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6464      * As an exception, the init functions cannot take any {@code v} parameters,
6465      * because those values are not yet computed when the init functions are executed.
6466      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6467      * In fact, any clause function may take no arguments at all.
6468      * <p>
6469      * <em>Loop parameters:</em>
6470      * A clause function may take all the iteration variable values it is entitled to, in which case
6471      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6472      * with their types and values notated as {@code (A...)} and {@code (a...)}.
6473      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6474      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6475      * init function is automatically a loop parameter {@code a}.)
6476      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6477      * These loop parameters act as loop-invariant values visible across the whole loop.
6478      * <p>
6479      * <em>Parameters visible everywhere:</em>
6480      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6481      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6482      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6483      * Most clause functions will not need all of this information, but they will be formally connected to it
6484      * as if by {@link #dropArguments}.
6485      * <a id="astar"></a>
6486      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6487      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6488      * In that notation, the general form of an init function parameter list
6489      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6490      * <p>
6491      * <em>Checking clause structure:</em>
6492      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6493      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6494      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6495      * met by the inputs to the loop combinator.
6496      * <p>
6497      * <em>Effectively identical sequences:</em>
6498      * <a id="effid"></a>
6499      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6500      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6501      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6502      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6503      * that longest list.
6504      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6505      * and the same is true if more sequences of the form {@code (V... A*)} are added.
6506      * <p>
6507      * <em>Step 0: Determine clause structure.</em><ol type="a">
6508      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6509      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6510      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6511      * four. Padding takes place by appending elements to the array.
6512      * <li>Clauses with all {@code null}s are disregarded.
6513      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6514      * </ol>
6515      * <p>
6516      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6517      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6518      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6519      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6520      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6521      * iteration variable type.
6522      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6523      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6524      * </ol>
6525      * <p>
6526      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6527      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6528      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6529      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6530      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6531      * (These types will be checked in step 2, along with all the clause function types.)
6532      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6533      * <li>All of the collected parameter lists must be effectively identical.
6534      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6535      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6536      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6537      * the "internal parameter list".
6538      * </ul>
6539      * <p>
6540      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6541      * <li>Examine fini function return types, disregarding omitted fini functions.
6542      * <li>If there are no fini functions, the loop return type is {@code void}.
6543      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6544      * type.
6545      * </ol>
6546      * <p>
6547      * <em>Step 1D: Check other types.</em><ol type="a">
6548      * <li>There must be at least one non-omitted pred function.
6549      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6550      * </ol>
6551      * <p>
6552      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6553      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6554      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6555      * (Note that their parameter lists are already effectively identical to this list.)
6556      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6557      * effectively identical to the internal parameter list {@code (V... A...)}.
6558      * </ol>
6559      * <p>
6560      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6561      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6562      * type.
6563      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6564      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6565      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6566      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6567      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6568      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6569      * loop return type.
6570      * </ol>
6571      * <p>
6572      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6573      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6574      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6575      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6576      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6577      * pad out the end of the list.
6578      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6579      * </ol>
6580      * <p>
6581      * <em>Final observations.</em><ol type="a">
6582      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6583      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6584      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6585      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6586      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6587      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6588      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6589      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6590      * </ol>
6591      * <p>
6592      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6593      * <ul>
6594      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6595      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6596      * (Only one {@code Pn} has to be non-{@code null}.)
6597      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6598      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6599      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6600      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6601      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6602      * the resulting loop handle's parameter types {@code (A...)}.
6603      * </ul>
6604      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6605      * which is natural if most of the loop computation happens in the steps.  For some loops,
6606      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6607      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6608      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6609      * where the init functions will need the extra parameters.  For such reasons, the rules for
6610      * determining these parameters are as symmetric as possible, across all clause parts.
6611      * In general, the loop parameters function as common invariant values across the whole
6612      * loop, while the iteration variables function as common variant values, or (if there is
6613      * no step function) as internal loop invariant temporaries.
6614      * <p>
6615      * <em>Loop execution.</em><ol type="a">
6616      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6617      * every clause function. These locals are loop invariant.
6618      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6619      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6620      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6621      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6622      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6623      * (in argument order).
6624      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6625      * returns {@code false}.
6626      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6627      * sequence {@code (v...)} of loop variables.
6628      * The updated value is immediately visible to all subsequent function calls.
6629      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6630      * (of type {@code R}) is returned from the loop as a whole.
6631      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6632      * except by throwing an exception.
6633      * </ol>
6634      * <p>
6635      * <em>Usage tips.</em>
6636      * <ul>
6637      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6638      * sometimes a step function only needs to observe the current value of its own variable.
6639      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6640      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6641      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6642      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6643      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6644      * <li>If some of the clause functions are virtual methods on an instance, the instance
6645      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6646      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6647      * will be the first iteration variable value, and it will be easy to use virtual
6648      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6649      * </ul>
6650      * <p>
6651      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6652      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6653      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6654      * {@snippet lang="java" :
6655      * V... init...(A...);
6656      * boolean pred...(V..., A...);
6657      * V... step...(V..., A...);
6658      * R fini...(V..., A...);
6659      * R loop(A... a) {
6660      *   V... v... = init...(a...);
6661      *   for (;;) {
6662      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6663      *       v = s(v..., a...);
6664      *       if (!p(v..., a...)) {
6665      *         return f(v..., a...);
6666      *       }
6667      *     }
6668      *   }
6669      * }
6670      * }
6671      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6672      * to their full length, even though individual clause functions may neglect to take them all.
6673      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6674      *
6675      * @apiNote Example:
6676      * {@snippet lang="java" :
6677      * // iterative implementation of the factorial function as a loop handle
6678      * static int one(int k) { return 1; }
6679      * static int inc(int i, int acc, int k) { return i + 1; }
6680      * static int mult(int i, int acc, int k) { return i * acc; }
6681      * static boolean pred(int i, int acc, int k) { return i < k; }
6682      * static int fin(int i, int acc, int k) { return acc; }
6683      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6684      * // null initializer for counter, should initialize to 0
6685      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6686      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6687      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6688      * assertEquals(120, loop.invoke(5));
6689      * }
6690      * The same example, dropping arguments and using combinators:
6691      * {@snippet lang="java" :
6692      * // simplified implementation of the factorial function as a loop handle
6693      * static int inc(int i) { return i + 1; } // drop acc, k
6694      * static int mult(int i, int acc) { return i * acc; } //drop k
6695      * static boolean cmp(int i, int k) { return i < k; }
6696      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6697      * // null initializer for counter, should initialize to 0
6698      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6699      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6700      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6701      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6702      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6703      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6704      * assertEquals(720, loop.invoke(6));
6705      * }
6706      * A similar example, using a helper object to hold a loop parameter:
6707      * {@snippet lang="java" :
6708      * // instance-based implementation of the factorial function as a loop handle
6709      * static class FacLoop {
6710      *   final int k;
6711      *   FacLoop(int k) { this.k = k; }
6712      *   int inc(int i) { return i + 1; }
6713      *   int mult(int i, int acc) { return i * acc; }
6714      *   boolean pred(int i) { return i < k; }
6715      *   int fin(int i, int acc) { return acc; }
6716      * }
6717      * // assume MH_FacLoop is a handle to the constructor
6718      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6719      * // null initializer for counter, should initialize to 0
6720      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6721      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6722      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6723      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6724      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6725      * assertEquals(5040, loop.invoke(7));
6726      * }
6727      *
6728      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6729      *
6730      * @return a method handle embodying the looping behavior as defined by the arguments.
6731      *
6732      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6733      *
6734      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6735      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6736      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6737      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6738      * @since 9
6739      */
6740     public static MethodHandle loop(MethodHandle[]... clauses) {
6741         // Step 0: determine clause structure.
6742         loopChecks0(clauses);
6743 
6744         List<MethodHandle> init = new ArrayList<>();
6745         List<MethodHandle> step = new ArrayList<>();
6746         List<MethodHandle> pred = new ArrayList<>();
6747         List<MethodHandle> fini = new ArrayList<>();
6748 
6749         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6750             init.add(clause[0]); // all clauses have at least length 1
6751             step.add(clause.length <= 1 ? null : clause[1]);
6752             pred.add(clause.length <= 2 ? null : clause[2]);
6753             fini.add(clause.length <= 3 ? null : clause[3]);
6754         });
6755 
6756         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6757         final int nclauses = init.size();
6758 
6759         // Step 1A: determine iteration variables (V...).
6760         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6761         for (int i = 0; i < nclauses; ++i) {
6762             MethodHandle in = init.get(i);
6763             MethodHandle st = step.get(i);
6764             if (in == null && st == null) {
6765                 iterationVariableTypes.add(void.class);
6766             } else if (in != null && st != null) {
6767                 loopChecks1a(i, in, st);
6768                 iterationVariableTypes.add(in.type().returnType());
6769             } else {
6770                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6771             }
6772         }
6773         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6774 
6775         // Step 1B: determine loop parameters (A...).
6776         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6777         loopChecks1b(init, commonSuffix);
6778 
6779         // Step 1C: determine loop return type.
6780         // Step 1D: check other types.
6781         // local variable required here; see JDK-8223553
6782         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6783                 .map(MethodType::returnType);
6784         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6785         loopChecks1cd(pred, fini, loopReturnType);
6786 
6787         // Step 2: determine parameter lists.
6788         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6789         commonParameterSequence.addAll(commonSuffix);
6790         loopChecks2(step, pred, fini, commonParameterSequence);
6791         // Step 3: fill in omitted functions.
6792         for (int i = 0; i < nclauses; ++i) {
6793             Class<?> t = iterationVariableTypes.get(i);
6794             if (init.get(i) == null) {
6795                 init.set(i, empty(methodType(t, commonSuffix)));
6796             }
6797             if (step.get(i) == null) {
6798                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6799             }
6800             if (pred.get(i) == null) {
6801                 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
6802             }
6803             if (fini.get(i) == null) {
6804                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6805             }
6806         }
6807 
6808         // Step 4: fill in missing parameter types.
6809         // Also convert all handles to fixed-arity handles.
6810         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6811         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6812         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6813         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6814 
6815         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6816                 allMatch(pl -> pl.equals(commonSuffix));
6817         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6818                 allMatch(pl -> pl.equals(commonParameterSequence));
6819 
6820         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6821     }
6822 
6823     private static void loopChecks0(MethodHandle[][] clauses) {
6824         if (clauses == null || clauses.length == 0) {
6825             throw newIllegalArgumentException("null or no clauses passed");
6826         }
6827         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6828             throw newIllegalArgumentException("null clauses are not allowed");
6829         }
6830         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6831             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6832         }
6833     }
6834 
6835     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6836         if (in.type().returnType() != st.type().returnType()) {
6837             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6838                     st.type().returnType());
6839         }
6840     }
6841 
6842     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6843         return mhs.filter(Objects::nonNull)
6844                 // take only those that can contribute to a common suffix because they are longer than the prefix
6845                 .map(MethodHandle::type)
6846                 .filter(t -> t.parameterCount() > skipSize)
6847                 .max(Comparator.comparingInt(MethodType::parameterCount))
6848                 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount())))
6849                 .orElse(List.of());
6850     }
6851 
6852     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6853         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6854         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6855         return longest1.size() >= longest2.size() ? longest1 : longest2;
6856     }
6857 
6858     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6859         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6860                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6861             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6862                     " (common suffix: " + commonSuffix + ")");
6863         }
6864     }
6865 
6866     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6867         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6868                 anyMatch(t -> t != loopReturnType)) {
6869             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6870                     loopReturnType + ")");
6871         }
6872 
6873         if (pred.stream().noneMatch(Objects::nonNull)) {
6874             throw newIllegalArgumentException("no predicate found", pred);
6875         }
6876         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6877                 anyMatch(t -> t != boolean.class)) {
6878             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6879         }
6880     }
6881 
6882     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6883         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6884                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6885             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6886                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6887         }
6888     }
6889 
6890     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6891         return hs.stream().map(h -> {
6892             int pc = h.type().parameterCount();
6893             int tpsize = targetParams.size();
6894             return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
6895         }).toList();
6896     }
6897 
6898     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6899         return hs.stream().map(MethodHandle::asFixedArity).toList();
6900     }
6901 
6902     /**
6903      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6904      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6905      * <p>
6906      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6907      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6908      * evaluates to {@code true}).
6909      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6910      * <p>
6911      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6912      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6913      * and updated with the value returned from its invocation. The result of loop execution will be
6914      * the final value of the additional loop-local variable (if present).
6915      * <p>
6916      * The following rules hold for these argument handles:<ul>
6917      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6918      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6919      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6920      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6921      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6922      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6923      * It will constrain the parameter lists of the other loop parts.
6924      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6925      * list {@code (A...)} is called the <em>external parameter list</em>.
6926      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6927      * additional state variable of the loop.
6928      * The body must both accept and return a value of this type {@code V}.
6929      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6930      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6931      * <a href="MethodHandles.html#effid">effectively identical</a>
6932      * to the external parameter list {@code (A...)}.
6933      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6934      * {@linkplain #empty default value}.
6935      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6936      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6937      * effectively identical to the internal parameter list.
6938      * </ul>
6939      * <p>
6940      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6941      * <li>The loop handle's result type is the result type {@code V} of the body.
6942      * <li>The loop handle's parameter types are the types {@code (A...)},
6943      * from the external parameter list.
6944      * </ul>
6945      * <p>
6946      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6947      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6948      * passed to the loop.
6949      * {@snippet lang="java" :
6950      * V init(A...);
6951      * boolean pred(V, A...);
6952      * V body(V, A...);
6953      * V whileLoop(A... a...) {
6954      *   V v = init(a...);
6955      *   while (pred(v, a...)) {
6956      *     v = body(v, a...);
6957      *   }
6958      *   return v;
6959      * }
6960      * }
6961      *
6962      * @apiNote Example:
6963      * {@snippet lang="java" :
6964      * // implement the zip function for lists as a loop handle
6965      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6966      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6967      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6968      *   zip.add(a.next());
6969      *   zip.add(b.next());
6970      *   return zip;
6971      * }
6972      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6973      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6974      * List<String> a = Arrays.asList("a", "b", "c", "d");
6975      * List<String> b = Arrays.asList("e", "f", "g", "h");
6976      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6977      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6978      * }
6979      *
6980      *
6981      * @apiNote The implementation of this method can be expressed as follows:
6982      * {@snippet lang="java" :
6983      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6984      *     MethodHandle fini = (body.type().returnType() == void.class
6985      *                         ? null : identity(body.type().returnType()));
6986      *     MethodHandle[]
6987      *         checkExit = { null, null, pred, fini },
6988      *         varBody   = { init, body };
6989      *     return loop(checkExit, varBody);
6990      * }
6991      * }
6992      *
6993      * @param init optional initializer, providing the initial value of the loop variable.
6994      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6995      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6996      *             above for other constraints.
6997      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6998      *             See above for other constraints.
6999      *
7000      * @return a method handle implementing the {@code while} loop as described by the arguments.
7001      * @throws IllegalArgumentException if the rules for the arguments are violated.
7002      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7003      *
7004      * @see #loop(MethodHandle[][])
7005      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
7006      * @since 9
7007      */
7008     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
7009         whileLoopChecks(init, pred, body);
7010         MethodHandle fini = identityOrVoid(body.type().returnType());
7011         MethodHandle[] checkExit = { null, null, pred, fini };
7012         MethodHandle[] varBody = { init, body };
7013         return loop(checkExit, varBody);
7014     }
7015 
7016     /**
7017      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
7018      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7019      * <p>
7020      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
7021      * method will, in each iteration, first execute its body and then evaluate the predicate.
7022      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
7023      * <p>
7024      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
7025      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
7026      * and updated with the value returned from its invocation. The result of loop execution will be
7027      * the final value of the additional loop-local variable (if present).
7028      * <p>
7029      * The following rules hold for these argument handles:<ul>
7030      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7031      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
7032      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7033      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
7034      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
7035      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
7036      * It will constrain the parameter lists of the other loop parts.
7037      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
7038      * list {@code (A...)} is called the <em>external parameter list</em>.
7039      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7040      * additional state variable of the loop.
7041      * The body must both accept and return a value of this type {@code V}.
7042      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7043      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7044      * <a href="MethodHandles.html#effid">effectively identical</a>
7045      * to the external parameter list {@code (A...)}.
7046      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7047      * {@linkplain #empty default value}.
7048      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
7049      * Its parameter list (either empty or of the form {@code (V A*)}) must be
7050      * effectively identical to the internal parameter list.
7051      * </ul>
7052      * <p>
7053      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7054      * <li>The loop handle's result type is the result type {@code V} of the body.
7055      * <li>The loop handle's parameter types are the types {@code (A...)},
7056      * from the external parameter list.
7057      * </ul>
7058      * <p>
7059      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7060      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
7061      * passed to the loop.
7062      * {@snippet lang="java" :
7063      * V init(A...);
7064      * boolean pred(V, A...);
7065      * V body(V, A...);
7066      * V doWhileLoop(A... a...) {
7067      *   V v = init(a...);
7068      *   do {
7069      *     v = body(v, a...);
7070      *   } while (pred(v, a...));
7071      *   return v;
7072      * }
7073      * }
7074      *
7075      * @apiNote Example:
7076      * {@snippet lang="java" :
7077      * // int i = 0; while (i < limit) { ++i; } return i; => limit
7078      * static int zero(int limit) { return 0; }
7079      * static int step(int i, int limit) { return i + 1; }
7080      * static boolean pred(int i, int limit) { return i < limit; }
7081      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
7082      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
7083      * assertEquals(23, loop.invoke(23));
7084      * }
7085      *
7086      *
7087      * @apiNote The implementation of this method can be expressed as follows:
7088      * {@snippet lang="java" :
7089      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7090      *     MethodHandle fini = (body.type().returnType() == void.class
7091      *                         ? null : identity(body.type().returnType()));
7092      *     MethodHandle[] clause = { init, body, pred, fini };
7093      *     return loop(clause);
7094      * }
7095      * }
7096      *
7097      * @param init optional initializer, providing the initial value of the loop variable.
7098      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7099      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7100      *             See above for other constraints.
7101      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7102      *             above for other constraints.
7103      *
7104      * @return a method handle implementing the {@code while} loop as described by the arguments.
7105      * @throws IllegalArgumentException if the rules for the arguments are violated.
7106      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7107      *
7108      * @see #loop(MethodHandle[][])
7109      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
7110      * @since 9
7111      */
7112     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7113         whileLoopChecks(init, pred, body);
7114         MethodHandle fini = identityOrVoid(body.type().returnType());
7115         MethodHandle[] clause = {init, body, pred, fini };
7116         return loop(clause);
7117     }
7118 
7119     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
7120         Objects.requireNonNull(pred);
7121         Objects.requireNonNull(body);
7122         MethodType bodyType = body.type();
7123         Class<?> returnType = bodyType.returnType();
7124         List<Class<?>> innerList = bodyType.parameterList();
7125         List<Class<?>> outerList = innerList;
7126         if (returnType == void.class) {
7127             // OK
7128         } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
7129             // leading V argument missing => error
7130             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7131             throw misMatchedTypes("body function", bodyType, expected);
7132         } else {
7133             outerList = innerList.subList(1, innerList.size());
7134         }
7135         MethodType predType = pred.type();
7136         if (predType.returnType() != boolean.class ||
7137                 !predType.effectivelyIdenticalParameters(0, innerList)) {
7138             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
7139         }
7140         if (init != null) {
7141             MethodType initType = init.type();
7142             if (initType.returnType() != returnType ||
7143                     !initType.effectivelyIdenticalParameters(0, outerList)) {
7144                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7145             }
7146         }
7147     }
7148 
7149     /**
7150      * Constructs a loop that runs a given number of iterations.
7151      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7152      * <p>
7153      * The number of iterations is determined by the {@code iterations} handle evaluation result.
7154      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
7155      * It will be initialized to 0 and incremented by 1 in each iteration.
7156      * <p>
7157      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7158      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7159      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7160      * <p>
7161      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7162      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7163      * iteration variable.
7164      * The result of the loop handle execution will be the final {@code V} value of that variable
7165      * (or {@code void} if there is no {@code V} variable).
7166      * <p>
7167      * The following rules hold for the argument handles:<ul>
7168      * <li>The {@code iterations} handle must not be {@code null}, and must return
7169      * the type {@code int}, referred to here as {@code I} in parameter type lists.
7170      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7171      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7172      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7173      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7174      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7175      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7176      * of types called the <em>internal parameter list</em>.
7177      * It will constrain the parameter lists of the other loop parts.
7178      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7179      * with no additional {@code A} types, then the internal parameter list is extended by
7180      * the argument types {@code A...} of the {@code iterations} handle.
7181      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7182      * list {@code (A...)} is called the <em>external parameter list</em>.
7183      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7184      * additional state variable of the loop.
7185      * The body must both accept a leading parameter and return a value of this type {@code V}.
7186      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7187      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7188      * <a href="MethodHandles.html#effid">effectively identical</a>
7189      * to the external parameter list {@code (A...)}.
7190      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7191      * {@linkplain #empty default value}.
7192      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
7193      * effectively identical to the external parameter list {@code (A...)}.
7194      * </ul>
7195      * <p>
7196      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7197      * <li>The loop handle's result type is the result type {@code V} of the body.
7198      * <li>The loop handle's parameter types are the types {@code (A...)},
7199      * from the external parameter list.
7200      * </ul>
7201      * <p>
7202      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7203      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7204      * arguments passed to the loop.
7205      * {@snippet lang="java" :
7206      * int iterations(A...);
7207      * V init(A...);
7208      * V body(V, int, A...);
7209      * V countedLoop(A... a...) {
7210      *   int end = iterations(a...);
7211      *   V v = init(a...);
7212      *   for (int i = 0; i < end; ++i) {
7213      *     v = body(v, i, a...);
7214      *   }
7215      *   return v;
7216      * }
7217      * }
7218      *
7219      * @apiNote Example with a fully conformant body method:
7220      * {@snippet lang="java" :
7221      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7222      * // => a variation on a well known theme
7223      * static String step(String v, int counter, String init) { return "na " + v; }
7224      * // assume MH_step is a handle to the method above
7225      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
7226      * MethodHandle start = MethodHandles.identity(String.class);
7227      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
7228      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
7229      * }
7230      *
7231      * @apiNote Example with the simplest possible body method type,
7232      * and passing the number of iterations to the loop invocation:
7233      * {@snippet lang="java" :
7234      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7235      * // => a variation on a well known theme
7236      * static String step(String v, int counter ) { return "na " + v; }
7237      * // assume MH_step is a handle to the method above
7238      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
7239      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
7240      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
7241      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
7242      * }
7243      *
7244      * @apiNote Example that treats the number of iterations, string to append to, and string to append
7245      * as loop parameters:
7246      * {@snippet lang="java" :
7247      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7248      * // => a variation on a well known theme
7249      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
7250      * // assume MH_step is a handle to the method above
7251      * MethodHandle count = MethodHandles.identity(int.class);
7252      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
7253      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
7254      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
7255      * }
7256      *
7257      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
7258      * to enforce a loop type:
7259      * {@snippet lang="java" :
7260      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7261      * // => a variation on a well known theme
7262      * static String step(String v, int counter, String pre) { return pre + " " + v; }
7263      * // assume MH_step is a handle to the method above
7264      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
7265      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
7266      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
7267      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
7268      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
7269      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
7270      * }
7271      *
7272      * @apiNote The implementation of this method can be expressed as follows:
7273      * {@snippet lang="java" :
7274      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7275      *     return countedLoop(empty(iterations.type()), iterations, init, body);
7276      * }
7277      * }
7278      *
7279      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
7280      *                   result type must be {@code int}. See above for other constraints.
7281      * @param init optional initializer, providing the initial value of the loop variable.
7282      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7283      * @param body body of the loop, which may not be {@code null}.
7284      *             It controls the loop parameters and result type in the standard case (see above for details).
7285      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7286      *             and may accept any number of additional types.
7287      *             See above for other constraints.
7288      *
7289      * @return a method handle representing the loop.
7290      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7291      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7292      *
7293      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7294      * @since 9
7295      */
7296     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7297         return countedLoop(empty(iterations.type()), iterations, init, body);
7298     }
7299 
7300     /**
7301      * Constructs a loop that counts over a range of numbers.
7302      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7303      * <p>
7304      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7305      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7306      * values of the loop counter.
7307      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7308      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7309      * <p>
7310      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7311      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7312      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7313      * <p>
7314      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7315      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7316      * iteration variable.
7317      * The result of the loop handle execution will be the final {@code V} value of that variable
7318      * (or {@code void} if there is no {@code V} variable).
7319      * <p>
7320      * The following rules hold for the argument handles:<ul>
7321      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7322      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7323      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7324      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7325      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7326      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7327      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7328      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7329      * of types called the <em>internal parameter list</em>.
7330      * It will constrain the parameter lists of the other loop parts.
7331      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7332      * with no additional {@code A} types, then the internal parameter list is extended by
7333      * the argument types {@code A...} of the {@code end} handle.
7334      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7335      * list {@code (A...)} is called the <em>external parameter list</em>.
7336      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7337      * additional state variable of the loop.
7338      * The body must both accept a leading parameter and return a value of this type {@code V}.
7339      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7340      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7341      * <a href="MethodHandles.html#effid">effectively identical</a>
7342      * to the external parameter list {@code (A...)}.
7343      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7344      * {@linkplain #empty default value}.
7345      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7346      * effectively identical to the external parameter list {@code (A...)}.
7347      * <li>Likewise, the parameter list of {@code end} must be effectively identical
7348      * to the external parameter list.
7349      * </ul>
7350      * <p>
7351      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7352      * <li>The loop handle's result type is the result type {@code V} of the body.
7353      * <li>The loop handle's parameter types are the types {@code (A...)},
7354      * from the external parameter list.
7355      * </ul>
7356      * <p>
7357      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7358      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7359      * arguments passed to the loop.
7360      * {@snippet lang="java" :
7361      * int start(A...);
7362      * int end(A...);
7363      * V init(A...);
7364      * V body(V, int, A...);
7365      * V countedLoop(A... a...) {
7366      *   int e = end(a...);
7367      *   int s = start(a...);
7368      *   V v = init(a...);
7369      *   for (int i = s; i < e; ++i) {
7370      *     v = body(v, i, a...);
7371      *   }
7372      *   return v;
7373      * }
7374      * }
7375      *
7376      * @apiNote The implementation of this method can be expressed as follows:
7377      * {@snippet lang="java" :
7378      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7379      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7380      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7381      *     // the following semantics:
7382      *     // MH_increment: (int limit, int counter) -> counter + 1
7383      *     // MH_predicate: (int limit, int counter) -> counter < limit
7384      *     Class<?> counterType = start.type().returnType();  // int
7385      *     Class<?> returnType = body.type().returnType();
7386      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7387      *     if (returnType != void.class) {  // ignore the V variable
7388      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7389      *         pred = dropArguments(pred, 1, returnType);  // ditto
7390      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7391      *     }
7392      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
7393      *     MethodHandle[]
7394      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7395      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
7396      *         indexVar   = { start, incr };           // i = start(); i = i + 1
7397      *     return loop(loopLimit, bodyClause, indexVar);
7398      * }
7399      * }
7400      *
7401      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7402      *              See above for other constraints.
7403      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7404      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
7405      * @param init optional initializer, providing the initial value of the loop variable.
7406      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7407      * @param body body of the loop, which may not be {@code null}.
7408      *             It controls the loop parameters and result type in the standard case (see above for details).
7409      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7410      *             and may accept any number of additional types.
7411      *             See above for other constraints.
7412      *
7413      * @return a method handle representing the loop.
7414      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7415      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7416      *
7417      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7418      * @since 9
7419      */
7420     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7421         countedLoopChecks(start, end, init, body);
7422         Class<?> counterType = start.type().returnType();  // int, but who's counting?
7423         Class<?> limitType   = end.type().returnType();    // yes, int again
7424         Class<?> returnType  = body.type().returnType();
7425         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7426         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7427         MethodHandle retv = null;
7428         if (returnType != void.class) {
7429             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7430             pred = dropArguments(pred, 1, returnType);  // ditto
7431             retv = dropArguments(identity(returnType), 0, counterType);
7432         }
7433         body = dropArguments(body, 0, counterType);  // ignore the limit variable
7434         MethodHandle[]
7435             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7436             bodyClause = { init, body },            // v = init(); v = body(v, i)
7437             indexVar   = { start, incr };           // i = start(); i = i + 1
7438         return loop(loopLimit, bodyClause, indexVar);
7439     }
7440 
7441     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7442         Objects.requireNonNull(start);
7443         Objects.requireNonNull(end);
7444         Objects.requireNonNull(body);
7445         Class<?> counterType = start.type().returnType();
7446         if (counterType != int.class) {
7447             MethodType expected = start.type().changeReturnType(int.class);
7448             throw misMatchedTypes("start function", start.type(), expected);
7449         } else if (end.type().returnType() != counterType) {
7450             MethodType expected = end.type().changeReturnType(counterType);
7451             throw misMatchedTypes("end function", end.type(), expected);
7452         }
7453         MethodType bodyType = body.type();
7454         Class<?> returnType = bodyType.returnType();
7455         List<Class<?>> innerList = bodyType.parameterList();
7456         // strip leading V value if present
7457         int vsize = (returnType == void.class ? 0 : 1);
7458         if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7459             // argument list has no "V" => error
7460             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7461             throw misMatchedTypes("body function", bodyType, expected);
7462         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7463             // missing I type => error
7464             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7465             throw misMatchedTypes("body function", bodyType, expected);
7466         }
7467         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7468         if (outerList.isEmpty()) {
7469             // special case; take lists from end handle
7470             outerList = end.type().parameterList();
7471             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7472         }
7473         MethodType expected = methodType(counterType, outerList);
7474         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7475             throw misMatchedTypes("start parameter types", start.type(), expected);
7476         }
7477         if (end.type() != start.type() &&
7478             !end.type().effectivelyIdenticalParameters(0, outerList)) {
7479             throw misMatchedTypes("end parameter types", end.type(), expected);
7480         }
7481         if (init != null) {
7482             MethodType initType = init.type();
7483             if (initType.returnType() != returnType ||
7484                 !initType.effectivelyIdenticalParameters(0, outerList)) {
7485                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7486             }
7487         }
7488     }
7489 
7490     /**
7491      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7492      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7493      * <p>
7494      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7495      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7496      * <p>
7497      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7498      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7499      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7500      * <p>
7501      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7502      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7503      * iteration variable.
7504      * The result of the loop handle execution will be the final {@code V} value of that variable
7505      * (or {@code void} if there is no {@code V} variable).
7506      * <p>
7507      * The following rules hold for the argument handles:<ul>
7508      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7509      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7510      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7511      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7512      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7513      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7514      * of types called the <em>internal parameter list</em>.
7515      * It will constrain the parameter lists of the other loop parts.
7516      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7517      * with no additional {@code A} types, then the internal parameter list is extended by
7518      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7519      * single type {@code Iterable} is added and constitutes the {@code A...} list.
7520      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7521      * list {@code (A...)} is called the <em>external parameter list</em>.
7522      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7523      * additional state variable of the loop.
7524      * The body must both accept a leading parameter and return a value of this type {@code V}.
7525      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7526      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7527      * <a href="MethodHandles.html#effid">effectively identical</a>
7528      * to the external parameter list {@code (A...)}.
7529      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7530      * {@linkplain #empty default value}.
7531      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7532      * type {@code java.util.Iterator} or a subtype thereof.
7533      * The iterator it produces when the loop is executed will be assumed
7534      * to yield values which can be converted to type {@code T}.
7535      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7536      * effectively identical to the external parameter list {@code (A...)}.
7537      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7538      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7539      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7540      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7541      * the {@link MethodHandle#asType asType} conversion method.
7542      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7543      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7544      * </ul>
7545      * <p>
7546      * The type {@code T} may be either a primitive or reference.
7547      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7548      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7549      * as if by the {@link MethodHandle#asType asType} conversion method.
7550      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7551      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7552      * <p>
7553      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7554      * <li>The loop handle's result type is the result type {@code V} of the body.
7555      * <li>The loop handle's parameter types are the types {@code (A...)},
7556      * from the external parameter list.
7557      * </ul>
7558      * <p>
7559      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7560      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7561      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7562      * {@snippet lang="java" :
7563      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7564      * V init(A...);
7565      * V body(V,T,A...);
7566      * V iteratedLoop(A... a...) {
7567      *   Iterator<T> it = iterator(a...);
7568      *   V v = init(a...);
7569      *   while (it.hasNext()) {
7570      *     T t = it.next();
7571      *     v = body(v, t, a...);
7572      *   }
7573      *   return v;
7574      * }
7575      * }
7576      *
7577      * @apiNote Example:
7578      * {@snippet lang="java" :
7579      * // get an iterator from a list
7580      * static List<String> reverseStep(List<String> r, String e) {
7581      *   r.add(0, e);
7582      *   return r;
7583      * }
7584      * static List<String> newArrayList() { return new ArrayList<>(); }
7585      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7586      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7587      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7588      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7589      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7590      * }
7591      *
7592      * @apiNote The implementation of this method can be expressed approximately as follows:
7593      * {@snippet lang="java" :
7594      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7595      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7596      *     Class<?> returnType = body.type().returnType();
7597      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7598      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7599      *     MethodHandle retv = null, step = body, startIter = iterator;
7600      *     if (returnType != void.class) {
7601      *         // the simple thing first:  in (I V A...), drop the I to get V
7602      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7603      *         // body type signature (V T A...), internal loop types (I V A...)
7604      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7605      *     }
7606      *     if (startIter == null)  startIter = MH_getIter;
7607      *     MethodHandle[]
7608      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7609      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7610      *     return loop(iterVar, bodyClause);
7611      * }
7612      * }
7613      *
7614      * @param iterator an optional handle to return the iterator to start the loop.
7615      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7616      *                 See above for other constraints.
7617      * @param init optional initializer, providing the initial value of the loop variable.
7618      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7619      * @param body body of the loop, which may not be {@code null}.
7620      *             It controls the loop parameters and result type in the standard case (see above for details).
7621      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7622      *             and may accept any number of additional types.
7623      *             See above for other constraints.
7624      *
7625      * @return a method handle embodying the iteration loop functionality.
7626      * @throws NullPointerException if the {@code body} handle is {@code null}.
7627      * @throws IllegalArgumentException if any argument violates the above requirements.
7628      *
7629      * @since 9
7630      */
7631     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7632         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7633         Class<?> returnType = body.type().returnType();
7634         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7635         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7636         MethodHandle startIter;
7637         MethodHandle nextVal;
7638         {
7639             MethodType iteratorType;
7640             if (iterator == null) {
7641                 // derive argument type from body, if available, else use Iterable
7642                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7643                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7644             } else {
7645                 // force return type to the internal iterator class
7646                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7647                 startIter = iterator;
7648             }
7649             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7650             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7651 
7652             // perform the asType transforms under an exception transformer, as per spec.:
7653             try {
7654                 startIter = startIter.asType(iteratorType);
7655                 nextVal = nextRaw.asType(nextValType);
7656             } catch (WrongMethodTypeException ex) {
7657                 throw new IllegalArgumentException(ex);
7658             }
7659         }
7660 
7661         MethodHandle retv = null, step = body;
7662         if (returnType != void.class) {
7663             // the simple thing first:  in (I V A...), drop the I to get V
7664             retv = dropArguments(identity(returnType), 0, Iterator.class);
7665             // body type signature (V T A...), internal loop types (I V A...)
7666             step = swapArguments(body, 0, 1);  // swap V <-> T
7667         }
7668 
7669         MethodHandle[]
7670             iterVar    = { startIter, null, hasNext, retv },
7671             bodyClause = { init, filterArgument(step, 0, nextVal) };
7672         return loop(iterVar, bodyClause);
7673     }
7674 
7675     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7676         Objects.requireNonNull(body);
7677         MethodType bodyType = body.type();
7678         Class<?> returnType = bodyType.returnType();
7679         List<Class<?>> internalParamList = bodyType.parameterList();
7680         // strip leading V value if present
7681         int vsize = (returnType == void.class ? 0 : 1);
7682         if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7683             // argument list has no "V" => error
7684             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7685             throw misMatchedTypes("body function", bodyType, expected);
7686         } else if (internalParamList.size() <= vsize) {
7687             // missing T type => error
7688             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7689             throw misMatchedTypes("body function", bodyType, expected);
7690         }
7691         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7692         Class<?> iterableType = null;
7693         if (iterator != null) {
7694             // special case; if the body handle only declares V and T then
7695             // the external parameter list is obtained from iterator handle
7696             if (externalParamList.isEmpty()) {
7697                 externalParamList = iterator.type().parameterList();
7698             }
7699             MethodType itype = iterator.type();
7700             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7701                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7702             }
7703             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7704                 MethodType expected = methodType(itype.returnType(), externalParamList);
7705                 throw misMatchedTypes("iterator parameters", itype, expected);
7706             }
7707         } else {
7708             if (externalParamList.isEmpty()) {
7709                 // special case; if the iterator handle is null and the body handle
7710                 // only declares V and T then the external parameter list consists
7711                 // of Iterable
7712                 externalParamList = List.of(Iterable.class);
7713                 iterableType = Iterable.class;
7714             } else {
7715                 // special case; if the iterator handle is null and the external
7716                 // parameter list is not empty then the first parameter must be
7717                 // assignable to Iterable
7718                 iterableType = externalParamList.get(0);
7719                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7720                     throw newIllegalArgumentException(
7721                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7722                 }
7723             }
7724         }
7725         if (init != null) {
7726             MethodType initType = init.type();
7727             if (initType.returnType() != returnType ||
7728                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7729                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7730             }
7731         }
7732         return iterableType;  // help the caller a bit
7733     }
7734 
7735     /*non-public*/
7736     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7737         // there should be a better way to uncross my wires
7738         int arity = mh.type().parameterCount();
7739         int[] order = new int[arity];
7740         for (int k = 0; k < arity; k++)  order[k] = k;
7741         order[i] = j; order[j] = i;
7742         Class<?>[] types = mh.type().parameterArray();
7743         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7744         MethodType swapType = methodType(mh.type().returnType(), types);
7745         return permuteArguments(mh, swapType, order);
7746     }
7747 
7748     /**
7749      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7750      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7751      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7752      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7753      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7754      * {@code try-finally} handle.
7755      * <p>
7756      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7757      * The first is the exception thrown during the
7758      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7759      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7760      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7761      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7762      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7763      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7764      * <p>
7765      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7766      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7767      * two extra leading parameters:<ul>
7768      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7769      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7770      * the result from the execution of the {@code target} handle.
7771      * This parameter is not present if the {@code target} returns {@code void}.
7772      * </ul>
7773      * <p>
7774      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7775      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7776      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7777      * the cleanup.
7778      * {@snippet lang="java" :
7779      * V target(A..., B...);
7780      * V cleanup(Throwable, V, A...);
7781      * V adapter(A... a, B... b) {
7782      *   V result = (zero value for V);
7783      *   Throwable throwable = null;
7784      *   try {
7785      *     result = target(a..., b...);
7786      *   } catch (Throwable t) {
7787      *     throwable = t;
7788      *     throw t;
7789      *   } finally {
7790      *     result = cleanup(throwable, result, a...);
7791      *   }
7792      *   return result;
7793      * }
7794      * }
7795      * <p>
7796      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7797      * be modified by execution of the target, and so are passed unchanged
7798      * from the caller to the cleanup, if it is invoked.
7799      * <p>
7800      * The target and cleanup must return the same type, even if the cleanup
7801      * always throws.
7802      * To create such a throwing cleanup, compose the cleanup logic
7803      * with {@link #throwException throwException},
7804      * in order to create a method handle of the correct return type.
7805      * <p>
7806      * Note that {@code tryFinally} never converts exceptions into normal returns.
7807      * In rare cases where exceptions must be converted in that way, first wrap
7808      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7809      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7810      * <p>
7811      * It is recommended that the first parameter type of {@code cleanup} be
7812      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7813      * {@code cleanup} will always be invoked with whatever exception that
7814      * {@code target} throws.  Declaring a narrower type may result in a
7815      * {@code ClassCastException} being thrown by the {@code try-finally}
7816      * handle if the type of the exception thrown by {@code target} is not
7817      * assignable to the first parameter type of {@code cleanup}.  Note that
7818      * various exception types of {@code VirtualMachineError},
7819      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7820      * thrown by almost any kind of Java code, and a finally clause that
7821      * catches (say) only {@code IOException} would mask any of the others
7822      * behind a {@code ClassCastException}.
7823      *
7824      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7825      * @param cleanup the handle that is invoked in the finally block.
7826      *
7827      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7828      * @throws NullPointerException if any argument is null
7829      * @throws IllegalArgumentException if {@code cleanup} does not accept
7830      *          the required leading arguments, or if the method handle types do
7831      *          not match in their return types and their
7832      *          corresponding trailing parameters
7833      *
7834      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7835      * @since 9
7836      */
7837     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7838         Class<?>[] targetParamTypes = target.type().ptypes();
7839         Class<?> rtype = target.type().returnType();
7840 
7841         tryFinallyChecks(target, cleanup);
7842 
7843         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7844         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7845         // target parameter list.
7846         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false);
7847 
7848         // Ensure that the intrinsic type checks the instance thrown by the
7849         // target against the first parameter of cleanup
7850         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7851 
7852         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7853         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7854     }
7855 
7856     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7857         Class<?> rtype = target.type().returnType();
7858         if (rtype != cleanup.type().returnType()) {
7859             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7860         }
7861         MethodType cleanupType = cleanup.type();
7862         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7863             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7864         }
7865         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7866             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7867         }
7868         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7869         // target parameter list.
7870         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7871         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7872             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7873                     cleanup.type(), target.type());
7874         }
7875     }
7876 
7877     /**
7878      * Creates a table switch method handle, which can be used to switch over a set of target
7879      * method handles, based on a given target index, called selector.
7880      * <p>
7881      * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7882      * and where {@code N} is the number of target method handles, the table switch method
7883      * handle will invoke the n-th target method handle from the list of target method handles.
7884      * <p>
7885      * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7886      * method handle will invoke the given fallback method handle.
7887      * <p>
7888      * All method handles passed to this method must have the same type, with the additional
7889      * requirement that the leading parameter be of type {@code int}. The leading parameter
7890      * represents the selector.
7891      * <p>
7892      * Any trailing parameters present in the type will appear on the returned table switch
7893      * method handle as well. Any arguments assigned to these parameters will be forwarded,
7894      * together with the selector value, to the selected method handle when invoking it.
7895      *
7896      * @apiNote Example:
7897      * The cases each drop the {@code selector} value they are given, and take an additional
7898      * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7899      * to a specific constant label string for each case:
7900      * {@snippet lang="java" :
7901      * MethodHandles.Lookup lookup = MethodHandles.lookup();
7902      * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7903      *         MethodType.methodType(String.class, String.class));
7904      * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7905      *
7906      * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7907      * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7908      * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7909      *
7910      * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7911      *     caseDefault,
7912      *     case0,
7913      *     case1
7914      * );
7915      *
7916      * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7917      * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7918      * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7919      * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7920      * }
7921      *
7922      * @param fallback the fallback method handle that is called when the selector is not
7923      *                 within the range {@code [0, N)}.
7924      * @param targets array of target method handles.
7925      * @return the table switch method handle.
7926      * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7927      *                              any of the elements of the {@code targets} array are
7928      *                              {@code null}.
7929      * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7930      *                                  parameter of the fallback handle or any of the target
7931      *                                  handles is not {@code int}, or if the types of
7932      *                                  the fallback handle and all of target handles are
7933      *                                  not the same.
7934      */
7935     public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7936         Objects.requireNonNull(fallback);
7937         Objects.requireNonNull(targets);
7938         targets = targets.clone();
7939         MethodType type = tableSwitchChecks(fallback, targets);
7940         return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7941     }
7942 
7943     private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7944         if (caseActions.length == 0)
7945             throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7946 
7947         MethodType expectedType = defaultCase.type();
7948 
7949         if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7950             throw new IllegalArgumentException(
7951                 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7952 
7953         for (MethodHandle mh : caseActions) {
7954             Objects.requireNonNull(mh);
7955             if (mh.type() != expectedType)
7956                 throw new IllegalArgumentException(
7957                     "Case actions must have the same type: " + Arrays.toString(caseActions));
7958         }
7959 
7960         return expectedType;
7961     }
7962 
7963     /**
7964      * Creates a var handle object, which can be used to dereference a {@linkplain java.lang.foreign.MemorySegment memory segment}
7965      * at a given byte offset, using the provided value layout.
7966      *
7967      * <p>The provided layout specifies the {@linkplain ValueLayout#carrier() carrier type},
7968      * the {@linkplain ValueLayout#byteSize() byte size},
7969      * the {@linkplain ValueLayout#byteAlignment() byte alignment} and the {@linkplain ValueLayout#order() byte order}
7970      * associated with the returned var handle.
7971      *
7972      * <p>The list of coordinate types associated with the returned var handle is {@code (MemorySegment, long)},
7973      * where the {@code long} coordinate type corresponds to byte offset into the given memory segment coordinate.
7974      * Thus, the returned var handle accesses bytes at an offset in a given memory segment, composing bytes to or from
7975      * a value of the var handle type. Moreover, the access operation will honor the endianness and the
7976      * alignment constraints expressed in the provided layout.
7977      *
7978      * <p>As an example, consider the memory layout expressed by a {@link GroupLayout} instance constructed as follows:
7979      * {@snippet lang="java" :
7980      *     GroupLayout seq = java.lang.foreign.MemoryLayout.structLayout(
7981      *             MemoryLayout.paddingLayout(4),
7982      *             ValueLayout.JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN).withName("value")
7983      *     );
7984      * }
7985      * To access the member layout named {@code value}, we can construct a memory segment view var handle as follows:
7986      * {@snippet lang="java" :
7987      *     VarHandle handle = MethodHandles.memorySegmentViewVarHandle(ValueLayout.JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN)); //(MemorySegment, long) -> int
7988      *     handle = MethodHandles.insertCoordinates(handle, 1, 4); //(MemorySegment) -> int
7989      * }
7990      *
7991      * @apiNote The resulting var handle features certain <i>access mode restrictions</i>,
7992      * which are common to all memory segment view var handles. A memory segment view var handle is associated
7993      * with an access size {@code S} and an alignment constraint {@code B}
7994      * (both expressed in bytes). We say that a memory access operation is <em>fully aligned</em> if it occurs
7995      * at a memory address {@code A} which is compatible with both alignment constraints {@code S} and {@code B}.
7996      * If access is fully aligned then following access modes are supported and are
7997      * guaranteed to support atomic access:
7998      * <ul>
7999      * <li>read write access modes for all {@code T}, with the exception of
8000      *     access modes {@code get} and {@code set} for {@code long} and
8001      *     {@code double} on 32-bit platforms.
8002      * <li>atomic update access modes for {@code int}, {@code long},
8003      *     {@code float}, {@code double} or {@link MemorySegment}.
8004      *     (Future major platform releases of the JDK may support additional
8005      *     types for certain currently unsupported access modes.)
8006      * <li>numeric atomic update access modes for {@code int}, {@code long} and {@link MemorySegment}.
8007      *     (Future major platform releases of the JDK may support additional
8008      *     numeric types for certain currently unsupported access modes.)
8009      * <li>bitwise atomic update access modes for {@code int}, {@code long} and {@link MemorySegment}.
8010      *     (Future major platform releases of the JDK may support additional
8011      *     numeric types for certain currently unsupported access modes.)
8012      * </ul>
8013      *
8014      * If {@code T} is {@code float}, {@code double} or {@link MemorySegment} then atomic
8015      * update access modes compare values using their bitwise representation
8016      * (see {@link Float#floatToRawIntBits},
8017      * {@link Double#doubleToRawLongBits} and {@link MemorySegment#address()}, respectively).
8018      * <p>
8019      * Alternatively, a memory access operation is <em>partially aligned</em> if it occurs at a memory address {@code A}
8020      * which is only compatible with the alignment constraint {@code B}; in such cases, access for anything other than the
8021      * {@code get} and {@code set} access modes will result in an {@code IllegalStateException}. If access is partially aligned,
8022      * atomic access is only guaranteed with respect to the largest power of two that divides the GCD of {@code A} and {@code S}.
8023      * <p>
8024      * In all other cases, we say that a memory access operation is <em>misaligned</em>; in such cases an
8025      * {@code IllegalStateException} is thrown, irrespective of the access mode being used.
8026      * <p>
8027      * Finally, if {@code T} is {@code MemorySegment} all write access modes throw {@link IllegalArgumentException}
8028      * unless the value to be written is a {@linkplain MemorySegment#isNative() native} memory segment.
8029      *
8030      * @param layout the value layout for which a memory access handle is to be obtained.
8031      * @return the new memory segment view var handle.
8032      * @throws NullPointerException if {@code layout} is {@code null}.
8033      * @see MemoryLayout#varHandle(MemoryLayout.PathElement...)
8034      * @since 19
8035      */
8036     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8037     public static VarHandle memorySegmentViewVarHandle(ValueLayout layout) {
8038         Objects.requireNonNull(layout);
8039         return Utils.makeSegmentViewVarHandle(layout);
8040     }
8041 
8042     /**
8043      * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions.
8044      * <p>
8045      * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where
8046      * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed
8047      * to the target var handle.
8048      * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from
8049      * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function)
8050      * is processed using the second filter and returned to the caller. More advanced access mode types, such as
8051      * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time.
8052      * <p>
8053      * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and
8054      * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case,
8055      * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which
8056      * will be appended to the coordinates of the target var handle).
8057      * <p>
8058      * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will
8059      * throw an {@link IllegalStateException}.
8060      * <p>
8061      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8062      * atomic access guarantees as those featured by the target var handle.
8063      *
8064      * @param target the target var handle
8065      * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target}
8066      * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S}
8067      * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions.
8068      * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types
8069      * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle,
8070      * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions.
8071      * @throws NullPointerException if any of the arguments is {@code null}.
8072      * @since 19
8073      */
8074     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8075     public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
8076         return VarHandles.filterValue(target, filterToTarget, filterFromTarget);
8077     }
8078 
8079     /**
8080      * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions.
8081      * <p>
8082      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values
8083      * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types
8084      * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the
8085      * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered
8086      * by the adaptation) to the target var handle.
8087      * <p>
8088      * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn},
8089      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
8090      * <p>
8091      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8092      * throw an {@link IllegalStateException}.
8093      * <p>
8094      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8095      * atomic access guarantees as those featured by the target var handle.
8096      *
8097      * @param target the target var handle
8098      * @param pos the position of the first coordinate to be transformed
8099      * @param filters the unary functions which are used to transform coordinates starting at position {@code pos}
8100      * @return an adapter var handle which accepts new coordinate types, applying the provided transformation
8101      * to the new coordinate values.
8102      * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types
8103      * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting
8104      * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8105      * or if more filters are provided than the actual number of coordinate types available starting at {@code pos},
8106      * or if it's determined that any of the filters throws any checked exceptions.
8107      * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}.
8108      * @since 19
8109      */
8110     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8111     public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
8112         return VarHandles.filterCoordinates(target, pos, filters);
8113     }
8114 
8115     /**
8116      * Provides a target var handle with one or more <em>bound coordinates</em>
8117      * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less
8118      * coordinate types than the target var handle.
8119      * <p>
8120      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values
8121      * are joined with bound coordinate values, and then passed to the target var handle.
8122      * <p>
8123      * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn },
8124      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
8125      * <p>
8126      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8127      * atomic access guarantees as those featured by the target var handle.
8128      *
8129      * @param target the var handle to invoke after the bound coordinates are inserted
8130      * @param pos the position of the first coordinate to be inserted
8131      * @param values the series of bound coordinates to insert
8132      * @return an adapter var handle which inserts additional coordinates,
8133      *         before calling the target var handle
8134      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8135      * or if more values are provided than the actual number of coordinate types available starting at {@code pos}.
8136      * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types
8137      * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos}
8138      * of the target var handle.
8139      * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}.
8140      * @since 19
8141      */
8142     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8143     public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
8144         return VarHandles.insertCoordinates(target, pos, values);
8145     }
8146 
8147     /**
8148      * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them
8149      * so that the new coordinates match the provided ones.
8150      * <p>
8151      * The given array controls the reordering.
8152      * Call {@code #I} the number of incoming coordinates (the value
8153      * {@code newCoordinates.size()}), and call {@code #O} the number
8154      * of outgoing coordinates (the number of coordinates associated with the target var handle).
8155      * Then the length of the reordering array must be {@code #O},
8156      * and each element must be a non-negative number less than {@code #I}.
8157      * For every {@code N} less than {@code #O}, the {@code N}-th
8158      * outgoing coordinate will be taken from the {@code I}-th incoming
8159      * coordinate, where {@code I} is {@code reorder[N]}.
8160      * <p>
8161      * No coordinate value conversions are applied.
8162      * The type of each incoming coordinate, as determined by {@code newCoordinates},
8163      * must be identical to the type of the corresponding outgoing coordinate
8164      * in the target var handle.
8165      * <p>
8166      * The reordering array need not specify an actual permutation.
8167      * An incoming coordinate will be duplicated if its index appears
8168      * more than once in the array, and an incoming coordinate will be dropped
8169      * if its index does not appear in the array.
8170      * <p>
8171      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8172      * atomic access guarantees as those featured by the target var handle.
8173      * @param target the var handle to invoke after the coordinates have been reordered
8174      * @param newCoordinates the new coordinate types
8175      * @param reorder an index array which controls the reordering
8176      * @return an adapter var handle which re-arranges the incoming coordinate values,
8177      * before calling the target var handle
8178      * @throws IllegalArgumentException if the index array length is not equal to
8179      * the number of coordinates of the target var handle, or if any index array element is not a valid index for
8180      * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in
8181      * the target var handle and in {@code newCoordinates} are not identical.
8182      * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}.
8183      * @since 19
8184      */
8185     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8186     public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
8187         return VarHandles.permuteCoordinates(target, newCoordinates, reorder);
8188     }
8189 
8190     /**
8191      * Adapts a target var handle by pre-processing
8192      * a sub-sequence of its coordinate values with a filter (a method handle).
8193      * The pre-processed coordinates are replaced by the result (if any) of the
8194      * filter function and the target var handle is then called on the modified (usually shortened)
8195      * coordinate list.
8196      * <p>
8197      * If {@code R} is the return type of the filter, then:
8198      * <ul>
8199      * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in
8200      * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos}
8201      * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first,
8202      * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the
8203      * target var handle.</li>
8204      * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the
8205      * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle
8206      * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a
8207      * downstream invocation of the target var handle.</li>
8208      * </ul>
8209      * <p>
8210      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8211      * throw an {@link IllegalStateException}.
8212      * <p>
8213      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8214      * atomic access guarantees as those featured by the target var handle.
8215      *
8216      * @param target the var handle to invoke after the coordinates have been filtered
8217      * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted
8218      * @param filter the filter method handle
8219      * @return an adapter var handle which filters the incoming coordinate values,
8220      * before calling the target var handle
8221      * @throws IllegalArgumentException if the return type of {@code filter}
8222      * is not void, and it is not the same as the {@code pos} coordinate of the target var handle,
8223      * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8224      * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>,
8225      * or if it's determined that {@code filter} throws any checked exceptions.
8226      * @throws NullPointerException if any of the arguments is {@code null}.
8227      * @since 19
8228      */
8229     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8230     public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
8231         return VarHandles.collectCoordinates(target, pos, filter);
8232     }
8233 
8234     /**
8235      * Returns a var handle which will discard some dummy coordinates before delegating to the
8236      * target var handle. As a consequence, the resulting var handle will feature more
8237      * coordinate types than the target var handle.
8238      * <p>
8239      * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the
8240      * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede
8241      * the target's real arguments; if {@code pos} is <i>N</i> they will come after.
8242      * <p>
8243      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8244      * atomic access guarantees as those featured by the target var handle.
8245      *
8246      * @param target the var handle to invoke after the dummy coordinates are dropped
8247      * @param pos position of the first coordinate to drop (zero for the leftmost)
8248      * @param valueTypes the type(s) of the coordinate(s) to drop
8249      * @return an adapter var handle which drops some dummy coordinates,
8250      *         before calling the target var handle
8251      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive.
8252      * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}.
8253      * @since 19
8254      */
8255     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8256     public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
8257         return VarHandles.dropCoordinates(target, pos, valueTypes);
8258     }
8259 }