1 /*
   2  * Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import jdk.internal.access.SharedSecrets;
  29 import jdk.internal.misc.Unsafe;
  30 import jdk.internal.misc.VM;
  31 import jdk.internal.org.objectweb.asm.ClassReader;
  32 import jdk.internal.org.objectweb.asm.Opcodes;
  33 import jdk.internal.org.objectweb.asm.Type;
  34 import jdk.internal.reflect.CallerSensitive;
  35 import jdk.internal.reflect.CallerSensitiveAdapter;
  36 import jdk.internal.reflect.Reflection;
  37 import jdk.internal.util.ClassFileDumper;
  38 import jdk.internal.vm.annotation.ForceInline;
  39 import sun.invoke.util.ValueConversions;
  40 import sun.invoke.util.VerifyAccess;
  41 import sun.invoke.util.Wrapper;
  42 import sun.reflect.misc.ReflectUtil;
  43 import sun.security.util.SecurityConstants;
  44 
  45 import java.lang.constant.ConstantDescs;
  46 import java.lang.invoke.LambdaForm.BasicType;
  47 import java.lang.reflect.Constructor;
  48 import java.lang.reflect.Field;
  49 import java.lang.reflect.Member;
  50 import java.lang.reflect.Method;
  51 import java.lang.reflect.Modifier;
  52 import java.nio.ByteOrder;
  53 import java.security.ProtectionDomain;
  54 import java.util.ArrayList;
  55 import java.util.Arrays;
  56 import java.util.BitSet;
  57 import java.util.Comparator;
  58 import java.util.Iterator;
  59 import java.util.List;
  60 import java.util.Objects;
  61 import java.util.Set;
  62 import java.util.concurrent.ConcurrentHashMap;
  63 import java.util.stream.Stream;
  64 
  65 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
  66 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  67 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  68 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
  69 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  70 import static java.lang.invoke.MethodHandleStatics.newInternalError;
  71 import static java.lang.invoke.MethodType.methodType;
  72 
  73 /**
  74  * This class consists exclusively of static methods that operate on or return
  75  * method handles. They fall into several categories:
  76  * <ul>
  77  * <li>Lookup methods which help create method handles for methods and fields.
  78  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  79  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  80  * </ul>
  81  * A lookup, combinator, or factory method will fail and throw an
  82  * {@code IllegalArgumentException} if the created method handle's type
  83  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  84  *
  85  * @author John Rose, JSR 292 EG
  86  * @since 1.7
  87  */
  88 public class MethodHandles {
  89 
  90     private MethodHandles() { }  // do not instantiate
  91 
  92     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  93 
  94     // See IMPL_LOOKUP below.
  95 
  96     //// Method handle creation from ordinary methods.
  97 
  98     /**
  99      * Returns a {@link Lookup lookup object} with
 100      * full capabilities to emulate all supported bytecode behaviors of the caller.
 101      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
 102      * Factory methods on the lookup object can create
 103      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
 104      * for any member that the caller has access to via bytecodes,
 105      * including protected and private fields and methods.
 106      * This lookup object is created by the original lookup class
 107      * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
 108      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 109      * Do not store it in place where untrusted code can access it.
 110      * <p>
 111      * This method is caller sensitive, which means that it may return different
 112      * values to different callers.
 113      * In cases where {@code MethodHandles.lookup} is called from a context where
 114      * there is no caller frame on the stack (e.g. when called directly
 115      * from a JNI attached thread), {@code IllegalCallerException} is thrown.
 116      * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will
 117      * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()}
 118      * to obtain a low-privileged lookup instead.
 119      * @return a lookup object for the caller of this method, with
 120      * {@linkplain Lookup#ORIGINAL original} and
 121      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
 122      * @throws IllegalCallerException if there is no caller frame on the stack.
 123      */
 124     @CallerSensitive
 125     @ForceInline // to ensure Reflection.getCallerClass optimization
 126     public static Lookup lookup() {
 127         final Class<?> c = Reflection.getCallerClass();
 128         if (c == null) {
 129             throw new IllegalCallerException("no caller frame");
 130         }
 131         return new Lookup(c);
 132     }
 133 
 134     /**
 135      * This lookup method is the alternate implementation of
 136      * the lookup method with a leading caller class argument which is
 137      * non-caller-sensitive.  This method is only invoked by reflection
 138      * and method handle.
 139      */
 140     @CallerSensitiveAdapter
 141     private static Lookup lookup(Class<?> caller) {
 142         if (caller.getClassLoader() == null) {
 143             throw newInternalError("calling lookup() reflectively is not supported: "+caller);
 144         }
 145         return new Lookup(caller);
 146     }
 147 
 148     /**
 149      * Returns a {@link Lookup lookup object} which is trusted minimally.
 150      * The lookup has the {@code UNCONDITIONAL} mode.
 151      * It can only be used to create method handles to public members of
 152      * public classes in packages that are exported unconditionally.
 153      * <p>
 154      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 155      * of this lookup object will be {@link java.lang.Object}.
 156      *
 157      * @apiNote The use of Object is conventional, and because the lookup modes are
 158      * limited, there is no special access provided to the internals of Object, its package
 159      * or its module.  This public lookup object or other lookup object with
 160      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 161      * is not used to determine the lookup context.
 162      *
 163      * <p style="font-size:smaller;">
 164      * <em>Discussion:</em>
 165      * The lookup class can be changed to any other class {@code C} using an expression of the form
 166      * {@link Lookup#in publicLookup().in(C.class)}.
 167      * A public lookup object is always subject to
 168      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 169      * Also, it cannot access
 170      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 171      * @return a lookup object which is trusted minimally
 172      */
 173     public static Lookup publicLookup() {
 174         return Lookup.PUBLIC_LOOKUP;
 175     }
 176 
 177     /**
 178      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 179      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 180      * The returned lookup object can provide access to classes in modules and packages,
 181      * and members of those classes, outside the normal rules of Java access control,
 182      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 183      * <p>
 184      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 185      * allowed to do deep reflection on module {@code M2} and package of the target class
 186      * if and only if all of the following conditions are {@code true}:
 187      * <ul>
 188      * <li>If there is a security manager, its {@code checkPermission} method is
 189      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 190      * that must return normally.
 191      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 192      * full privilege access}.  Specifically:
 193      *   <ul>
 194      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 195      *         (This is because otherwise there would be no way to ensure the original lookup
 196      *         creator was a member of any particular module, and so any subsequent checks
 197      *         for readability and qualified exports would become ineffective.)
 198      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 199      *         (This is because an application intending to share intra-module access
 200      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 201      *         deep reflection to its own module.)
 202      *   </ul>
 203      * <li>The target class must be a proper class, not a primitive or array class.
 204      * (Thus, {@code M2} is well-defined.)
 205      * <li>If the caller module {@code M1} differs from
 206      * the target module {@code M2} then both of the following must be true:
 207      *   <ul>
 208      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 209      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 210      *         containing the target class to at least {@code M1}.</li>
 211      *   </ul>
 212      * </ul>
 213      * <p>
 214      * If any of the above checks is violated, this method fails with an
 215      * exception.
 216      * <p>
 217      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 218      * returns a {@code Lookup} on {@code targetClass} with
 219      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 220      * with {@code null} previous lookup class.
 221      * <p>
 222      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 223      * returns a {@code Lookup} on {@code targetClass} that records
 224      * the lookup class of the caller as the new previous lookup class with
 225      * {@code PRIVATE} access but no {@code MODULE} access.
 226      * <p>
 227      * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
 228      *
 229      * @apiNote The {@code Lookup} object returned by this method is allowed to
 230      * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
 231      * of {@code targetClass}. Extreme caution should be taken when opening a package
 232      * to another module as such defined classes have the same full privilege
 233      * access as other members in {@code targetClass}'s module.
 234      *
 235      * @param targetClass the target class
 236      * @param caller the caller lookup object
 237      * @return a lookup object for the target class, with private access
 238      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 239      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 240      * @throws SecurityException if denied by the security manager
 241      * @throws IllegalAccessException if any of the other access checks specified above fails
 242      * @since 9
 243      * @see Lookup#dropLookupMode
 244      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 245      */
 246     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 247         if (caller.allowedModes == Lookup.TRUSTED) {
 248             return new Lookup(targetClass);
 249         }
 250 
 251         @SuppressWarnings("removal")
 252         SecurityManager sm = System.getSecurityManager();
 253         if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 254         if (targetClass.isPrimitive())
 255             throw new IllegalArgumentException(targetClass + " is a primitive class");
 256         if (targetClass.isArray())
 257             throw new IllegalArgumentException(targetClass + " is an array class");
 258         // Ensure that we can reason accurately about private and module access.
 259         int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
 260         if ((caller.lookupModes() & requireAccess) != requireAccess)
 261             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 262 
 263         // previous lookup class is never set if it has MODULE access
 264         assert caller.previousLookupClass() == null;
 265 
 266         Class<?> callerClass = caller.lookupClass();
 267         Module callerModule = callerClass.getModule();  // M1
 268         Module targetModule = targetClass.getModule();  // M2
 269         Class<?> newPreviousClass = null;
 270         int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
 271 
 272         if (targetModule != callerModule) {
 273             if (!callerModule.canRead(targetModule))
 274                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 275             if (targetModule.isNamed()) {
 276                 String pn = targetClass.getPackageName();
 277                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 278                 if (!targetModule.isOpen(pn, callerModule))
 279                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 280             }
 281 
 282             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 283             newPreviousClass = callerClass;
 284             newModes &= ~Lookup.MODULE;
 285         }
 286         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 287     }
 288 
 289     /**
 290      * Returns the <em>class data</em> associated with the lookup class
 291      * of the given {@code caller} lookup object, or {@code null}.
 292      *
 293      * <p> A hidden class with class data can be created by calling
 294      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 295      * Lookup::defineHiddenClassWithClassData}.
 296      * This method will cause the static class initializer of the lookup
 297      * class of the given {@code caller} lookup object be executed if
 298      * it has not been initialized.
 299      *
 300      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 301      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 302      * {@code null} is returned if this method is called on the lookup object
 303      * on these classes.
 304      *
 305      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 306      * must have {@linkplain Lookup#ORIGINAL original access}
 307      * in order to retrieve the class data.
 308      *
 309      * @apiNote
 310      * This method can be called as a bootstrap method for a dynamically computed
 311      * constant.  A framework can create a hidden class with class data, for
 312      * example that can be {@code Class} or {@code MethodHandle} object.
 313      * The class data is accessible only to the lookup object
 314      * created by the original caller but inaccessible to other members
 315      * in the same nest.  If a framework passes security sensitive objects
 316      * to a hidden class via class data, it is recommended to load the value
 317      * of class data as a dynamically computed constant instead of storing
 318      * the class data in private static field(s) which are accessible to
 319      * other nestmates.
 320      *
 321      * @param <T> the type to cast the class data object to
 322      * @param caller the lookup context describing the class performing the
 323      * operation (normally stacked by the JVM)
 324      * @param name must be {@link ConstantDescs#DEFAULT_NAME}
 325      *             ({@code "_"})
 326      * @param type the type of the class data
 327      * @return the value of the class data if present in the lookup class;
 328      * otherwise {@code null}
 329      * @throws IllegalArgumentException if name is not {@code "_"}
 330      * @throws IllegalAccessException if the lookup context does not have
 331      * {@linkplain Lookup#ORIGINAL original} access
 332      * @throws ClassCastException if the class data cannot be converted to
 333      * the given {@code type}
 334      * @throws NullPointerException if {@code caller} or {@code type} argument
 335      * is {@code null}
 336      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 337      * @see MethodHandles#classDataAt(Lookup, String, Class, int)
 338      * @since 16
 339      * @jvms 5.5 Initialization
 340      */
 341      public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 342          Objects.requireNonNull(caller);
 343          Objects.requireNonNull(type);
 344          if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
 345              throw new IllegalArgumentException("name must be \"_\": " + name);
 346          }
 347 
 348          if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL)  {
 349              throw new IllegalAccessException(caller + " does not have ORIGINAL access");
 350          }
 351 
 352          Object classdata = classData(caller.lookupClass());
 353          if (classdata == null) return null;
 354 
 355          try {
 356              return BootstrapMethodInvoker.widenAndCast(classdata, type);
 357          } catch (RuntimeException|Error e) {
 358              throw e; // let CCE and other runtime exceptions through
 359          } catch (Throwable e) {
 360              throw new InternalError(e);
 361          }
 362     }
 363 
 364     /*
 365      * Returns the class data set by the VM in the Class::classData field.
 366      *
 367      * This is also invoked by LambdaForms as it cannot use condy via
 368      * MethodHandles::classData due to bootstrapping issue.
 369      */
 370     static Object classData(Class<?> c) {
 371         UNSAFE.ensureClassInitialized(c);
 372         return SharedSecrets.getJavaLangAccess().classData(c);
 373     }
 374 
 375     /**
 376      * Returns the element at the specified index in the
 377      * {@linkplain #classData(Lookup, String, Class) class data},
 378      * if the class data associated with the lookup class
 379      * of the given {@code caller} lookup object is a {@code List}.
 380      * If the class data is not present in this lookup class, this method
 381      * returns {@code null}.
 382      *
 383      * <p> A hidden class with class data can be created by calling
 384      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 385      * Lookup::defineHiddenClassWithClassData}.
 386      * This method will cause the static class initializer of the lookup
 387      * class of the given {@code caller} lookup object be executed if
 388      * it has not been initialized.
 389      *
 390      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 391      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 392      * {@code null} is returned if this method is called on the lookup object
 393      * on these classes.
 394      *
 395      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 396      * must have {@linkplain Lookup#ORIGINAL original access}
 397      * in order to retrieve the class data.
 398      *
 399      * @apiNote
 400      * This method can be called as a bootstrap method for a dynamically computed
 401      * constant.  A framework can create a hidden class with class data, for
 402      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 403      * one object and use this method to load one element at a specific index.
 404      * The class data is accessible only to the lookup object
 405      * created by the original caller but inaccessible to other members
 406      * in the same nest.  If a framework passes security sensitive objects
 407      * to a hidden class via class data, it is recommended to load the value
 408      * of class data as a dynamically computed constant instead of storing
 409      * the class data in private static field(s) which are accessible to other
 410      * nestmates.
 411      *
 412      * @param <T> the type to cast the result object to
 413      * @param caller the lookup context describing the class performing the
 414      * operation (normally stacked by the JVM)
 415      * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
 416      *             ({@code "_"})
 417      * @param type the type of the element at the given index in the class data
 418      * @param index index of the element in the class data
 419      * @return the element at the given index in the class data
 420      * if the class data is present; otherwise {@code null}
 421      * @throws IllegalArgumentException if name is not {@code "_"}
 422      * @throws IllegalAccessException if the lookup context does not have
 423      * {@linkplain Lookup#ORIGINAL original} access
 424      * @throws ClassCastException if the class data cannot be converted to {@code List}
 425      * or the element at the specified index cannot be converted to the given type
 426      * @throws IndexOutOfBoundsException if the index is out of range
 427      * @throws NullPointerException if {@code caller} or {@code type} argument is
 428      * {@code null}; or if unboxing operation fails because
 429      * the element at the given index is {@code null}
 430      *
 431      * @since 16
 432      * @see #classData(Lookup, String, Class)
 433      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 434      */
 435     public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
 436             throws IllegalAccessException
 437     {
 438         @SuppressWarnings("unchecked")
 439         List<Object> classdata = (List<Object>)classData(caller, name, List.class);
 440         if (classdata == null) return null;
 441 
 442         try {
 443             Object element = classdata.get(index);
 444             return BootstrapMethodInvoker.widenAndCast(element, type);
 445         } catch (RuntimeException|Error e) {
 446             throw e; // let specified exceptions and other runtime exceptions/errors through
 447         } catch (Throwable e) {
 448             throw new InternalError(e);
 449         }
 450     }
 451 
 452     /**
 453      * Performs an unchecked "crack" of a
 454      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 455      * The result is as if the user had obtained a lookup object capable enough
 456      * to crack the target method handle, called
 457      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 458      * on the target to obtain its symbolic reference, and then called
 459      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 460      * to resolve the symbolic reference to a member.
 461      * <p>
 462      * If there is a security manager, its {@code checkPermission} method
 463      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 464      * @param <T> the desired type of the result, either {@link Member} or a subtype
 465      * @param target a direct method handle to crack into symbolic reference components
 466      * @param expected a class object representing the desired result type {@code T}
 467      * @return a reference to the method, constructor, or field object
 468      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 469      * @throws    NullPointerException if either argument is {@code null}
 470      * @throws    IllegalArgumentException if the target is not a direct method handle
 471      * @throws    ClassCastException if the member is not of the expected type
 472      * @since 1.8
 473      */
 474     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 475         @SuppressWarnings("removal")
 476         SecurityManager smgr = System.getSecurityManager();
 477         if (smgr != null)  smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 478         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 479         return lookup.revealDirect(target).reflectAs(expected, lookup);
 480     }
 481 
 482     /**
 483      * A <em>lookup object</em> is a factory for creating method handles,
 484      * when the creation requires access checking.
 485      * Method handles do not perform
 486      * access checks when they are called, but rather when they are created.
 487      * Therefore, method handle access
 488      * restrictions must be enforced when a method handle is created.
 489      * The caller class against which those restrictions are enforced
 490      * is known as the {@linkplain #lookupClass() lookup class}.
 491      * <p>
 492      * A lookup class which needs to create method handles will call
 493      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 494      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 495      * determined, and securely stored in the {@code Lookup} object.
 496      * The lookup class (or its delegates) may then use factory methods
 497      * on the {@code Lookup} object to create method handles for access-checked members.
 498      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 499      * even private ones.
 500      *
 501      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 502      * The factory methods on a {@code Lookup} object correspond to all major
 503      * use cases for methods, constructors, and fields.
 504      * Each method handle created by a factory method is the functional
 505      * equivalent of a particular <em>bytecode behavior</em>.
 506      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 507      * the Java Virtual Machine Specification.)
 508      * Here is a summary of the correspondence between these factory methods and
 509      * the behavior of the resulting method handles:
 510      * <table class="striped">
 511      * <caption style="display:none">lookup method behaviors</caption>
 512      * <thead>
 513      * <tr>
 514      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 515      *     <th scope="col">member</th>
 516      *     <th scope="col">bytecode behavior</th>
 517      * </tr>
 518      * </thead>
 519      * <tbody>
 520      * <tr>
 521      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 522      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 523      * </tr>
 524      * <tr>
 525      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 526      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 527      * </tr>
 528      * <tr>
 529      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 530      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 531      * </tr>
 532      * <tr>
 533      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 534      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 535      * </tr>
 536      * <tr>
 537      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 538      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 539      * </tr>
 540      * <tr>
 541      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 542      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 543      * </tr>
 544      * <tr>
 545      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 546      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 547      * </tr>
 548      * <tr>
 549      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 550      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 551      * </tr>
 552      * <tr>
 553      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 554      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 555      * </tr>
 556      * <tr>
 557      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 558      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 559      * </tr>
 560      * <tr>
 561      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 562      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 563      * </tr>
 564      * <tr>
 565      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 566      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 567      * </tr>
 568      * <tr>
 569      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 570      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 571      * </tr>
 572      * <tr>
 573      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 574      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 575      * </tr>
 576      * </tbody>
 577      * </table>
 578      *
 579      * Here, the type {@code C} is the class or interface being searched for a member,
 580      * documented as a parameter named {@code refc} in the lookup methods.
 581      * The method type {@code MT} is composed from the return type {@code T}
 582      * and the sequence of argument types {@code A*}.
 583      * The constructor also has a sequence of argument types {@code A*} and
 584      * is deemed to return the newly-created object of type {@code C}.
 585      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 586      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 587      * if it is present, it is always the leading argument to the method handle invocation.
 588      * (In the case of some {@code protected} members, {@code this} may be
 589      * restricted in type to the lookup class; see below.)
 590      * The name {@code arg} stands for all the other method handle arguments.
 591      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 592      * stands for a null reference if the accessed method or field is static,
 593      * and {@code this} otherwise.
 594      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 595      * for reflective objects corresponding to the given members declared in type {@code C}.
 596      * <p>
 597      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 598      * as if by {@code ldc CONSTANT_Class}.
 599      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 600      * <p>
 601      * In cases where the given member is of variable arity (i.e., a method or constructor)
 602      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 603      * In all other cases, the returned method handle will be of fixed arity.
 604      * <p style="font-size:smaller;">
 605      * <em>Discussion:</em>
 606      * The equivalence between looked-up method handles and underlying
 607      * class members and bytecode behaviors
 608      * can break down in a few ways:
 609      * <ul style="font-size:smaller;">
 610      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 611      * the lookup can still succeed, even when there is no equivalent
 612      * Java expression or bytecoded constant.
 613      * <li>Likewise, if {@code T} or {@code MT}
 614      * is not symbolically accessible from the lookup class's loader,
 615      * the lookup can still succeed.
 616      * For example, lookups for {@code MethodHandle.invokeExact} and
 617      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 618      * <li>If there is a security manager installed, it can forbid the lookup
 619      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 620      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 621      * constant is not subject to security manager checks.
 622      * <li>If the looked-up method has a
 623      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 624      * the method handle creation may fail with an
 625      * {@code IllegalArgumentException}, due to the method handle type having
 626      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 627      * </ul>
 628      *
 629      * <h2><a id="access"></a>Access checking</h2>
 630      * Access checks are applied in the factory methods of {@code Lookup},
 631      * when a method handle is created.
 632      * This is a key difference from the Core Reflection API, since
 633      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 634      * performs access checking against every caller, on every call.
 635      * <p>
 636      * All access checks start from a {@code Lookup} object, which
 637      * compares its recorded lookup class against all requests to
 638      * create method handles.
 639      * A single {@code Lookup} object can be used to create any number
 640      * of access-checked method handles, all checked against a single
 641      * lookup class.
 642      * <p>
 643      * A {@code Lookup} object can be shared with other trusted code,
 644      * such as a metaobject protocol.
 645      * A shared {@code Lookup} object delegates the capability
 646      * to create method handles on private members of the lookup class.
 647      * Even if privileged code uses the {@code Lookup} object,
 648      * the access checking is confined to the privileges of the
 649      * original lookup class.
 650      * <p>
 651      * A lookup can fail, because
 652      * the containing class is not accessible to the lookup class, or
 653      * because the desired class member is missing, or because the
 654      * desired class member is not accessible to the lookup class, or
 655      * because the lookup object is not trusted enough to access the member.
 656      * In the case of a field setter function on a {@code final} field,
 657      * finality enforcement is treated as a kind of access control,
 658      * and the lookup will fail, except in special cases of
 659      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 660      * In any of these cases, a {@code ReflectiveOperationException} will be
 661      * thrown from the attempted lookup.  The exact class will be one of
 662      * the following:
 663      * <ul>
 664      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 665      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 666      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 667      * </ul>
 668      * <p>
 669      * In general, the conditions under which a method handle may be
 670      * looked up for a method {@code M} are no more restrictive than the conditions
 671      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 672      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 673      * a method handle lookup will generally raise a corresponding
 674      * checked exception, such as {@code NoSuchMethodException}.
 675      * And the effect of invoking the method handle resulting from the lookup
 676      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 677      * to executing the compiled, verified, and resolved call to {@code M}.
 678      * The same point is true of fields and constructors.
 679      * <p style="font-size:smaller;">
 680      * <em>Discussion:</em>
 681      * Access checks only apply to named and reflected methods,
 682      * constructors, and fields.
 683      * Other method handle creation methods, such as
 684      * {@link MethodHandle#asType MethodHandle.asType},
 685      * do not require any access checks, and are used
 686      * independently of any {@code Lookup} object.
 687      * <p>
 688      * If the desired member is {@code protected}, the usual JVM rules apply,
 689      * including the requirement that the lookup class must either be in the
 690      * same package as the desired member, or must inherit that member.
 691      * (See the Java Virtual Machine Specification, sections {@jvms
 692      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 693      * In addition, if the desired member is a non-static field or method
 694      * in a different package, the resulting method handle may only be applied
 695      * to objects of the lookup class or one of its subclasses.
 696      * This requirement is enforced by narrowing the type of the leading
 697      * {@code this} parameter from {@code C}
 698      * (which will necessarily be a superclass of the lookup class)
 699      * to the lookup class itself.
 700      * <p>
 701      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 702      * that the receiver argument must match both the resolved method <em>and</em>
 703      * the current class.  Again, this requirement is enforced by narrowing the
 704      * type of the leading parameter to the resulting method handle.
 705      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 706      * <p>
 707      * The JVM represents constructors and static initializer blocks as internal methods
 708      * with special names ({@value ConstantDescs#INIT_NAME} and {@value
 709      * ConstantDescs#CLASS_INIT_NAME}).
 710      * The internal syntax of invocation instructions allows them to refer to such internal
 711      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 712      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 713      * <p>
 714      * If the relationship between nested types is expressed directly through the
 715      * {@code NestHost} and {@code NestMembers} attributes
 716      * (see the Java Virtual Machine Specification, sections {@jvms
 717      * 4.7.28} and {@jvms 4.7.29}),
 718      * then the associated {@code Lookup} object provides direct access to
 719      * the lookup class and all of its nestmates
 720      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 721      * Otherwise, access between nested classes is obtained by the Java compiler creating
 722      * a wrapper method to access a private method of another class in the same nest.
 723      * For example, a nested class {@code C.D}
 724      * can access private members within other related classes such as
 725      * {@code C}, {@code C.D.E}, or {@code C.B},
 726      * but the Java compiler may need to generate wrapper methods in
 727      * those related classes.  In such cases, a {@code Lookup} object on
 728      * {@code C.E} would be unable to access those private members.
 729      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 730      * which can transform a lookup on {@code C.E} into one on any of those other
 731      * classes, without special elevation of privilege.
 732      * <p>
 733      * The accesses permitted to a given lookup object may be limited,
 734      * according to its set of {@link #lookupModes lookupModes},
 735      * to a subset of members normally accessible to the lookup class.
 736      * For example, the {@link MethodHandles#publicLookup publicLookup}
 737      * method produces a lookup object which is only allowed to access
 738      * public members in public classes of exported packages.
 739      * The caller sensitive method {@link MethodHandles#lookup lookup}
 740      * produces a lookup object with full capabilities relative to
 741      * its caller class, to emulate all supported bytecode behaviors.
 742      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 743      * with fewer access modes than the original lookup object.
 744      *
 745      * <p style="font-size:smaller;">
 746      * <a id="privacc"></a>
 747      * <em>Discussion of private and module access:</em>
 748      * We say that a lookup has <em>private access</em>
 749      * if its {@linkplain #lookupModes lookup modes}
 750      * include the possibility of accessing {@code private} members
 751      * (which includes the private members of nestmates).
 752      * As documented in the relevant methods elsewhere,
 753      * only lookups with private access possess the following capabilities:
 754      * <ul style="font-size:smaller;">
 755      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 756      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 757      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 758      *     for classes accessible to the lookup class
 759      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 760      *     within the same package member
 761      * </ul>
 762      * <p style="font-size:smaller;">
 763      * Similarly, a lookup with module access ensures that the original lookup creator was
 764      * a member in the same module as the lookup class.
 765      * <p style="font-size:smaller;">
 766      * Private and module access are independently determined modes; a lookup may have
 767      * either or both or neither.  A lookup which possesses both access modes is said to
 768      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
 769      * <p style="font-size:smaller;">
 770      * A lookup with <em>original access</em> ensures that this lookup is created by
 771      * the original lookup class and the bootstrap method invoked by the VM.
 772      * Such a lookup with original access also has private and module access
 773      * which has the following additional capability:
 774      * <ul style="font-size:smaller;">
 775      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 776      *     such as {@code Class.forName}
 777      * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
 778      * class data} associated with the lookup class</li>
 779      * </ul>
 780      * <p style="font-size:smaller;">
 781      * Each of these permissions is a consequence of the fact that a lookup object
 782      * with private access can be securely traced back to an originating class,
 783      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 784      * can be reliably determined and emulated by method handles.
 785      *
 786      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 787      * When a lookup class in one module {@code M1} accesses a class in another module
 788      * {@code M2}, extra access checking is performed beyond the access mode bits.
 789      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 790      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 791      * and when the type is in a package of {@code M2} that is exported to
 792      * at least {@code M1}.
 793      * <p>
 794      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 795      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 796      * MethodHandles.privateLookupIn} methods.
 797      * Teleporting across modules will always record the original lookup class as
 798      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 799      * and drops {@link Lookup#MODULE MODULE} access.
 800      * If the target class is in the same module as the lookup class {@code C},
 801      * then the target class becomes the new lookup class
 802      * and there is no change to the previous lookup class.
 803      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 804      * {@code C} becomes the new previous lookup class
 805      * and the target class becomes the new lookup class.
 806      * In that case, if there was already a previous lookup class in {@code M0},
 807      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 808      * drops all privileges.
 809      * For example,
 810      * {@snippet lang="java" :
 811      * Lookup lookup = MethodHandles.lookup();   // in class C
 812      * Lookup lookup2 = lookup.in(D.class);
 813      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 814      * }
 815      * <p>
 816      * The {@link #lookup()} factory method produces a {@code Lookup} object
 817      * with {@code null} previous lookup class.
 818      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 819      * to class {@code D} without elevation of privileges.
 820      * If {@code C} and {@code D} are in the same module,
 821      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 822      * same previous lookup class as the original {@code lookup}, or
 823      * {@code null} if not present.
 824      * <p>
 825      * When a {@code Lookup} teleports from a class
 826      * in one nest to another nest, {@code PRIVATE} access is dropped.
 827      * When a {@code Lookup} teleports from a class in one package to
 828      * another package, {@code PACKAGE} access is dropped.
 829      * When a {@code Lookup} teleports from a class in one module to another module,
 830      * {@code MODULE} access is dropped.
 831      * Teleporting across modules drops the ability to access non-exported classes
 832      * in both the module of the new lookup class and the module of the old lookup class
 833      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 834      * A {@code Lookup} can teleport back and forth to a class in the module of
 835      * the lookup class and the module of the previous class lookup.
 836      * Teleporting across modules can only decrease access but cannot increase it.
 837      * Teleporting to some third module drops all accesses.
 838      * <p>
 839      * In the above example, if {@code C} and {@code D} are in different modules,
 840      * {@code lookup2} records {@code D} as its lookup class and
 841      * {@code C} as its previous lookup class and {@code lookup2} has only
 842      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 843      * {@code C}'s module and {@code D}'s module.
 844      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 845      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 846      * class {@code D} is recorded as its previous lookup class.
 847      * <p>
 848      * Teleporting across modules restricts access to the public types that
 849      * both the lookup class and the previous lookup class can equally access
 850      * (see below).
 851      * <p>
 852      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 853      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 854      * and produce a new {@code Lookup} with <a href="#privacc">private access</a>
 855      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 856      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 857      * to call {@code privateLookupIn}.
 858      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 859      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 860      * produces a new {@code Lookup} on {@code T} with full capabilities.
 861      * A {@code lookup} on {@code C} is also allowed
 862      * to do deep reflection on {@code T} in another module {@code M2} if
 863      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 864      * the package containing {@code T} to at least {@code M1}.
 865      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 866      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 867      * The resulting {@code Lookup} can be used to do member lookup or teleport
 868      * to another lookup class by calling {@link #in Lookup::in}.  But
 869      * it cannot be used to obtain another private {@code Lookup} by calling
 870      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 871      * because it has no {@code MODULE} access.
 872      * <p>
 873      * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to
 874      * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
 875      * of {@code T}. Extreme caution should be taken when opening a package
 876      * to another module as such defined classes have the same full privilege
 877      * access as other members in {@code M2}.
 878      *
 879      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 880      *
 881      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 882      * allows cross-module access. The access checking is performed with respect
 883      * to both the lookup class and the previous lookup class if present.
 884      * <p>
 885      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 886      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 887      * exported unconditionally}.
 888      * <p>
 889      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 890      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 891      * that are readable to {@code M1} and the type is in a package that is exported
 892      * at least to {@code M1}.
 893      * <p>
 894      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 895      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 896      * the intersection of all public types that are accessible to {@code M1}
 897      * with all public types that are accessible to {@code M0}. {@code M0}
 898      * reads {@code M1} and hence the set of accessible types includes:
 899      *
 900      * <ul>
 901      * <li>unconditional-exported packages from {@code M1}</li>
 902      * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li>
 903      * <li>
 904      *     unconditional-exported packages from a third module {@code M2}if both {@code M0}
 905      *     and {@code M1} read {@code M2}
 906      * </li>
 907      * <li>qualified-exported packages from {@code M1} to {@code M0}</li>
 908      * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li>
 909      * <li>
 910      *     qualified-exported packages from a third module {@code M2} to both {@code M0} and
 911      *     {@code M1} if both {@code M0} and {@code M1} read {@code M2}
 912      * </li>
 913      * </ul>
 914      *
 915      * <h2><a id="access-modes"></a>Access modes</h2>
 916      *
 917      * The table below shows the access modes of a {@code Lookup} produced by
 918      * any of the following factory or transformation methods:
 919      * <ul>
 920      * <li>{@link #lookup() MethodHandles::lookup}</li>
 921      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 922      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 923      * <li>{@link Lookup#in Lookup::in}</li>
 924      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 925      * </ul>
 926      *
 927      * <table class="striped">
 928      * <caption style="display:none">
 929      * Access mode summary
 930      * </caption>
 931      * <thead>
 932      * <tr>
 933      * <th scope="col">Lookup object</th>
 934      * <th style="text-align:center">original</th>
 935      * <th style="text-align:center">protected</th>
 936      * <th style="text-align:center">private</th>
 937      * <th style="text-align:center">package</th>
 938      * <th style="text-align:center">module</th>
 939      * <th style="text-align:center">public</th>
 940      * </tr>
 941      * </thead>
 942      * <tbody>
 943      * <tr>
 944      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 945      * <td style="text-align:center">ORI</td>
 946      * <td style="text-align:center">PRO</td>
 947      * <td style="text-align:center">PRI</td>
 948      * <td style="text-align:center">PAC</td>
 949      * <td style="text-align:center">MOD</td>
 950      * <td style="text-align:center">1R</td>
 951      * </tr>
 952      * <tr>
 953      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 954      * <td></td>
 955      * <td></td>
 956      * <td></td>
 957      * <td style="text-align:center">PAC</td>
 958      * <td style="text-align:center">MOD</td>
 959      * <td style="text-align:center">1R</td>
 960      * </tr>
 961      * <tr>
 962      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 963      * <td></td>
 964      * <td></td>
 965      * <td></td>
 966      * <td></td>
 967      * <td style="text-align:center">MOD</td>
 968      * <td style="text-align:center">1R</td>
 969      * </tr>
 970      * <tr>
 971      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 972      * <td></td>
 973      * <td></td>
 974      * <td></td>
 975      * <td></td>
 976      * <td></td>
 977      * <td style="text-align:center">2R</td>
 978      * </tr>
 979      * <tr>
 980      * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th>
 981      * <td></td>
 982      * <td></td>
 983      * <td></td>
 984      * <td></td>
 985      * <td></td>
 986      * <td style="text-align:center">2R</td>
 987      * </tr>
 988      * <tr>
 989      * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th>
 990      * <td></td>
 991      * <td style="text-align:center">PRO</td>
 992      * <td style="text-align:center">PRI</td>
 993      * <td style="text-align:center">PAC</td>
 994      * <td style="text-align:center">MOD</td>
 995      * <td style="text-align:center">1R</td>
 996      * </tr>
 997      * <tr>
 998      * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th>
 999      * <td></td>
1000      * <td style="text-align:center">PRO</td>
1001      * <td style="text-align:center">PRI</td>
1002      * <td style="text-align:center">PAC</td>
1003      * <td style="text-align:center">MOD</td>
1004      * <td style="text-align:center">1R</td>
1005      * </tr>
1006      * <tr>
1007      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th>
1008      * <td></td>
1009      * <td></td>
1010      * <td></td>
1011      * <td style="text-align:center">PAC</td>
1012      * <td style="text-align:center">MOD</td>
1013      * <td style="text-align:center">1R</td>
1014      * </tr>
1015      * <tr>
1016      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th>
1017      * <td></td>
1018      * <td></td>
1019      * <td></td>
1020      * <td></td>
1021      * <td style="text-align:center">MOD</td>
1022      * <td style="text-align:center">1R</td>
1023      * </tr>
1024      * <tr>
1025      * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th>
1026      * <td></td>
1027      * <td></td>
1028      * <td></td>
1029      * <td></td>
1030      * <td></td>
1031      * <td style="text-align:center">2R</td>
1032      * </tr>
1033      * <tr>
1034      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th>
1035      * <td></td>
1036      * <td></td>
1037      * <td style="text-align:center">PRI</td>
1038      * <td style="text-align:center">PAC</td>
1039      * <td style="text-align:center">MOD</td>
1040      * <td style="text-align:center">1R</td>
1041      * </tr>
1042      * <tr>
1043      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th>
1044      * <td></td>
1045      * <td></td>
1046      * <td></td>
1047      * <td style="text-align:center">PAC</td>
1048      * <td style="text-align:center">MOD</td>
1049      * <td style="text-align:center">1R</td>
1050      * </tr>
1051      * <tr>
1052      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th>
1053      * <td></td>
1054      * <td></td>
1055      * <td></td>
1056      * <td></td>
1057      * <td style="text-align:center">MOD</td>
1058      * <td style="text-align:center">1R</td>
1059      * </tr>
1060      * <tr>
1061      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th>
1062      * <td></td>
1063      * <td></td>
1064      * <td></td>
1065      * <td></td>
1066      * <td></td>
1067      * <td style="text-align:center">1R</td>
1068      * </tr>
1069      * <tr>
1070      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th>
1071      * <td></td>
1072      * <td></td>
1073      * <td></td>
1074      * <td></td>
1075      * <td></td>
1076      * <td style="text-align:center">none</td>
1077      * <tr>
1078      * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th>
1079      * <td></td>
1080      * <td style="text-align:center">PRO</td>
1081      * <td style="text-align:center">PRI</td>
1082      * <td style="text-align:center">PAC</td>
1083      * <td></td>
1084      * <td style="text-align:center">2R</td>
1085      * </tr>
1086      * <tr>
1087      * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th>
1088      * <td></td>
1089      * <td style="text-align:center">PRO</td>
1090      * <td style="text-align:center">PRI</td>
1091      * <td style="text-align:center">PAC</td>
1092      * <td></td>
1093      * <td style="text-align:center">2R</td>
1094      * </tr>
1095      * <tr>
1096      * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th>
1097      * <td></td>
1098      * <td></td>
1099      * <td></td>
1100      * <td></td>
1101      * <td></td>
1102      * <td style="text-align:center">IAE</td>
1103      * </tr>
1104      * <tr>
1105      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th>
1106      * <td></td>
1107      * <td></td>
1108      * <td></td>
1109      * <td style="text-align:center">PAC</td>
1110      * <td></td>
1111      * <td style="text-align:center">2R</td>
1112      * </tr>
1113      * <tr>
1114      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th>
1115      * <td></td>
1116      * <td></td>
1117      * <td></td>
1118      * <td></td>
1119      * <td></td>
1120      * <td style="text-align:center">2R</td>
1121      * </tr>
1122      * <tr>
1123      * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th>
1124      * <td></td>
1125      * <td></td>
1126      * <td></td>
1127      * <td></td>
1128      * <td></td>
1129      * <td style="text-align:center">2R</td>
1130      * </tr>
1131      * <tr>
1132      * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th>
1133      * <td></td>
1134      * <td></td>
1135      * <td></td>
1136      * <td></td>
1137      * <td></td>
1138      * <td style="text-align:center">none</td>
1139      * </tr>
1140      * <tr>
1141      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th>
1142      * <td></td>
1143      * <td></td>
1144      * <td style="text-align:center">PRI</td>
1145      * <td style="text-align:center">PAC</td>
1146      * <td></td>
1147      * <td style="text-align:center">2R</td>
1148      * </tr>
1149      * <tr>
1150      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th>
1151      * <td></td>
1152      * <td></td>
1153      * <td></td>
1154      * <td style="text-align:center">PAC</td>
1155      * <td></td>
1156      * <td style="text-align:center">2R</td>
1157      * </tr>
1158      * <tr>
1159      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th>
1160      * <td></td>
1161      * <td></td>
1162      * <td></td>
1163      * <td></td>
1164      * <td></td>
1165      * <td style="text-align:center">2R</td>
1166      * </tr>
1167      * <tr>
1168      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th>
1169      * <td></td>
1170      * <td></td>
1171      * <td></td>
1172      * <td></td>
1173      * <td></td>
1174      * <td style="text-align:center">2R</td>
1175      * </tr>
1176      * <tr>
1177      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th>
1178      * <td></td>
1179      * <td></td>
1180      * <td></td>
1181      * <td></td>
1182      * <td></td>
1183      * <td style="text-align:center">none</td>
1184      * </tr>
1185      * <tr>
1186      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th>
1187      * <td></td>
1188      * <td></td>
1189      * <td style="text-align:center">PRI</td>
1190      * <td style="text-align:center">PAC</td>
1191      * <td style="text-align:center">MOD</td>
1192      * <td style="text-align:center">1R</td>
1193      * </tr>
1194      * <tr>
1195      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th>
1196      * <td></td>
1197      * <td></td>
1198      * <td></td>
1199      * <td style="text-align:center">PAC</td>
1200      * <td style="text-align:center">MOD</td>
1201      * <td style="text-align:center">1R</td>
1202      * </tr>
1203      * <tr>
1204      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th>
1205      * <td></td>
1206      * <td></td>
1207      * <td></td>
1208      * <td></td>
1209      * <td style="text-align:center">MOD</td>
1210      * <td style="text-align:center">1R</td>
1211      * </tr>
1212      * <tr>
1213      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th>
1214      * <td></td>
1215      * <td></td>
1216      * <td></td>
1217      * <td></td>
1218      * <td></td>
1219      * <td style="text-align:center">1R</td>
1220      * </tr>
1221      * <tr>
1222      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th>
1223      * <td></td>
1224      * <td></td>
1225      * <td></td>
1226      * <td></td>
1227      * <td></td>
1228      * <td style="text-align:center">none</td>
1229      * </tr>
1230      * <tr>
1231      * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th>
1232      * <td></td>
1233      * <td></td>
1234      * <td></td>
1235      * <td></td>
1236      * <td></td>
1237      * <td style="text-align:center">U</td>
1238      * </tr>
1239      * <tr>
1240      * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th>
1241      * <td></td>
1242      * <td></td>
1243      * <td></td>
1244      * <td></td>
1245      * <td></td>
1246      * <td style="text-align:center">U</td>
1247      * </tr>
1248      * <tr>
1249      * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th>
1250      * <td></td>
1251      * <td></td>
1252      * <td></td>
1253      * <td></td>
1254      * <td></td>
1255      * <td style="text-align:center">U</td>
1256      * </tr>
1257      * <tr>
1258      * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th>
1259      * <td></td>
1260      * <td></td>
1261      * <td></td>
1262      * <td></td>
1263      * <td></td>
1264      * <td style="text-align:center">none</td>
1265      * </tr>
1266      * <tr>
1267      * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th>
1268      * <td></td>
1269      * <td></td>
1270      * <td></td>
1271      * <td></td>
1272      * <td></td>
1273      * <td style="text-align:center">IAE</td>
1274      * </tr>
1275      * <tr>
1276      * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th>
1277      * <td></td>
1278      * <td></td>
1279      * <td></td>
1280      * <td></td>
1281      * <td></td>
1282      * <td style="text-align:center">none</td>
1283      * </tr>
1284      * </tbody>
1285      * </table>
1286      *
1287      * <p>
1288      * Notes:
1289      * <ul>
1290      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1291      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1292      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1293      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1294      * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1295      *     {@code PRO} indicates {@link #PROTECTED} bit set,
1296      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1297      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1298      *     {@code MOD} indicates {@link #MODULE} bit set,
1299      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1300      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1301      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1302      * <li>Public access comes in three kinds:
1303      * <ul>
1304      * <li>unconditional ({@code U}): the lookup assumes readability.
1305      *     The lookup has {@code null} previous lookup class.
1306      * <li>one-module-reads ({@code 1R}): the module access checking is
1307      *     performed with respect to the lookup class.  The lookup has {@code null}
1308      *     previous lookup class.
1309      * <li>two-module-reads ({@code 2R}): the module access checking is
1310      *     performed with respect to the lookup class and the previous lookup class.
1311      *     The lookup has a non-null previous lookup class which is in a
1312      *     different module from the current lookup class.
1313      * </ul>
1314      * <li>Any attempt to reach a third module loses all access.</li>
1315      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1316      * all access modes are dropped.</li>
1317      * </ul>
1318      *
1319      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1320      * Although bytecode instructions can only refer to classes in
1321      * a related class loader, this API can search for methods in any
1322      * class, as long as a reference to its {@code Class} object is
1323      * available.  Such cross-loader references are also possible with the
1324      * Core Reflection API, and are impossible to bytecode instructions
1325      * such as {@code invokestatic} or {@code getfield}.
1326      * There is a {@linkplain java.lang.SecurityManager security manager API}
1327      * to allow applications to check such cross-loader references.
1328      * These checks apply to both the {@code MethodHandles.Lookup} API
1329      * and the Core Reflection API
1330      * (as found on {@link java.lang.Class Class}).
1331      * <p>
1332      * If a security manager is present, member and class lookups are subject to
1333      * additional checks.
1334      * From one to three calls are made to the security manager.
1335      * Any of these calls can refuse access by throwing a
1336      * {@link java.lang.SecurityException SecurityException}.
1337      * Define {@code smgr} as the security manager,
1338      * {@code lookc} as the lookup class of the current lookup object,
1339      * {@code refc} as the containing class in which the member
1340      * is being sought, and {@code defc} as the class in which the
1341      * member is actually defined.
1342      * (If a class or other type is being accessed,
1343      * the {@code refc} and {@code defc} values are the class itself.)
1344      * The value {@code lookc} is defined as <em>not present</em>
1345      * if the current lookup object does not have
1346      * {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1347      * The calls are made according to the following rules:
1348      * <ul>
1349      * <li><b>Step 1:</b>
1350      *     If {@code lookc} is not present, or if its class loader is not
1351      *     the same as or an ancestor of the class loader of {@code refc},
1352      *     then {@link SecurityManager#checkPackageAccess
1353      *     smgr.checkPackageAccess(refcPkg)} is called,
1354      *     where {@code refcPkg} is the package of {@code refc}.
1355      * <li><b>Step 2a:</b>
1356      *     If the retrieved member is not public and
1357      *     {@code lookc} is not present, then
1358      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1359      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
1360      * <li><b>Step 2b:</b>
1361      *     If the retrieved class has a {@code null} class loader,
1362      *     and {@code lookc} is not present, then
1363      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1364      *     with {@code RuntimePermission("getClassLoader")} is called.
1365      * <li><b>Step 3:</b>
1366      *     If the retrieved member is not public,
1367      *     and if {@code lookc} is not present,
1368      *     and if {@code defc} and {@code refc} are different,
1369      *     then {@link SecurityManager#checkPackageAccess
1370      *     smgr.checkPackageAccess(defcPkg)} is called,
1371      *     where {@code defcPkg} is the package of {@code defc}.
1372      * </ul>
1373      * Security checks are performed after other access checks have passed.
1374      * Therefore, the above rules presuppose a member or class that is public,
1375      * or else that is being accessed from a lookup class that has
1376      * rights to access the member or class.
1377      * <p>
1378      * If a security manager is present and the current lookup object does not have
1379      * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then
1380      * {@link #defineClass(byte[]) defineClass},
1381      * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass},
1382      * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...)
1383      * defineHiddenClassWithClassData}
1384      * calls {@link SecurityManager#checkPermission smgr.checkPermission}
1385      * with {@code RuntimePermission("defineClass")}.
1386      *
1387      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1388      * A small number of Java methods have a special property called caller sensitivity.
1389      * A <em>caller-sensitive</em> method can behave differently depending on the
1390      * identity of its immediate caller.
1391      * <p>
1392      * If a method handle for a caller-sensitive method is requested,
1393      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1394      * but they take account of the lookup class in a special way.
1395      * The resulting method handle behaves as if it were called
1396      * from an instruction contained in the lookup class,
1397      * so that the caller-sensitive method detects the lookup class.
1398      * (By contrast, the invoker of the method handle is disregarded.)
1399      * Thus, in the case of caller-sensitive methods,
1400      * different lookup classes may give rise to
1401      * differently behaving method handles.
1402      * <p>
1403      * In cases where the lookup object is
1404      * {@link MethodHandles#publicLookup() publicLookup()},
1405      * or some other lookup object without the
1406      * {@linkplain #ORIGINAL original access},
1407      * the lookup class is disregarded.
1408      * In such cases, no caller-sensitive method handle can be created,
1409      * access is forbidden, and the lookup fails with an
1410      * {@code IllegalAccessException}.
1411      * <p style="font-size:smaller;">
1412      * <em>Discussion:</em>
1413      * For example, the caller-sensitive method
1414      * {@link java.lang.Class#forName(String) Class.forName(x)}
1415      * can return varying classes or throw varying exceptions,
1416      * depending on the class loader of the class that calls it.
1417      * A public lookup of {@code Class.forName} will fail, because
1418      * there is no reasonable way to determine its bytecode behavior.
1419      * <p style="font-size:smaller;">
1420      * If an application caches method handles for broad sharing,
1421      * it should use {@code publicLookup()} to create them.
1422      * If there is a lookup of {@code Class.forName}, it will fail,
1423      * and the application must take appropriate action in that case.
1424      * It may be that a later lookup, perhaps during the invocation of a
1425      * bootstrap method, can incorporate the specific identity
1426      * of the caller, making the method accessible.
1427      * <p style="font-size:smaller;">
1428      * The function {@code MethodHandles.lookup} is caller sensitive
1429      * so that there can be a secure foundation for lookups.
1430      * Nearly all other methods in the JSR 292 API rely on lookup
1431      * objects to check access requests.
1432      */
1433     public static final
1434     class Lookup {
1435         /** The class on behalf of whom the lookup is being performed. */
1436         private final Class<?> lookupClass;
1437 
1438         /** previous lookup class */
1439         private final Class<?> prevLookupClass;
1440 
1441         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1442         private final int allowedModes;
1443 
1444         static {
1445             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1446         }
1447 
1448         /** A single-bit mask representing {@code public} access,
1449          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1450          *  The value, {@code 0x01}, happens to be the same as the value of the
1451          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1452          *  <p>
1453          *  A {@code Lookup} with this lookup mode performs cross-module access check
1454          *  with respect to the {@linkplain #lookupClass() lookup class} and
1455          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1456          */
1457         public static final int PUBLIC = Modifier.PUBLIC;
1458 
1459         /** A single-bit mask representing {@code private} access,
1460          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1461          *  The value, {@code 0x02}, happens to be the same as the value of the
1462          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1463          */
1464         public static final int PRIVATE = Modifier.PRIVATE;
1465 
1466         /** A single-bit mask representing {@code protected} access,
1467          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1468          *  The value, {@code 0x04}, happens to be the same as the value of the
1469          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1470          */
1471         public static final int PROTECTED = Modifier.PROTECTED;
1472 
1473         /** A single-bit mask representing {@code package} access (default access),
1474          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1475          *  The value is {@code 0x08}, which does not correspond meaningfully to
1476          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1477          */
1478         public static final int PACKAGE = Modifier.STATIC;
1479 
1480         /** A single-bit mask representing {@code module} access,
1481          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1482          *  The value is {@code 0x10}, which does not correspond meaningfully to
1483          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1484          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1485          *  with this lookup mode can access all public types in the module of the
1486          *  lookup class and public types in packages exported by other modules
1487          *  to the module of the lookup class.
1488          *  <p>
1489          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1490          *  previous lookup class} is always {@code null}.
1491          *
1492          *  @since 9
1493          */
1494         public static final int MODULE = PACKAGE << 1;
1495 
1496         /** A single-bit mask representing {@code unconditional} access
1497          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1498          *  The value is {@code 0x20}, which does not correspond meaningfully to
1499          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1500          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1501          *  java.lang.Module#canRead(java.lang.Module) readability}.
1502          *  This lookup mode can access all public members of public types
1503          *  of all modules when the type is in a package that is {@link
1504          *  java.lang.Module#isExported(String) exported unconditionally}.
1505          *
1506          *  <p>
1507          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1508          *  previous lookup class} is always {@code null}.
1509          *
1510          *  @since 9
1511          *  @see #publicLookup()
1512          */
1513         public static final int UNCONDITIONAL = PACKAGE << 2;
1514 
1515         /** A single-bit mask representing {@code original} access
1516          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1517          *  The value is {@code 0x40}, which does not correspond meaningfully to
1518          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1519          *
1520          *  <p>
1521          *  If this lookup mode is set, the {@code Lookup} object must be
1522          *  created by the original lookup class by calling
1523          *  {@link MethodHandles#lookup()} method or by a bootstrap method
1524          *  invoked by the VM.  The {@code Lookup} object with this lookup
1525          *  mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1526          *
1527          *  @since 16
1528          */
1529         public static final int ORIGINAL = PACKAGE << 3;
1530 
1531         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1532         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);   // with original access
1533         private static final int TRUSTED   = -1;
1534 
1535         /*
1536          * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1537          * Adjust 0 => PACKAGE
1538          */
1539         private static int fixmods(int mods) {
1540             mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1541             if (Modifier.isPublic(mods))
1542                 mods |= UNCONDITIONAL;
1543             return (mods != 0) ? mods : PACKAGE;
1544         }
1545 
1546         /** Tells which class is performing the lookup.  It is this class against
1547          *  which checks are performed for visibility and access permissions.
1548          *  <p>
1549          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1550          *  access checks are performed against both the lookup class and the previous lookup class.
1551          *  <p>
1552          *  The class implies a maximum level of access permission,
1553          *  but the permissions may be additionally limited by the bitmask
1554          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1555          *  can be accessed.
1556          *  @return the lookup class, on behalf of which this lookup object finds members
1557          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1558          */
1559         public Class<?> lookupClass() {
1560             return lookupClass;
1561         }
1562 
1563         /** Reports a lookup class in another module that this lookup object
1564          * was previously teleported from, or {@code null}.
1565          * <p>
1566          * A {@code Lookup} object produced by the factory methods, such as the
1567          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1568          * has {@code null} previous lookup class.
1569          * A {@code Lookup} object has a non-null previous lookup class
1570          * when this lookup was teleported from an old lookup class
1571          * in one module to a new lookup class in another module.
1572          *
1573          * @return the lookup class in another module that this lookup object was
1574          *         previously teleported from, or {@code null}
1575          * @since 14
1576          * @see #in(Class)
1577          * @see MethodHandles#privateLookupIn(Class, Lookup)
1578          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1579          */
1580         public Class<?> previousLookupClass() {
1581             return prevLookupClass;
1582         }
1583 
1584         // This is just for calling out to MethodHandleImpl.
1585         private Class<?> lookupClassOrNull() {
1586             return (allowedModes == TRUSTED) ? null : lookupClass;
1587         }
1588 
1589         /** Tells which access-protection classes of members this lookup object can produce.
1590          *  The result is a bit-mask of the bits
1591          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1592          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1593          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1594          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1595          *  {@linkplain #MODULE MODULE (0x10)},
1596          *  {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1597          *  and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1598          *  <p>
1599          *  A freshly-created lookup object
1600          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1601          *  all possible bits set, except {@code UNCONDITIONAL}.
1602          *  A lookup object on a new lookup class
1603          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1604          *  may have some mode bits set to zero.
1605          *  Mode bits can also be
1606          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1607          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1608          *  The purpose of this is to restrict access via the new lookup object,
1609          *  so that it can access only names which can be reached by the original
1610          *  lookup object, and also by the new lookup class.
1611          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1612          *  @see #in
1613          *  @see #dropLookupMode
1614          */
1615         public int lookupModes() {
1616             return allowedModes & ALL_MODES;
1617         }
1618 
1619         /** Embody the current class (the lookupClass) as a lookup class
1620          * for method handle creation.
1621          * Must be called by from a method in this package,
1622          * which in turn is called by a method not in this package.
1623          */
1624         Lookup(Class<?> lookupClass) {
1625             this(lookupClass, null, FULL_POWER_MODES);
1626         }
1627 
1628         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1629             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1630                     && prevLookupClass.getModule() != lookupClass.getModule());
1631             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1632             this.lookupClass = lookupClass;
1633             this.prevLookupClass = prevLookupClass;
1634             this.allowedModes = allowedModes;
1635         }
1636 
1637         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1638             // make sure we haven't accidentally picked up a privileged class:
1639             checkUnprivilegedlookupClass(lookupClass);
1640             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1641         }
1642 
1643         /**
1644          * Creates a lookup on the specified new lookup class.
1645          * The resulting object will report the specified
1646          * class as its own {@link #lookupClass() lookupClass}.
1647          *
1648          * <p>
1649          * However, the resulting {@code Lookup} object is guaranteed
1650          * to have no more access capabilities than the original.
1651          * In particular, access capabilities can be lost as follows:<ul>
1652          * <li>If the new lookup class is different from the old lookup class,
1653          * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1654          * <li>If the new lookup class is in a different module from the old one,
1655          * i.e. {@link #MODULE MODULE} access is lost.
1656          * <li>If the new lookup class is in a different package
1657          * than the old one, protected and default (package) members will not be accessible,
1658          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1659          * <li>If the new lookup class is not within the same package member
1660          * as the old one, private members will not be accessible, and protected members
1661          * will not be accessible by virtue of inheritance,
1662          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1663          * (Protected members may continue to be accessible because of package sharing.)
1664          * <li>If the new lookup class is not
1665          * {@linkplain #accessClass(Class) accessible} to this lookup,
1666          * then no members, not even public members, will be accessible
1667          * i.e. all access modes are lost.
1668          * <li>If the new lookup class, the old lookup class and the previous lookup class
1669          * are all in different modules i.e. teleporting to a third module,
1670          * all access modes are lost.
1671          * </ul>
1672          * <p>
1673          * The new previous lookup class is chosen as follows:
1674          * <ul>
1675          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1676          * the new previous lookup class is {@code null}.
1677          * <li>If the new lookup class is in the same module as the old lookup class,
1678          * the new previous lookup class is the old previous lookup class.
1679          * <li>If the new lookup class is in a different module from the old lookup class,
1680          * the new previous lookup class is the old lookup class.
1681          *</ul>
1682          * <p>
1683          * The resulting lookup's capabilities for loading classes
1684          * (used during {@link #findClass} invocations)
1685          * are determined by the lookup class' loader,
1686          * which may change due to this operation.
1687          *
1688          * @param requestedLookupClass the desired lookup class for the new lookup object
1689          * @return a lookup object which reports the desired lookup class, or the same object
1690          * if there is no change
1691          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1692          * @throws NullPointerException if the argument is null
1693          *
1694          * @see #accessClass(Class)
1695          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1696          */
1697         public Lookup in(Class<?> requestedLookupClass) {
1698             Objects.requireNonNull(requestedLookupClass);
1699             if (requestedLookupClass.isPrimitive())
1700                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1701             if (requestedLookupClass.isArray())
1702                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1703 
1704             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1705                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1706             if (requestedLookupClass == this.lookupClass)
1707                 return this;  // keep same capabilities
1708             int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1709             Module fromModule = this.lookupClass.getModule();
1710             Module targetModule = requestedLookupClass.getModule();
1711             Class<?> plc = this.previousLookupClass();
1712             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1713                 assert plc == null;
1714                 newModes = UNCONDITIONAL;
1715             } else if (fromModule != targetModule) {
1716                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1717                     // allow hopping back and forth between fromModule and plc's module
1718                     // but not the third module
1719                     newModes = 0;
1720                 }
1721                 // drop MODULE access
1722                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1723                 // teleport from this lookup class
1724                 plc = this.lookupClass;
1725             }
1726             if ((newModes & PACKAGE) != 0
1727                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1728                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1729             }
1730             // Allow nestmate lookups to be created without special privilege:
1731             if ((newModes & PRIVATE) != 0
1732                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1733                 newModes &= ~(PRIVATE|PROTECTED);
1734             }
1735             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1736                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1737                 // The requested class it not accessible from the lookup class.
1738                 // No permissions.
1739                 newModes = 0;
1740             }
1741             return newLookup(requestedLookupClass, plc, newModes);
1742         }
1743 
1744         /**
1745          * Creates a lookup on the same lookup class which this lookup object
1746          * finds members, but with a lookup mode that has lost the given lookup mode.
1747          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1748          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1749          * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1750          * {@link #UNCONDITIONAL UNCONDITIONAL}.
1751          *
1752          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1753          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1754          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1755          * lookup has no access.
1756          *
1757          * <p> If this lookup is not a public lookup, then the following applies
1758          * regardless of its {@linkplain #lookupModes() lookup modes}.
1759          * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1760          * dropped and so the resulting lookup mode will never have these access
1761          * capabilities. When dropping {@code PACKAGE}
1762          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1763          * access. When dropping {@code MODULE} then the resulting lookup will not
1764          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1765          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1766          *
1767          * @apiNote
1768          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1769          * delegate non-public access within the package of the lookup class without
1770          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1771          * A lookup with {@code MODULE} but not
1772          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1773          * the module of the lookup class without conferring package access.
1774          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1775          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1776          * to public classes accessible to both the module of the lookup class
1777          * and the module of the previous lookup class.
1778          *
1779          * @param modeToDrop the lookup mode to drop
1780          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1781          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1782          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1783          * or {@code UNCONDITIONAL}
1784          * @see MethodHandles#privateLookupIn
1785          * @since 9
1786          */
1787         public Lookup dropLookupMode(int modeToDrop) {
1788             int oldModes = lookupModes();
1789             int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1790             switch (modeToDrop) {
1791                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1792                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1793                 case PACKAGE: newModes &= ~(PRIVATE); break;
1794                 case PROTECTED:
1795                 case PRIVATE:
1796                 case ORIGINAL:
1797                 case UNCONDITIONAL: break;
1798                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1799             }
1800             if (newModes == oldModes) return this;  // return self if no change
1801             return newLookup(lookupClass(), previousLookupClass(), newModes);
1802         }
1803 
1804         /**
1805          * Creates and links a class or interface from {@code bytes}
1806          * with the same class loader and in the same runtime package and
1807          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1808          * {@linkplain #lookupClass() lookup class} as if calling
1809          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1810          * ClassLoader::defineClass}.
1811          *
1812          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1813          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1814          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1815          * that the lookup object was created by a caller in the runtime package (or derived
1816          * from a lookup originally created by suitably privileged code to a target class in
1817          * the runtime package). </p>
1818          *
1819          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1820          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1821          * same package as the lookup class. </p>
1822          *
1823          * <p> This method does not run the class initializer. The class initializer may
1824          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1825          * Specification</em>. </p>
1826          *
1827          * <p> If there is a security manager and this lookup does not have {@linkplain
1828          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1829          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1830          *
1831          * @param bytes the class bytes
1832          * @return the {@code Class} object for the class
1833          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1834          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1835          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1836          * than the lookup class or {@code bytes} is not a class or interface
1837          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1838          * @throws VerifyError if the newly created class cannot be verified
1839          * @throws LinkageError if the newly created class cannot be linked for any other reason
1840          * @throws SecurityException if a security manager is present and it
1841          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1842          * @throws NullPointerException if {@code bytes} is {@code null}
1843          * @since 9
1844          * @see Lookup#privateLookupIn
1845          * @see Lookup#dropLookupMode
1846          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1847          */
1848         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1849             ensureDefineClassPermission();
1850             if ((lookupModes() & PACKAGE) == 0)
1851                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1852             return makeClassDefiner(bytes.clone()).defineClass(false);
1853         }
1854 
1855         private void ensureDefineClassPermission() {
1856             if (allowedModes == TRUSTED)  return;
1857 
1858             if (!hasFullPrivilegeAccess()) {
1859                 @SuppressWarnings("removal")
1860                 SecurityManager sm = System.getSecurityManager();
1861                 if (sm != null)
1862                     sm.checkPermission(new RuntimePermission("defineClass"));
1863             }
1864         }
1865 
1866         /**
1867          * The set of class options that specify whether a hidden class created by
1868          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1869          * Lookup::defineHiddenClass} method is dynamically added as a new member
1870          * to the nest of a lookup class and/or whether a hidden class has
1871          * a strong relationship with the class loader marked as its defining loader.
1872          *
1873          * @since 15
1874          */
1875         public enum ClassOption {
1876             /**
1877              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1878              * of a lookup class as a nestmate.
1879              *
1880              * <p> A hidden nestmate class has access to the private members of all
1881              * classes and interfaces in the same nest.
1882              *
1883              * @see Class#getNestHost()
1884              */
1885             NESTMATE(NESTMATE_CLASS),
1886 
1887             /**
1888              * Specifies that a hidden class has a <em>strong</em>
1889              * relationship with the class loader marked as its defining loader,
1890              * as a normal class or interface has with its own defining loader.
1891              * This means that the hidden class may be unloaded if and only if
1892              * its defining loader is not reachable and thus may be reclaimed
1893              * by a garbage collector (JLS {@jls 12.7}).
1894              *
1895              * <p> By default, a hidden class or interface may be unloaded
1896              * even if the class loader that is marked as its defining loader is
1897              * <a href="../ref/package-summary.html#reachability">reachable</a>.
1898 
1899              *
1900              * @jls 12.7 Unloading of Classes and Interfaces
1901              */
1902             STRONG(STRONG_LOADER_LINK);
1903 
1904             /* the flag value is used by VM at define class time */
1905             private final int flag;
1906             ClassOption(int flag) {
1907                 this.flag = flag;
1908             }
1909 
1910             static int optionsToFlag(Set<ClassOption> options) {
1911                 int flags = 0;
1912                 for (ClassOption cp : options) {
1913                     flags |= cp.flag;
1914                 }
1915                 return flags;
1916             }
1917         }
1918 
1919         /**
1920          * Creates a <em>hidden</em> class or interface from {@code bytes},
1921          * returning a {@code Lookup} on the newly created class or interface.
1922          *
1923          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1924          * which either defines {@code C} directly or delegates to another class loader.
1925          * A class loader defines {@code C} directly by invoking
1926          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1927          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1928          * to derive {@code C} from a purported representation in {@code class} file format.
1929          * In situations where use of a class loader is undesirable, a class or interface
1930          * {@code C} can be created by this method instead. This method is capable of
1931          * defining {@code C}, and thereby creating it, without invoking
1932          * {@code ClassLoader::defineClass}.
1933          * Instead, this method defines {@code C} as if by arranging for
1934          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1935          * from a purported representation in {@code class} file format
1936          * using the following rules:
1937          *
1938          * <ol>
1939          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1940          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1941          * This level of access is needed to create {@code C} in the module
1942          * of the lookup class of this {@code Lookup}.</li>
1943          *
1944          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1945          * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1946          * The major and minor version may differ from the {@code class} file version
1947          * of the lookup class of this {@code Lookup}.</li>
1948          *
1949          * <li> The value of {@code this_class} must be a valid index in the
1950          * {@code constant_pool} table, and the entry at that index must be a valid
1951          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1952          * encoded in internal form that is specified by this structure. {@code N} must
1953          * denote a class or interface in the same package as the lookup class.</li>
1954          *
1955          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1956          * where {@code <suffix>} is an unqualified name.
1957          *
1958          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1959          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1960          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1961          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1962          * refers to the new {@code CONSTANT_Utf8_info} structure.
1963          *
1964          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1965          *
1966          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1967          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1968          * with the following adjustments:
1969          * <ul>
1970          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1971          * that includes a single {@code "."} character, even though this is not a valid
1972          * binary class or interface name in internal form.</li>
1973          *
1974          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1975          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1976          *
1977          * <li> {@code C} is considered to have the same runtime
1978          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1979          * and {@linkplain java.security.ProtectionDomain protection domain}
1980          * as the lookup class of this {@code Lookup}.
1981          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1982          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1983          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1984          * <ul>
1985          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1986          *      even though this is not a valid binary class or interface name.</li>
1987          * <li> {@link Class#descriptorString()} returns the string
1988          *      {@code "L" + N + "." + <suffix> + ";"},
1989          *      even though this is not a valid type descriptor name.</li>
1990          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
1991          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
1992          * </ul>
1993          * </ul>
1994          * </li>
1995          * </ol>
1996          *
1997          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1998          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
1999          * <ul>
2000          * <li> During verification, whenever it is necessary to load the class named
2001          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
2002          * made of any class loader.</li>
2003          *
2004          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
2005          * by {@code this_class}, the symbolic reference is considered to be resolved to
2006          * {@code C} and resolution always succeeds immediately.</li>
2007          * </ul>
2008          *
2009          * <p> If the {@code initialize} parameter is {@code true},
2010          * then {@code C} is initialized by the Java Virtual Machine.
2011          *
2012          * <p> The newly created class or interface {@code C} serves as the
2013          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
2014          * returned by this method. {@code C} is <em>hidden</em> in the sense that
2015          * no other class or interface can refer to {@code C} via a constant pool entry.
2016          * That is, a hidden class or interface cannot be named as a supertype, a field type,
2017          * a method parameter type, or a method return type by any other class.
2018          * This is because a hidden class or interface does not have a binary name, so
2019          * there is no internal form available to record in any class's constant pool.
2020          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
2021          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
2022          * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class)
2023          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
2024          * JVM Tool Interface</a>.
2025          *
2026          * <p> A class or interface created by
2027          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
2028          * a class loader} has a strong relationship with that class loader.
2029          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
2030          * that {@linkplain Class#getClassLoader() defined it}.
2031          * This means that a class created by a class loader may be unloaded if and
2032          * only if its defining loader is not reachable and thus may be reclaimed
2033          * by a garbage collector (JLS {@jls 12.7}).
2034          *
2035          * By default, however, a hidden class or interface may be unloaded even if
2036          * the class loader that is marked as its defining loader is
2037          * <a href="../ref/package-summary.html#reachability">reachable</a>.
2038          * This behavior is useful when a hidden class or interface serves multiple
2039          * classes defined by arbitrary class loaders.  In other cases, a hidden
2040          * class or interface may be linked to a single class (or a small number of classes)
2041          * with the same defining loader as the hidden class or interface.
2042          * In such cases, where the hidden class or interface must be coterminous
2043          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
2044          * option may be passed in {@code options}.
2045          * This arranges for a hidden class to have the same strong relationship
2046          * with the class loader marked as its defining loader,
2047          * as a normal class or interface has with its own defining loader.
2048          *
2049          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
2050          * may still prevent a hidden class or interface from being
2051          * unloaded by ensuring that the {@code Class} object is reachable.
2052          *
2053          * <p> The unloading characteristics are set for each hidden class when it is
2054          * defined, and cannot be changed later.  An advantage of allowing hidden classes
2055          * to be unloaded independently of the class loader marked as their defining loader
2056          * is that a very large number of hidden classes may be created by an application.
2057          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
2058          * just as if normal classes were created by class loaders.
2059          *
2060          * <p> Classes and interfaces in a nest are allowed to have mutual access to
2061          * their private members.  The nest relationship is determined by
2062          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
2063          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
2064          * By default, a hidden class belongs to a nest consisting only of itself
2065          * because a hidden class has no binary name.
2066          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
2067          * to create a hidden class or interface {@code C} as a member of a nest.
2068          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
2069          * in the {@code ClassFile} structure from which {@code C} was derived.
2070          * Instead, the following rules determine the nest host of {@code C}:
2071          * <ul>
2072          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
2073          *     been determined, then let {@code H} be the nest host of the lookup class.
2074          *     Otherwise, the nest host of the lookup class is determined using the
2075          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
2076          * <li>The nest host of {@code C} is determined to be {@code H},
2077          *     the nest host of the lookup class.</li>
2078          * </ul>
2079          *
2080          * <p> A hidden class or interface may be serializable, but this requires a custom
2081          * serialization mechanism in order to ensure that instances are properly serialized
2082          * and deserialized. The default serialization mechanism supports only classes and
2083          * interfaces that are discoverable by their class name.
2084          *
2085          * @param bytes the bytes that make up the class data,
2086          * in the format of a valid {@code class} file as defined by
2087          * <cite>The Java Virtual Machine Specification</cite>.
2088          * @param initialize if {@code true} the class will be initialized.
2089          * @param options {@linkplain ClassOption class options}
2090          * @return the {@code Lookup} object on the hidden class,
2091          * with {@linkplain #ORIGINAL original} and
2092          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2093          *
2094          * @throws IllegalAccessException if this {@code Lookup} does not have
2095          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2096          * @throws SecurityException if a security manager is present and it
2097          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2098          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2099          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2100          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2101          * than the lookup class or {@code bytes} is not a class or interface
2102          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2103          * @throws IncompatibleClassChangeError if the class or interface named as
2104          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2105          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2106          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2107          * {@code C} is {@code C} itself
2108          * @throws VerifyError if the newly created class cannot be verified
2109          * @throws LinkageError if the newly created class cannot be linked for any other reason
2110          * @throws NullPointerException if any parameter is {@code null}
2111          *
2112          * @since 15
2113          * @see Class#isHidden()
2114          * @jvms 4.2.1 Binary Class and Interface Names
2115          * @jvms 4.2.2 Unqualified Names
2116          * @jvms 4.7.28 The {@code NestHost} Attribute
2117          * @jvms 4.7.29 The {@code NestMembers} Attribute
2118          * @jvms 5.4.3.1 Class and Interface Resolution
2119          * @jvms 5.4.4 Access Control
2120          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2121          * @jvms 5.4 Linking
2122          * @jvms 5.5 Initialization
2123          * @jls 12.7 Unloading of Classes and Interfaces
2124          */
2125         @SuppressWarnings("doclint:reference") // cross-module links
2126         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2127                 throws IllegalAccessException
2128         {
2129             Objects.requireNonNull(bytes);
2130             Objects.requireNonNull(options);
2131 
2132             ensureDefineClassPermission();
2133             if (!hasFullPrivilegeAccess()) {
2134                 throw new IllegalAccessException(this + " does not have full privilege access");
2135             }
2136 
2137             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
2138         }
2139 
2140         /**
2141          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2142          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2143          * returning a {@code Lookup} on the newly created class or interface.
2144          *
2145          * <p> This method is equivalent to calling
2146          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2147          * as if the hidden class is injected with a private static final <i>unnamed</i>
2148          * field which is initialized with the given {@code classData} at
2149          * the first instruction of the class initializer.
2150          * The newly created class is linked by the Java Virtual Machine.
2151          *
2152          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2153          * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2154          * methods can be used to retrieve the {@code classData}.
2155          *
2156          * @apiNote
2157          * A framework can create a hidden class with class data with one or more
2158          * objects and load the class data as dynamically-computed constant(s)
2159          * via a bootstrap method.  {@link MethodHandles#classData(Lookup, String, Class)
2160          * Class data} is accessible only to the lookup object created by the newly
2161          * defined hidden class but inaccessible to other members in the same nest
2162          * (unlike private static fields that are accessible to nestmates).
2163          * Care should be taken w.r.t. mutability for example when passing
2164          * an array or other mutable structure through the class data.
2165          * Changing any value stored in the class data at runtime may lead to
2166          * unpredictable behavior.
2167          * If the class data is a {@code List}, it is good practice to make it
2168          * unmodifiable for example via {@link List#of List::of}.
2169          *
2170          * @param bytes     the class bytes
2171          * @param classData pre-initialized class data
2172          * @param initialize if {@code true} the class will be initialized.
2173          * @param options   {@linkplain ClassOption class options}
2174          * @return the {@code Lookup} object on the hidden class,
2175          * with {@linkplain #ORIGINAL original} and
2176          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2177          *
2178          * @throws IllegalAccessException if this {@code Lookup} does not have
2179          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2180          * @throws SecurityException if a security manager is present and it
2181          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2182          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2183          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2184          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2185          * than the lookup class or {@code bytes} is not a class or interface
2186          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2187          * @throws IncompatibleClassChangeError if the class or interface named as
2188          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2189          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2190          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2191          * {@code C} is {@code C} itself
2192          * @throws VerifyError if the newly created class cannot be verified
2193          * @throws LinkageError if the newly created class cannot be linked for any other reason
2194          * @throws NullPointerException if any parameter is {@code null}
2195          *
2196          * @since 16
2197          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2198          * @see Class#isHidden()
2199          * @see MethodHandles#classData(Lookup, String, Class)
2200          * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2201          * @jvms 4.2.1 Binary Class and Interface Names
2202          * @jvms 4.2.2 Unqualified Names
2203          * @jvms 4.7.28 The {@code NestHost} Attribute
2204          * @jvms 4.7.29 The {@code NestMembers} Attribute
2205          * @jvms 5.4.3.1 Class and Interface Resolution
2206          * @jvms 5.4.4 Access Control
2207          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2208          * @jvms 5.4 Linking
2209          * @jvms 5.5 Initialization
2210          * @jls 12.7 Unloading of Classes and Interface
2211          */
2212         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2213                 throws IllegalAccessException
2214         {
2215             Objects.requireNonNull(bytes);
2216             Objects.requireNonNull(classData);
2217             Objects.requireNonNull(options);
2218 
2219             ensureDefineClassPermission();
2220             if (!hasFullPrivilegeAccess()) {
2221                 throw new IllegalAccessException(this + " does not have full privilege access");
2222             }
2223 
2224             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2225                        .defineClassAsLookup(initialize, classData);
2226         }
2227 
2228         // A default dumper for writing class files passed to Lookup::defineClass
2229         // and Lookup::defineHiddenClass to disk for debugging purposes.  To enable,
2230         // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or
2231         //     -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true
2232         //
2233         // This default dumper does not dump hidden classes defined by LambdaMetafactory
2234         // and LambdaForms and method handle internals.  They are dumped via
2235         // different ClassFileDumpers.
2236         private static ClassFileDumper defaultDumper() {
2237             return DEFAULT_DUMPER;
2238         }
2239 
2240         private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance(
2241                 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES");
2242 
2243         static class ClassFile {
2244             final String name;  // internal name
2245             final int accessFlags;
2246             final byte[] bytes;
2247             ClassFile(String name, int accessFlags, byte[] bytes) {
2248                 this.name = name;
2249                 this.accessFlags = accessFlags;
2250                 this.bytes = bytes;
2251             }
2252 
2253             static ClassFile newInstanceNoCheck(String name, byte[] bytes) {
2254                 return new ClassFile(name, 0, bytes);
2255             }
2256 
2257             /**
2258              * This method checks the class file version and the structure of `this_class`.
2259              * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2260              * that is in the named package.
2261              *
2262              * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2263              * or the class is not in the given package name.
2264              */
2265             static ClassFile newInstance(byte[] bytes, String pkgName) {
2266                 var cf = readClassFile(bytes);
2267 
2268                 // check if it's in the named package
2269                 int index = cf.name.lastIndexOf('/');
2270                 String pn = (index == -1) ? "" : cf.name.substring(0, index).replace('/', '.');
2271                 if (!pn.equals(pkgName)) {
2272                     throw newIllegalArgumentException(cf.name + " not in same package as lookup class");
2273                 }
2274                 return cf;
2275             }
2276 
2277             private static ClassFile readClassFile(byte[] bytes) {
2278                 int magic = readInt(bytes, 0);
2279                 if (magic != 0xCAFEBABE) {
2280                     throw new ClassFormatError("Incompatible magic value: " + magic);
2281                 }
2282                 int minor = readUnsignedShort(bytes, 4);
2283                 int major = readUnsignedShort(bytes, 6);
2284                 if (!VM.isSupportedClassFileVersion(major, minor)) {
2285                     throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2286                 }
2287 
2288                 String name;
2289                 int accessFlags;
2290                 try {
2291                     ClassReader reader = new ClassReader(bytes);
2292                     // ClassReader does not check if `this_class` is CONSTANT_Class_info
2293                     // workaround to read `this_class` using readConst and validate the value
2294                     int thisClass = reader.readUnsignedShort(reader.header + 2);
2295                     Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]);
2296                     if (!(constant instanceof Type type)) {
2297                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2298                     }
2299                     if (!type.getDescriptor().startsWith("L")) {
2300                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2301                     }
2302                     name = type.getInternalName();
2303                     accessFlags = reader.readUnsignedShort(reader.header);
2304                 } catch (RuntimeException e) {
2305                     // ASM exceptions are poorly specified
2306                     ClassFormatError cfe = new ClassFormatError();
2307                     cfe.initCause(e);
2308                     throw cfe;
2309                 }
2310                 // must be a class or interface
2311                 if ((accessFlags & Opcodes.ACC_MODULE) != 0) {
2312                     throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2313                 }
2314                 return new ClassFile(name, accessFlags, bytes);
2315             }
2316 
2317             private static int readInt(byte[] bytes, int offset) {
2318                 if ((offset+4) > bytes.length) {
2319                     throw new ClassFormatError("Invalid ClassFile structure");
2320                 }
2321                 return ((bytes[offset] & 0xFF) << 24)
2322                         | ((bytes[offset + 1] & 0xFF) << 16)
2323                         | ((bytes[offset + 2] & 0xFF) << 8)
2324                         | (bytes[offset + 3] & 0xFF);
2325             }
2326 
2327             private static int readUnsignedShort(byte[] bytes, int offset) {
2328                 if ((offset+2) > bytes.length) {
2329                     throw new ClassFormatError("Invalid ClassFile structure");
2330                 }
2331                 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2332             }
2333         }
2334 
2335         /*
2336          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2337          * from the given bytes.
2338          *
2339          * Caller should make a defensive copy of the arguments if needed
2340          * before calling this factory method.
2341          *
2342          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2343          * {@code bytes} denotes a class in a different package than the lookup class
2344          */
2345         private ClassDefiner makeClassDefiner(byte[] bytes) {
2346             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2347             return new ClassDefiner(this, cf, STRONG_LOADER_LINK, defaultDumper());
2348         }
2349 
2350         /**
2351          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2352          * from the given bytes.  No package name check on the given bytes.
2353          *
2354          * @param name    internal name
2355          * @param bytes   class bytes
2356          * @param dumper  dumper to write the given bytes to the dumper's output directory
2357          * @return ClassDefiner that defines a normal class of the given bytes.
2358          */
2359         ClassDefiner makeClassDefiner(String name, byte[] bytes, ClassFileDumper dumper) {
2360             // skip package name validation
2361             ClassFile cf = ClassFile.newInstanceNoCheck(name, bytes);
2362             return new ClassDefiner(this, cf, STRONG_LOADER_LINK, dumper);
2363         }
2364 
2365         /**
2366          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2367          * from the given bytes.  The name must be in the same package as the lookup class.
2368          *
2369          * Caller should make a defensive copy of the arguments if needed
2370          * before calling this factory method.
2371          *
2372          * @param bytes   class bytes
2373          * @param dumper dumper to write the given bytes to the dumper's output directory
2374          * @return ClassDefiner that defines a hidden class of the given bytes.
2375          *
2376          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2377          * {@code bytes} denotes a class in a different package than the lookup class
2378          */
2379         ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) {
2380             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2381             return makeHiddenClassDefiner(cf, Set.of(), false, dumper);
2382         }
2383 
2384         /**
2385          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2386          * from the given bytes and options.
2387          * The name must be in the same package as the lookup class.
2388          *
2389          * Caller should make a defensive copy of the arguments if needed
2390          * before calling this factory method.
2391          *
2392          * @param bytes   class bytes
2393          * @param options class options
2394          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2395          * @return ClassDefiner that defines a hidden class of the given bytes and options
2396          *
2397          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2398          * {@code bytes} denotes a class in a different package than the lookup class
2399          */
2400         private ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2401                                                     Set<ClassOption> options,
2402                                                     boolean accessVmAnnotations) {
2403             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2404             return makeHiddenClassDefiner(cf, options, accessVmAnnotations, defaultDumper());
2405         }
2406 
2407         /**
2408          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2409          * from the given bytes and the given options.  No package name check on the given bytes.
2410          *
2411          * @param name    internal name that specifies the prefix of the hidden class
2412          * @param bytes   class bytes
2413          * @param options class options
2414          * @param dumper  dumper to write the given bytes to the dumper's output directory
2415          * @return ClassDefiner that defines a hidden class of the given bytes and options.
2416          */
2417         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options, ClassFileDumper dumper) {
2418             Objects.requireNonNull(dumper);
2419             // skip name and access flags validation
2420             return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false, dumper);
2421         }
2422 
2423         /**
2424          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2425          * from the given class file and options.
2426          *
2427          * @param cf ClassFile
2428          * @param options class options
2429          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2430          * @param dumper dumper to write the given bytes to the dumper's output directory
2431          */
2432         private ClassDefiner makeHiddenClassDefiner(ClassFile cf,
2433                                                     Set<ClassOption> options,
2434                                                     boolean accessVmAnnotations,
2435                                                     ClassFileDumper dumper) {
2436             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2437             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2438                 // jdk.internal.vm.annotations are permitted for classes
2439                 // defined to boot loader and platform loader
2440                 flags |= ACCESS_VM_ANNOTATIONS;
2441             }
2442 
2443             return new ClassDefiner(this, cf, flags, dumper);
2444         }
2445 
2446         static class ClassDefiner {
2447             private final Lookup lookup;
2448             private final String name;  // internal name
2449             private final byte[] bytes;
2450             private final int classFlags;
2451             private final ClassFileDumper dumper;
2452 
2453             private ClassDefiner(Lookup lookup, ClassFile cf, int flags, ClassFileDumper dumper) {
2454                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2455                 this.lookup = lookup;
2456                 this.bytes = cf.bytes;
2457                 this.name = cf.name;
2458                 this.classFlags = flags;
2459                 this.dumper = dumper;
2460             }
2461 
2462             String internalName() {
2463                 return name;
2464             }
2465 
2466             Class<?> defineClass(boolean initialize) {
2467                 return defineClass(initialize, null);
2468             }
2469 
2470             Lookup defineClassAsLookup(boolean initialize) {
2471                 Class<?> c = defineClass(initialize, null);
2472                 return new Lookup(c, null, FULL_POWER_MODES);
2473             }
2474 
2475             /**
2476              * Defines the class of the given bytes and the given classData.
2477              * If {@code initialize} parameter is true, then the class will be initialized.
2478              *
2479              * @param initialize true if the class to be initialized
2480              * @param classData classData or null
2481              * @return the class
2482              *
2483              * @throws LinkageError linkage error
2484              */
2485             Class<?> defineClass(boolean initialize, Object classData) {
2486                 Class<?> lookupClass = lookup.lookupClass();
2487                 ClassLoader loader = lookupClass.getClassLoader();
2488                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2489                 Class<?> c = null;
2490                 try {
2491                     c = SharedSecrets.getJavaLangAccess()
2492                             .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2493                     assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2494                     return c;
2495                 } finally {
2496                     // dump the classfile for debugging
2497                     if (dumper.isEnabled()) {
2498                         String name = internalName();
2499                         if (c != null) {
2500                             dumper.dumpClass(name, c, bytes);
2501                         } else {
2502                             dumper.dumpFailedClass(name, bytes);
2503                         }
2504                     }
2505                 }
2506             }
2507 
2508             /**
2509              * Defines the class of the given bytes and the given classData.
2510              * If {@code initialize} parameter is true, then the class will be initialized.
2511              *
2512              * @param initialize true if the class to be initialized
2513              * @param classData classData or null
2514              * @return a Lookup for the defined class
2515              *
2516              * @throws LinkageError linkage error
2517              */
2518             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2519                 Class<?> c = defineClass(initialize, classData);
2520                 return new Lookup(c, null, FULL_POWER_MODES);
2521             }
2522 
2523             private boolean isNestmate() {
2524                 return (classFlags & NESTMATE_CLASS) != 0;
2525             }
2526         }
2527 
2528         private ProtectionDomain lookupClassProtectionDomain() {
2529             ProtectionDomain pd = cachedProtectionDomain;
2530             if (pd == null) {
2531                 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2532             }
2533             return pd;
2534         }
2535 
2536         // cached protection domain
2537         private volatile ProtectionDomain cachedProtectionDomain;
2538 
2539         // Make sure outer class is initialized first.
2540         static { IMPL_NAMES.getClass(); }
2541 
2542         /** Package-private version of lookup which is trusted. */
2543         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2544 
2545         /** Version of lookup which is trusted minimally.
2546          *  It can only be used to create method handles to publicly accessible
2547          *  members in packages that are exported unconditionally.
2548          */
2549         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2550 
2551         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2552             String name = lookupClass.getName();
2553             if (name.startsWith("java.lang.invoke."))
2554                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2555         }
2556 
2557         /**
2558          * Displays the name of the class from which lookups are to be made,
2559          * followed by "/" and the name of the {@linkplain #previousLookupClass()
2560          * previous lookup class} if present.
2561          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2562          * If there are restrictions on the access permitted to this lookup,
2563          * this is indicated by adding a suffix to the class name, consisting
2564          * of a slash and a keyword.  The keyword represents the strongest
2565          * allowed access, and is chosen as follows:
2566          * <ul>
2567          * <li>If no access is allowed, the suffix is "/noaccess".
2568          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2569          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2570          * <li>If only public and module access are allowed, the suffix is "/module".
2571          * <li>If public and package access are allowed, the suffix is "/package".
2572          * <li>If public, package, and private access are allowed, the suffix is "/private".
2573          * </ul>
2574          * If none of the above cases apply, it is the case that
2575          * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2576          * (public, module, package, private, and protected) is allowed.
2577          * In this case, no suffix is added.
2578          * This is true only of an object obtained originally from
2579          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2580          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2581          * always have restricted access, and will display a suffix.
2582          * <p>
2583          * (It may seem strange that protected access should be
2584          * stronger than private access.  Viewed independently from
2585          * package access, protected access is the first to be lost,
2586          * because it requires a direct subclass relationship between
2587          * caller and callee.)
2588          * @see #in
2589          */
2590         @Override
2591         public String toString() {
2592             String cname = lookupClass.getName();
2593             if (prevLookupClass != null)
2594                 cname += "/" + prevLookupClass.getName();
2595             switch (allowedModes) {
2596             case 0:  // no privileges
2597                 return cname + "/noaccess";
2598             case UNCONDITIONAL:
2599                 return cname + "/publicLookup";
2600             case PUBLIC:
2601                 return cname + "/public";
2602             case PUBLIC|MODULE:
2603                 return cname + "/module";
2604             case PUBLIC|PACKAGE:
2605             case PUBLIC|MODULE|PACKAGE:
2606                 return cname + "/package";
2607             case PUBLIC|PACKAGE|PRIVATE:
2608             case PUBLIC|MODULE|PACKAGE|PRIVATE:
2609                     return cname + "/private";
2610             case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2611             case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2612             case FULL_POWER_MODES:
2613                     return cname;
2614             case TRUSTED:
2615                 return "/trusted";  // internal only; not exported
2616             default:  // Should not happen, but it's a bitfield...
2617                 cname = cname + "/" + Integer.toHexString(allowedModes);
2618                 assert(false) : cname;
2619                 return cname;
2620             }
2621         }
2622 
2623         /**
2624          * Produces a method handle for a static method.
2625          * The type of the method handle will be that of the method.
2626          * (Since static methods do not take receivers, there is no
2627          * additional receiver argument inserted into the method handle type,
2628          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2629          * The method and all its argument types must be accessible to the lookup object.
2630          * <p>
2631          * The returned method handle will have
2632          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2633          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2634          * <p>
2635          * If the returned method handle is invoked, the method's class will
2636          * be initialized, if it has not already been initialized.
2637          * <p><b>Example:</b>
2638          * {@snippet lang="java" :
2639 import static java.lang.invoke.MethodHandles.*;
2640 import static java.lang.invoke.MethodType.*;
2641 ...
2642 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2643   "asList", methodType(List.class, Object[].class));
2644 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2645          * }
2646          * @param refc the class from which the method is accessed
2647          * @param name the name of the method
2648          * @param type the type of the method
2649          * @return the desired method handle
2650          * @throws NoSuchMethodException if the method does not exist
2651          * @throws IllegalAccessException if access checking fails,
2652          *                                or if the method is not {@code static},
2653          *                                or if the method's variable arity modifier bit
2654          *                                is set and {@code asVarargsCollector} fails
2655          * @throws    SecurityException if a security manager is present and it
2656          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2657          * @throws NullPointerException if any argument is null
2658          */
2659         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2660             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2661             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2662         }
2663 
2664         /**
2665          * Produces a method handle for a virtual method.
2666          * The type of the method handle will be that of the method,
2667          * with the receiver type (usually {@code refc}) prepended.
2668          * The method and all its argument types must be accessible to the lookup object.
2669          * <p>
2670          * When called, the handle will treat the first argument as a receiver
2671          * and, for non-private methods, dispatch on the receiver's type to determine which method
2672          * implementation to enter.
2673          * For private methods the named method in {@code refc} will be invoked on the receiver.
2674          * (The dispatching action is identical with that performed by an
2675          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2676          * <p>
2677          * The first argument will be of type {@code refc} if the lookup
2678          * class has full privileges to access the member.  Otherwise
2679          * the member must be {@code protected} and the first argument
2680          * will be restricted in type to the lookup class.
2681          * <p>
2682          * The returned method handle will have
2683          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2684          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2685          * <p>
2686          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2687          * instructions and method handles produced by {@code findVirtual},
2688          * if the class is {@code MethodHandle} and the name string is
2689          * {@code invokeExact} or {@code invoke}, the resulting
2690          * method handle is equivalent to one produced by
2691          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2692          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2693          * with the same {@code type} argument.
2694          * <p>
2695          * If the class is {@code VarHandle} and the name string corresponds to
2696          * the name of a signature-polymorphic access mode method, the resulting
2697          * method handle is equivalent to one produced by
2698          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2699          * the access mode corresponding to the name string and with the same
2700          * {@code type} arguments.
2701          * <p>
2702          * <b>Example:</b>
2703          * {@snippet lang="java" :
2704 import static java.lang.invoke.MethodHandles.*;
2705 import static java.lang.invoke.MethodType.*;
2706 ...
2707 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2708   "concat", methodType(String.class, String.class));
2709 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2710   "hashCode", methodType(int.class));
2711 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2712   "hashCode", methodType(int.class));
2713 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2714 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2715 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2716 // interface method:
2717 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2718   "subSequence", methodType(CharSequence.class, int.class, int.class));
2719 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2720 // constructor "internal method" must be accessed differently:
2721 MethodType MT_newString = methodType(void.class); //()V for new String()
2722 try { assertEquals("impossible", lookup()
2723         .findVirtual(String.class, "<init>", MT_newString));
2724  } catch (NoSuchMethodException ex) { } // OK
2725 MethodHandle MH_newString = publicLookup()
2726   .findConstructor(String.class, MT_newString);
2727 assertEquals("", (String) MH_newString.invokeExact());
2728          * }
2729          *
2730          * @param refc the class or interface from which the method is accessed
2731          * @param name the name of the method
2732          * @param type the type of the method, with the receiver argument omitted
2733          * @return the desired method handle
2734          * @throws NoSuchMethodException if the method does not exist
2735          * @throws IllegalAccessException if access checking fails,
2736          *                                or if the method is {@code static},
2737          *                                or if the method's variable arity modifier bit
2738          *                                is set and {@code asVarargsCollector} fails
2739          * @throws    SecurityException if a security manager is present and it
2740          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2741          * @throws NullPointerException if any argument is null
2742          */
2743         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2744             if (refc == MethodHandle.class) {
2745                 MethodHandle mh = findVirtualForMH(name, type);
2746                 if (mh != null)  return mh;
2747             } else if (refc == VarHandle.class) {
2748                 MethodHandle mh = findVirtualForVH(name, type);
2749                 if (mh != null)  return mh;
2750             }
2751             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2752             MemberName method = resolveOrFail(refKind, refc, name, type);
2753             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2754         }
2755         private MethodHandle findVirtualForMH(String name, MethodType type) {
2756             // these names require special lookups because of the implicit MethodType argument
2757             if ("invoke".equals(name))
2758                 return invoker(type);
2759             if ("invokeExact".equals(name))
2760                 return exactInvoker(type);
2761             assert(!MemberName.isMethodHandleInvokeName(name));
2762             return null;
2763         }
2764         private MethodHandle findVirtualForVH(String name, MethodType type) {
2765             try {
2766                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2767             } catch (IllegalArgumentException e) {
2768                 return null;
2769             }
2770         }
2771 
2772         /**
2773          * Produces a method handle which creates an object and initializes it, using
2774          * the constructor of the specified type.
2775          * The parameter types of the method handle will be those of the constructor,
2776          * while the return type will be a reference to the constructor's class.
2777          * The constructor and all its argument types must be accessible to the lookup object.
2778          * <p>
2779          * The requested type must have a return type of {@code void}.
2780          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2781          * <p>
2782          * The returned method handle will have
2783          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2784          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2785          * <p>
2786          * If the returned method handle is invoked, the constructor's class will
2787          * be initialized, if it has not already been initialized.
2788          * <p><b>Example:</b>
2789          * {@snippet lang="java" :
2790 import static java.lang.invoke.MethodHandles.*;
2791 import static java.lang.invoke.MethodType.*;
2792 ...
2793 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2794   ArrayList.class, methodType(void.class, Collection.class));
2795 Collection orig = Arrays.asList("x", "y");
2796 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2797 assert(orig != copy);
2798 assertEquals(orig, copy);
2799 // a variable-arity constructor:
2800 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2801   ProcessBuilder.class, methodType(void.class, String[].class));
2802 ProcessBuilder pb = (ProcessBuilder)
2803   MH_newProcessBuilder.invoke("x", "y", "z");
2804 assertEquals("[x, y, z]", pb.command().toString());
2805          * }
2806          *
2807          *
2808          * @param refc the class or interface from which the method is accessed
2809          * @param type the type of the method, with the receiver argument omitted, and a void return type
2810          * @return the desired method handle
2811          * @throws NoSuchMethodException if the constructor does not exist
2812          * @throws IllegalAccessException if access checking fails
2813          *                                or if the method's variable arity modifier bit
2814          *                                is set and {@code asVarargsCollector} fails
2815          * @throws    SecurityException if a security manager is present and it
2816          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2817          * @throws NullPointerException if any argument is null
2818          */
2819         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2820             if (refc.isArray()) {
2821                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2822             }
2823             if (type.returnType() != void.class) {
2824                 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName());
2825             }
2826             String name = ConstantDescs.INIT_NAME;
2827             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2828             return getDirectConstructor(refc, ctor);
2829         }
2830 
2831         /**
2832          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2833          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2834          * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2835          * and then determines whether the class is accessible to this lookup object.
2836          * <p>
2837          * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}.
2838          * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences
2839          * of {@code '['} and followed by the element type as encoded in the
2840          * {@linkplain Class##nameFormat table} specified in {@link Class#getName}.
2841          * <p>
2842          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2843          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2844          *
2845          * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class
2846          *                   or the string representing an array class
2847          * @return the requested class.
2848          * @throws SecurityException if a security manager is present and it
2849          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2850          * @throws LinkageError if the linkage fails
2851          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2852          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2853          * modes.
2854          * @throws NullPointerException if {@code targetName} is null
2855          * @since 9
2856          * @jvms 5.4.3.1 Class and Interface Resolution
2857          */
2858         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2859             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2860             return accessClass(targetClass);
2861         }
2862 
2863         /**
2864          * Ensures that {@code targetClass} has been initialized. The class
2865          * to be initialized must be {@linkplain #accessClass accessible}
2866          * to this {@code Lookup} object.  This method causes {@code targetClass}
2867          * to be initialized if it has not been already initialized,
2868          * as specified in JVMS {@jvms 5.5}.
2869          *
2870          * <p>
2871          * This method returns when {@code targetClass} is fully initialized, or
2872          * when {@code targetClass} is being initialized by the current thread.
2873          *
2874          * @param <T> the type of the class to be initialized
2875          * @param targetClass the class to be initialized
2876          * @return {@code targetClass} that has been initialized, or that is being
2877          *         initialized by the current thread.
2878          *
2879          * @throws  IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2880          *          or array class
2881          * @throws  IllegalAccessException if {@code targetClass} is not
2882          *          {@linkplain #accessClass accessible} to this lookup
2883          * @throws  ExceptionInInitializerError if the class initialization provoked
2884          *          by this method fails
2885          * @throws  SecurityException if a security manager is present and it
2886          *          <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2887          * @since 15
2888          * @jvms 5.5 Initialization
2889          */
2890         public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException {
2891             if (targetClass.isPrimitive())
2892                 throw new IllegalArgumentException(targetClass + " is a primitive class");
2893             if (targetClass.isArray())
2894                 throw new IllegalArgumentException(targetClass + " is an array class");
2895 
2896             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2897                 throw makeAccessException(targetClass);
2898             }
2899             checkSecurityManager(targetClass);
2900 
2901             // ensure class initialization
2902             Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2903             return targetClass;
2904         }
2905 
2906         /*
2907          * Returns IllegalAccessException due to access violation to the given targetClass.
2908          *
2909          * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2910          * which verifies access to a class rather a member.
2911          */
2912         private IllegalAccessException makeAccessException(Class<?> targetClass) {
2913             String message = "access violation: "+ targetClass;
2914             if (this == MethodHandles.publicLookup()) {
2915                 message += ", from public Lookup";
2916             } else {
2917                 Module m = lookupClass().getModule();
2918                 message += ", from " + lookupClass() + " (" + m + ")";
2919                 if (prevLookupClass != null) {
2920                     message += ", previous lookup " +
2921                             prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2922                 }
2923             }
2924             return new IllegalAccessException(message);
2925         }
2926 
2927         /**
2928          * Determines if a class can be accessed from the lookup context defined by
2929          * this {@code Lookup} object. The static initializer of the class is not run.
2930          * If {@code targetClass} is an array class, {@code targetClass} is accessible
2931          * if the element type of the array class is accessible.  Otherwise,
2932          * {@code targetClass} is determined as accessible as follows.
2933          *
2934          * <p>
2935          * If {@code targetClass} is in the same module as the lookup class,
2936          * the lookup class is {@code LC} in module {@code M1} and
2937          * the previous lookup class is in module {@code M0} or
2938          * {@code null} if not present,
2939          * {@code targetClass} is accessible if and only if one of the following is true:
2940          * <ul>
2941          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2942          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2943          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2944          *     in the same runtime package of {@code LC}.</li>
2945          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2946          *     a public type in {@code M1}.</li>
2947          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2948          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2949          *     if the previous lookup class is present; otherwise, {@code targetClass}
2950          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2951          * </ul>
2952          *
2953          * <p>
2954          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2955          * can access public types in all modules when the type is in a package
2956          * that is exported unconditionally.
2957          * <p>
2958          * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2959          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2960          * is inaccessible.
2961          * <p>
2962          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2963          * {@code M1} is the module containing {@code lookupClass} and
2964          * {@code M2} is the module containing {@code targetClass},
2965          * then {@code targetClass} is accessible if and only if
2966          * <ul>
2967          * <li>{@code M1} reads {@code M2}, and
2968          * <li>{@code targetClass} is public and in a package exported by
2969          *     {@code M2} at least to {@code M1}.
2970          * </ul>
2971          * <p>
2972          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2973          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2974          * containing the previous lookup class, then {@code targetClass} is accessible
2975          * if and only if one of the following is true:
2976          * <ul>
2977          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2978          *     {@linkplain Module#reads reads} {@code M0} and the type is
2979          *     in a package that is exported to at least {@code M1}.
2980          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2981          *     {@linkplain Module#reads reads} {@code M1} and the type is
2982          *     in a package that is exported to at least {@code M0}.
2983          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2984          *     and {@code M1} reads {@code M2} and the type is in a package
2985          *     that is exported to at least both {@code M0} and {@code M2}.
2986          * </ul>
2987          * <p>
2988          * Otherwise, {@code targetClass} is not accessible.
2989          *
2990          * @param <T> the type of the class to be access-checked
2991          * @param targetClass the class to be access-checked
2992          * @return {@code targetClass} that has been access-checked
2993          * @throws IllegalAccessException if the class is not accessible from the lookup class
2994          * and previous lookup class, if present, using the allowed access modes.
2995          * @throws SecurityException if a security manager is present and it
2996          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2997          * @throws NullPointerException if {@code targetClass} is {@code null}
2998          * @since 9
2999          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
3000          */
3001         public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException {
3002             if (!isClassAccessible(targetClass)) {
3003                 throw makeAccessException(targetClass);
3004             }
3005             checkSecurityManager(targetClass);
3006             return targetClass;
3007         }
3008 
3009         /**
3010          * Produces an early-bound method handle for a virtual method.
3011          * It will bypass checks for overriding methods on the receiver,
3012          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3013          * instruction from within the explicitly specified {@code specialCaller}.
3014          * The type of the method handle will be that of the method,
3015          * with a suitably restricted receiver type prepended.
3016          * (The receiver type will be {@code specialCaller} or a subtype.)
3017          * The method and all its argument types must be accessible
3018          * to the lookup object.
3019          * <p>
3020          * Before method resolution,
3021          * if the explicitly specified caller class is not identical with the
3022          * lookup class, or if this lookup object does not have
3023          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3024          * privileges, the access fails.
3025          * <p>
3026          * The returned method handle will have
3027          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3028          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3029          * <p style="font-size:smaller;">
3030          * <em>(Note:  JVM internal methods named {@value ConstantDescs#INIT_NAME}
3031          * are not visible to this API,
3032          * even though the {@code invokespecial} instruction can refer to them
3033          * in special circumstances.  Use {@link #findConstructor findConstructor}
3034          * to access instance initialization methods in a safe manner.)</em>
3035          * <p><b>Example:</b>
3036          * {@snippet lang="java" :
3037 import static java.lang.invoke.MethodHandles.*;
3038 import static java.lang.invoke.MethodType.*;
3039 ...
3040 static class Listie extends ArrayList {
3041   public String toString() { return "[wee Listie]"; }
3042   static Lookup lookup() { return MethodHandles.lookup(); }
3043 }
3044 ...
3045 // no access to constructor via invokeSpecial:
3046 MethodHandle MH_newListie = Listie.lookup()
3047   .findConstructor(Listie.class, methodType(void.class));
3048 Listie l = (Listie) MH_newListie.invokeExact();
3049 try { assertEquals("impossible", Listie.lookup().findSpecial(
3050         Listie.class, "<init>", methodType(void.class), Listie.class));
3051  } catch (NoSuchMethodException ex) { } // OK
3052 // access to super and self methods via invokeSpecial:
3053 MethodHandle MH_super = Listie.lookup().findSpecial(
3054   ArrayList.class, "toString" , methodType(String.class), Listie.class);
3055 MethodHandle MH_this = Listie.lookup().findSpecial(
3056   Listie.class, "toString" , methodType(String.class), Listie.class);
3057 MethodHandle MH_duper = Listie.lookup().findSpecial(
3058   Object.class, "toString" , methodType(String.class), Listie.class);
3059 assertEquals("[]", (String) MH_super.invokeExact(l));
3060 assertEquals(""+l, (String) MH_this.invokeExact(l));
3061 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
3062 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
3063         String.class, "toString", methodType(String.class), Listie.class));
3064  } catch (IllegalAccessException ex) { } // OK
3065 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
3066 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
3067          * }
3068          *
3069          * @param refc the class or interface from which the method is accessed
3070          * @param name the name of the method (which must not be "&lt;init&gt;")
3071          * @param type the type of the method, with the receiver argument omitted
3072          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
3073          * @return the desired method handle
3074          * @throws NoSuchMethodException if the method does not exist
3075          * @throws IllegalAccessException if access checking fails,
3076          *                                or if the method is {@code static},
3077          *                                or if the method's variable arity modifier bit
3078          *                                is set and {@code asVarargsCollector} fails
3079          * @throws    SecurityException if a security manager is present and it
3080          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3081          * @throws NullPointerException if any argument is null
3082          */
3083         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
3084                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
3085             checkSpecialCaller(specialCaller, refc);
3086             Lookup specialLookup = this.in(specialCaller);
3087             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
3088             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
3089         }
3090 
3091         /**
3092          * Produces a method handle giving read access to a non-static field.
3093          * The type of the method handle will have a return type of the field's
3094          * value type.
3095          * The method handle's single argument will be the instance containing
3096          * the field.
3097          * Access checking is performed immediately on behalf of the lookup class.
3098          * @param refc the class or interface from which the method is accessed
3099          * @param name the field's name
3100          * @param type the field's type
3101          * @return a method handle which can load values from the field
3102          * @throws NoSuchFieldException if the field does not exist
3103          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3104          * @throws    SecurityException if a security manager is present and it
3105          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3106          * @throws NullPointerException if any argument is null
3107          * @see #findVarHandle(Class, String, Class)
3108          */
3109         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3110             MemberName field = resolveOrFail(REF_getField, refc, name, type);
3111             return getDirectField(REF_getField, refc, field);
3112         }
3113 
3114         /**
3115          * Produces a method handle giving write access to a non-static field.
3116          * The type of the method handle will have a void return type.
3117          * The method handle will take two arguments, the instance containing
3118          * the field, and the value to be stored.
3119          * The second argument will be of the field's value type.
3120          * Access checking is performed immediately on behalf of the lookup class.
3121          * @param refc the class or interface from which the method is accessed
3122          * @param name the field's name
3123          * @param type the field's type
3124          * @return a method handle which can store values into the field
3125          * @throws NoSuchFieldException if the field does not exist
3126          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3127          *                                or {@code final}
3128          * @throws    SecurityException if a security manager is present and it
3129          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3130          * @throws NullPointerException if any argument is null
3131          * @see #findVarHandle(Class, String, Class)
3132          */
3133         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3134             MemberName field = resolveOrFail(REF_putField, refc, name, type);
3135             return getDirectField(REF_putField, refc, field);
3136         }
3137 
3138         /**
3139          * Produces a VarHandle giving access to a non-static field {@code name}
3140          * of type {@code type} declared in a class of type {@code recv}.
3141          * The VarHandle's variable type is {@code type} and it has one
3142          * coordinate type, {@code recv}.
3143          * <p>
3144          * Access checking is performed immediately on behalf of the lookup
3145          * class.
3146          * <p>
3147          * Certain access modes of the returned VarHandle are unsupported under
3148          * the following conditions:
3149          * <ul>
3150          * <li>if the field is declared {@code final}, then the write, atomic
3151          *     update, numeric atomic update, and bitwise atomic update access
3152          *     modes are unsupported.
3153          * <li>if the field type is anything other than {@code byte},
3154          *     {@code short}, {@code char}, {@code int}, {@code long},
3155          *     {@code float}, or {@code double} then numeric atomic update
3156          *     access modes are unsupported.
3157          * <li>if the field type is anything other than {@code boolean},
3158          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3159          *     {@code long} then bitwise atomic update access modes are
3160          *     unsupported.
3161          * </ul>
3162          * <p>
3163          * If the field is declared {@code volatile} then the returned VarHandle
3164          * will override access to the field (effectively ignore the
3165          * {@code volatile} declaration) in accordance to its specified
3166          * access modes.
3167          * <p>
3168          * If the field type is {@code float} or {@code double} then numeric
3169          * and atomic update access modes compare values using their bitwise
3170          * representation (see {@link Float#floatToRawIntBits} and
3171          * {@link Double#doubleToRawLongBits}, respectively).
3172          * @apiNote
3173          * Bitwise comparison of {@code float} values or {@code double} values,
3174          * as performed by the numeric and atomic update access modes, differ
3175          * from the primitive {@code ==} operator and the {@link Float#equals}
3176          * and {@link Double#equals} methods, specifically with respect to
3177          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3178          * Care should be taken when performing a compare and set or a compare
3179          * and exchange operation with such values since the operation may
3180          * unexpectedly fail.
3181          * There are many possible NaN values that are considered to be
3182          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3183          * provided by Java can distinguish between them.  Operation failure can
3184          * occur if the expected or witness value is a NaN value and it is
3185          * transformed (perhaps in a platform specific manner) into another NaN
3186          * value, and thus has a different bitwise representation (see
3187          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3188          * details).
3189          * The values {@code -0.0} and {@code +0.0} have different bitwise
3190          * representations but are considered equal when using the primitive
3191          * {@code ==} operator.  Operation failure can occur if, for example, a
3192          * numeric algorithm computes an expected value to be say {@code -0.0}
3193          * and previously computed the witness value to be say {@code +0.0}.
3194          * @param recv the receiver class, of type {@code R}, that declares the
3195          * non-static field
3196          * @param name the field's name
3197          * @param type the field's type, of type {@code T}
3198          * @return a VarHandle giving access to non-static fields.
3199          * @throws NoSuchFieldException if the field does not exist
3200          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3201          * @throws    SecurityException if a security manager is present and it
3202          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3203          * @throws NullPointerException if any argument is null
3204          * @since 9
3205          */
3206         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3207             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3208             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3209             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3210         }
3211 
3212         /**
3213          * Produces a method handle giving read access to a static field.
3214          * The type of the method handle will have a return type of the field's
3215          * value type.
3216          * The method handle will take no arguments.
3217          * Access checking is performed immediately on behalf of the lookup class.
3218          * <p>
3219          * If the returned method handle is invoked, the field's class will
3220          * be initialized, if it has not already been initialized.
3221          * @param refc the class or interface from which the method is accessed
3222          * @param name the field's name
3223          * @param type the field's type
3224          * @return a method handle which can load values from the field
3225          * @throws NoSuchFieldException if the field does not exist
3226          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3227          * @throws    SecurityException if a security manager is present and it
3228          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3229          * @throws NullPointerException if any argument is null
3230          */
3231         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3232             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3233             return getDirectField(REF_getStatic, refc, field);
3234         }
3235 
3236         /**
3237          * Produces a method handle giving write access to a static field.
3238          * The type of the method handle will have a void return type.
3239          * The method handle will take a single
3240          * argument, of the field's value type, the value to be stored.
3241          * Access checking is performed immediately on behalf of the lookup class.
3242          * <p>
3243          * If the returned method handle is invoked, the field's class will
3244          * be initialized, if it has not already been initialized.
3245          * @param refc the class or interface from which the method is accessed
3246          * @param name the field's name
3247          * @param type the field's type
3248          * @return a method handle which can store values into the field
3249          * @throws NoSuchFieldException if the field does not exist
3250          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3251          *                                or is {@code final}
3252          * @throws    SecurityException if a security manager is present and it
3253          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3254          * @throws NullPointerException if any argument is null
3255          */
3256         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3257             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3258             return getDirectField(REF_putStatic, refc, field);
3259         }
3260 
3261         /**
3262          * Produces a VarHandle giving access to a static field {@code name} of
3263          * type {@code type} declared in a class of type {@code decl}.
3264          * The VarHandle's variable type is {@code type} and it has no
3265          * coordinate types.
3266          * <p>
3267          * Access checking is performed immediately on behalf of the lookup
3268          * class.
3269          * <p>
3270          * If the returned VarHandle is operated on, the declaring class will be
3271          * initialized, if it has not already been initialized.
3272          * <p>
3273          * Certain access modes of the returned VarHandle are unsupported under
3274          * the following conditions:
3275          * <ul>
3276          * <li>if the field is declared {@code final}, then the write, atomic
3277          *     update, numeric atomic update, and bitwise atomic update access
3278          *     modes are unsupported.
3279          * <li>if the field type is anything other than {@code byte},
3280          *     {@code short}, {@code char}, {@code int}, {@code long},
3281          *     {@code float}, or {@code double}, then numeric atomic update
3282          *     access modes are unsupported.
3283          * <li>if the field type is anything other than {@code boolean},
3284          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3285          *     {@code long} then bitwise atomic update access modes are
3286          *     unsupported.
3287          * </ul>
3288          * <p>
3289          * If the field is declared {@code volatile} then the returned VarHandle
3290          * will override access to the field (effectively ignore the
3291          * {@code volatile} declaration) in accordance to its specified
3292          * access modes.
3293          * <p>
3294          * If the field type is {@code float} or {@code double} then numeric
3295          * and atomic update access modes compare values using their bitwise
3296          * representation (see {@link Float#floatToRawIntBits} and
3297          * {@link Double#doubleToRawLongBits}, respectively).
3298          * @apiNote
3299          * Bitwise comparison of {@code float} values or {@code double} values,
3300          * as performed by the numeric and atomic update access modes, differ
3301          * from the primitive {@code ==} operator and the {@link Float#equals}
3302          * and {@link Double#equals} methods, specifically with respect to
3303          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3304          * Care should be taken when performing a compare and set or a compare
3305          * and exchange operation with such values since the operation may
3306          * unexpectedly fail.
3307          * There are many possible NaN values that are considered to be
3308          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3309          * provided by Java can distinguish between them.  Operation failure can
3310          * occur if the expected or witness value is a NaN value and it is
3311          * transformed (perhaps in a platform specific manner) into another NaN
3312          * value, and thus has a different bitwise representation (see
3313          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3314          * details).
3315          * The values {@code -0.0} and {@code +0.0} have different bitwise
3316          * representations but are considered equal when using the primitive
3317          * {@code ==} operator.  Operation failure can occur if, for example, a
3318          * numeric algorithm computes an expected value to be say {@code -0.0}
3319          * and previously computed the witness value to be say {@code +0.0}.
3320          * @param decl the class that declares the static field
3321          * @param name the field's name
3322          * @param type the field's type, of type {@code T}
3323          * @return a VarHandle giving access to a static field
3324          * @throws NoSuchFieldException if the field does not exist
3325          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3326          * @throws    SecurityException if a security manager is present and it
3327          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3328          * @throws NullPointerException if any argument is null
3329          * @since 9
3330          */
3331         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3332             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3333             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3334             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3335         }
3336 
3337         /**
3338          * Produces an early-bound method handle for a non-static method.
3339          * The receiver must have a supertype {@code defc} in which a method
3340          * of the given name and type is accessible to the lookup class.
3341          * The method and all its argument types must be accessible to the lookup object.
3342          * The type of the method handle will be that of the method,
3343          * without any insertion of an additional receiver parameter.
3344          * The given receiver will be bound into the method handle,
3345          * so that every call to the method handle will invoke the
3346          * requested method on the given receiver.
3347          * <p>
3348          * The returned method handle will have
3349          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3350          * the method's variable arity modifier bit ({@code 0x0080}) is set
3351          * <em>and</em> the trailing array argument is not the only argument.
3352          * (If the trailing array argument is the only argument,
3353          * the given receiver value will be bound to it.)
3354          * <p>
3355          * This is almost equivalent to the following code, with some differences noted below:
3356          * {@snippet lang="java" :
3357 import static java.lang.invoke.MethodHandles.*;
3358 import static java.lang.invoke.MethodType.*;
3359 ...
3360 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3361 MethodHandle mh1 = mh0.bindTo(receiver);
3362 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3363 return mh1;
3364          * }
3365          * where {@code defc} is either {@code receiver.getClass()} or a super
3366          * type of that class, in which the requested method is accessible
3367          * to the lookup class.
3368          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3369          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3370          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3371          * the receiver is restricted by {@code findVirtual} to the lookup class.)
3372          * @param receiver the object from which the method is accessed
3373          * @param name the name of the method
3374          * @param type the type of the method, with the receiver argument omitted
3375          * @return the desired method handle
3376          * @throws NoSuchMethodException if the method does not exist
3377          * @throws IllegalAccessException if access checking fails
3378          *                                or if the method's variable arity modifier bit
3379          *                                is set and {@code asVarargsCollector} fails
3380          * @throws    SecurityException if a security manager is present and it
3381          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3382          * @throws NullPointerException if any argument is null
3383          * @see MethodHandle#bindTo
3384          * @see #findVirtual
3385          */
3386         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3387             Class<? extends Object> refc = receiver.getClass(); // may get NPE
3388             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3389             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3390             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3391                 throw new IllegalAccessException("The restricted defining class " +
3392                                                  mh.type().leadingReferenceParameter().getName() +
3393                                                  " is not assignable from receiver class " +
3394                                                  receiver.getClass().getName());
3395             }
3396             return mh.bindArgumentL(0, receiver).setVarargs(method);
3397         }
3398 
3399         /**
3400          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3401          * to <i>m</i>, if the lookup class has permission.
3402          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3403          * If <i>m</i> is virtual, overriding is respected on every call.
3404          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3405          * The type of the method handle will be that of the method,
3406          * with the receiver type prepended (but only if it is non-static).
3407          * If the method's {@code accessible} flag is not set,
3408          * access checking is performed immediately on behalf of the lookup class.
3409          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3410          * <p>
3411          * The returned method handle will have
3412          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3413          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3414          * <p>
3415          * If <i>m</i> is static, and
3416          * if the returned method handle is invoked, the method's class will
3417          * be initialized, if it has not already been initialized.
3418          * @param m the reflected method
3419          * @return a method handle which can invoke the reflected method
3420          * @throws IllegalAccessException if access checking fails
3421          *                                or if the method's variable arity modifier bit
3422          *                                is set and {@code asVarargsCollector} fails
3423          * @throws NullPointerException if the argument is null
3424          */
3425         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3426             if (m.getDeclaringClass() == MethodHandle.class) {
3427                 MethodHandle mh = unreflectForMH(m);
3428                 if (mh != null)  return mh;
3429             }
3430             if (m.getDeclaringClass() == VarHandle.class) {
3431                 MethodHandle mh = unreflectForVH(m);
3432                 if (mh != null)  return mh;
3433             }
3434             MemberName method = new MemberName(m);
3435             byte refKind = method.getReferenceKind();
3436             if (refKind == REF_invokeSpecial)
3437                 refKind = REF_invokeVirtual;
3438             assert(method.isMethod());
3439             @SuppressWarnings("deprecation")
3440             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3441             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3442         }
3443         private MethodHandle unreflectForMH(Method m) {
3444             // these names require special lookups because they throw UnsupportedOperationException
3445             if (MemberName.isMethodHandleInvokeName(m.getName()))
3446                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3447             return null;
3448         }
3449         private MethodHandle unreflectForVH(Method m) {
3450             // these names require special lookups because they throw UnsupportedOperationException
3451             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3452                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3453             return null;
3454         }
3455 
3456         /**
3457          * Produces a method handle for a reflected method.
3458          * It will bypass checks for overriding methods on the receiver,
3459          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3460          * instruction from within the explicitly specified {@code specialCaller}.
3461          * The type of the method handle will be that of the method,
3462          * with a suitably restricted receiver type prepended.
3463          * (The receiver type will be {@code specialCaller} or a subtype.)
3464          * If the method's {@code accessible} flag is not set,
3465          * access checking is performed immediately on behalf of the lookup class,
3466          * as if {@code invokespecial} instruction were being linked.
3467          * <p>
3468          * Before method resolution,
3469          * if the explicitly specified caller class is not identical with the
3470          * lookup class, or if this lookup object does not have
3471          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3472          * privileges, the access fails.
3473          * <p>
3474          * The returned method handle will have
3475          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3476          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3477          * @param m the reflected method
3478          * @param specialCaller the class nominally calling the method
3479          * @return a method handle which can invoke the reflected method
3480          * @throws IllegalAccessException if access checking fails,
3481          *                                or if the method is {@code static},
3482          *                                or if the method's variable arity modifier bit
3483          *                                is set and {@code asVarargsCollector} fails
3484          * @throws NullPointerException if any argument is null
3485          */
3486         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3487             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3488             Lookup specialLookup = this.in(specialCaller);
3489             MemberName method = new MemberName(m, true);
3490             assert(method.isMethod());
3491             // ignore m.isAccessible:  this is a new kind of access
3492             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3493         }
3494 
3495         /**
3496          * Produces a method handle for a reflected constructor.
3497          * The type of the method handle will be that of the constructor,
3498          * with the return type changed to the declaring class.
3499          * The method handle will perform a {@code newInstance} operation,
3500          * creating a new instance of the constructor's class on the
3501          * arguments passed to the method handle.
3502          * <p>
3503          * If the constructor's {@code accessible} flag is not set,
3504          * access checking is performed immediately on behalf of the lookup class.
3505          * <p>
3506          * The returned method handle will have
3507          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3508          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3509          * <p>
3510          * If the returned method handle is invoked, the constructor's class will
3511          * be initialized, if it has not already been initialized.
3512          * @param c the reflected constructor
3513          * @return a method handle which can invoke the reflected constructor
3514          * @throws IllegalAccessException if access checking fails
3515          *                                or if the method's variable arity modifier bit
3516          *                                is set and {@code asVarargsCollector} fails
3517          * @throws NullPointerException if the argument is null
3518          */
3519         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3520             MemberName ctor = new MemberName(c);
3521             assert(ctor.isConstructor());
3522             @SuppressWarnings("deprecation")
3523             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3524             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
3525         }
3526 
3527         /*
3528          * Produces a method handle that is capable of creating instances of the given class
3529          * and instantiated by the given constructor.  No security manager check.
3530          *
3531          * This method should only be used by ReflectionFactory::newConstructorForSerialization.
3532          */
3533         /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException {
3534             MemberName ctor = new MemberName(c);
3535             assert(ctor.isConstructor() && constructorInSuperclass(decl, c));
3536             checkAccess(REF_newInvokeSpecial, decl, ctor);
3537             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
3538             return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor);
3539         }
3540 
3541         private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) {
3542             if (decl == ctor.getDeclaringClass())
3543                 return true;
3544 
3545             Class<?> cl = decl;
3546             while ((cl = cl.getSuperclass()) != null) {
3547                 if (cl == ctor.getDeclaringClass()) {
3548                     return true;
3549                 }
3550             }
3551             return false;
3552         }
3553 
3554         /**
3555          * Produces a method handle giving read access to a reflected field.
3556          * The type of the method handle will have a return type of the field's
3557          * value type.
3558          * If the field is {@code static}, the method handle will take no arguments.
3559          * Otherwise, its single argument will be the instance containing
3560          * the field.
3561          * If the {@code Field} object's {@code accessible} flag is not set,
3562          * access checking is performed immediately on behalf of the lookup class.
3563          * <p>
3564          * If the field is static, and
3565          * if the returned method handle is invoked, the field's class will
3566          * be initialized, if it has not already been initialized.
3567          * @param f the reflected field
3568          * @return a method handle which can load values from the reflected field
3569          * @throws IllegalAccessException if access checking fails
3570          * @throws NullPointerException if the argument is null
3571          */
3572         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3573             return unreflectField(f, false);
3574         }
3575 
3576         /**
3577          * Produces a method handle giving write access to a reflected field.
3578          * The type of the method handle will have a void return type.
3579          * If the field is {@code static}, the method handle will take a single
3580          * argument, of the field's value type, the value to be stored.
3581          * Otherwise, the two arguments will be the instance containing
3582          * the field, and the value to be stored.
3583          * If the {@code Field} object's {@code accessible} flag is not set,
3584          * access checking is performed immediately on behalf of the lookup class.
3585          * <p>
3586          * If the field is {@code final}, write access will not be
3587          * allowed and access checking will fail, except under certain
3588          * narrow circumstances documented for {@link Field#set Field.set}.
3589          * A method handle is returned only if a corresponding call to
3590          * the {@code Field} object's {@code set} method could return
3591          * normally.  In particular, fields which are both {@code static}
3592          * and {@code final} may never be set.
3593          * <p>
3594          * If the field is {@code static}, and
3595          * if the returned method handle is invoked, the field's class will
3596          * be initialized, if it has not already been initialized.
3597          * @param f the reflected field
3598          * @return a method handle which can store values into the reflected field
3599          * @throws IllegalAccessException if access checking fails,
3600          *         or if the field is {@code final} and write access
3601          *         is not enabled on the {@code Field} object
3602          * @throws NullPointerException if the argument is null
3603          */
3604         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3605             return unreflectField(f, true);
3606         }
3607 
3608         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3609             MemberName field = new MemberName(f, isSetter);
3610             if (isSetter && field.isFinal()) {
3611                 if (field.isTrustedFinalField()) {
3612                     String msg = field.isStatic() ? "static final field has no write access"
3613                                                   : "final field has no write access";
3614                     throw field.makeAccessException(msg, this);
3615                 }
3616             }
3617             assert(isSetter
3618                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3619                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3620             @SuppressWarnings("deprecation")
3621             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3622             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3623         }
3624 
3625         /**
3626          * Produces a VarHandle giving access to a reflected field {@code f}
3627          * of type {@code T} declared in a class of type {@code R}.
3628          * The VarHandle's variable type is {@code T}.
3629          * If the field is non-static the VarHandle has one coordinate type,
3630          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3631          * coordinate types.
3632          * <p>
3633          * Access checking is performed immediately on behalf of the lookup
3634          * class, regardless of the value of the field's {@code accessible}
3635          * flag.
3636          * <p>
3637          * If the field is static, and if the returned VarHandle is operated
3638          * on, the field's declaring class will be initialized, if it has not
3639          * already been initialized.
3640          * <p>
3641          * Certain access modes of the returned VarHandle are unsupported under
3642          * the following conditions:
3643          * <ul>
3644          * <li>if the field is declared {@code final}, then the write, atomic
3645          *     update, numeric atomic update, and bitwise atomic update access
3646          *     modes are unsupported.
3647          * <li>if the field type is anything other than {@code byte},
3648          *     {@code short}, {@code char}, {@code int}, {@code long},
3649          *     {@code float}, or {@code double} then numeric atomic update
3650          *     access modes are unsupported.
3651          * <li>if the field type is anything other than {@code boolean},
3652          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3653          *     {@code long} then bitwise atomic update access modes are
3654          *     unsupported.
3655          * </ul>
3656          * <p>
3657          * If the field is declared {@code volatile} then the returned VarHandle
3658          * will override access to the field (effectively ignore the
3659          * {@code volatile} declaration) in accordance to its specified
3660          * access modes.
3661          * <p>
3662          * If the field type is {@code float} or {@code double} then numeric
3663          * and atomic update access modes compare values using their bitwise
3664          * representation (see {@link Float#floatToRawIntBits} and
3665          * {@link Double#doubleToRawLongBits}, respectively).
3666          * @apiNote
3667          * Bitwise comparison of {@code float} values or {@code double} values,
3668          * as performed by the numeric and atomic update access modes, differ
3669          * from the primitive {@code ==} operator and the {@link Float#equals}
3670          * and {@link Double#equals} methods, specifically with respect to
3671          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3672          * Care should be taken when performing a compare and set or a compare
3673          * and exchange operation with such values since the operation may
3674          * unexpectedly fail.
3675          * There are many possible NaN values that are considered to be
3676          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3677          * provided by Java can distinguish between them.  Operation failure can
3678          * occur if the expected or witness value is a NaN value and it is
3679          * transformed (perhaps in a platform specific manner) into another NaN
3680          * value, and thus has a different bitwise representation (see
3681          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3682          * details).
3683          * The values {@code -0.0} and {@code +0.0} have different bitwise
3684          * representations but are considered equal when using the primitive
3685          * {@code ==} operator.  Operation failure can occur if, for example, a
3686          * numeric algorithm computes an expected value to be say {@code -0.0}
3687          * and previously computed the witness value to be say {@code +0.0}.
3688          * @param f the reflected field, with a field of type {@code T}, and
3689          * a declaring class of type {@code R}
3690          * @return a VarHandle giving access to non-static fields or a static
3691          * field
3692          * @throws IllegalAccessException if access checking fails
3693          * @throws NullPointerException if the argument is null
3694          * @since 9
3695          */
3696         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3697             MemberName getField = new MemberName(f, false);
3698             MemberName putField = new MemberName(f, true);
3699             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
3700                                                       f.getDeclaringClass(), getField, putField);
3701         }
3702 
3703         /**
3704          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3705          * created by this lookup object or a similar one.
3706          * Security and access checks are performed to ensure that this lookup object
3707          * is capable of reproducing the target method handle.
3708          * This means that the cracking may fail if target is a direct method handle
3709          * but was created by an unrelated lookup object.
3710          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3711          * and was created by a lookup object for a different class.
3712          * @param target a direct method handle to crack into symbolic reference components
3713          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3714          * @throws    SecurityException if a security manager is present and it
3715          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3716          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3717          * @throws    NullPointerException if the target is {@code null}
3718          * @see MethodHandleInfo
3719          * @since 1.8
3720          */
3721         public MethodHandleInfo revealDirect(MethodHandle target) {
3722             if (!target.isCrackable()) {
3723                 throw newIllegalArgumentException("not a direct method handle");
3724             }
3725             MemberName member = target.internalMemberName();
3726             Class<?> defc = member.getDeclaringClass();
3727             byte refKind = member.getReferenceKind();
3728             assert(MethodHandleNatives.refKindIsValid(refKind));
3729             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3730                 // Devirtualized method invocation is usually formally virtual.
3731                 // To avoid creating extra MemberName objects for this common case,
3732                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3733                 refKind = REF_invokeVirtual;
3734             if (refKind == REF_invokeVirtual && defc.isInterface())
3735                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3736                 refKind = REF_invokeInterface;
3737             // Check SM permissions and member access before cracking.
3738             try {
3739                 checkAccess(refKind, defc, member);
3740                 checkSecurityManager(defc, member);
3741             } catch (IllegalAccessException ex) {
3742                 throw new IllegalArgumentException(ex);
3743             }
3744             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3745                 Class<?> callerClass = target.internalCallerClass();
3746                 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3747                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3748             }
3749             // Produce the handle to the results.
3750             return new InfoFromMemberName(this, member, refKind);
3751         }
3752 
3753         /// Helper methods, all package-private.
3754 
3755         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3756             checkSymbolicClass(refc);  // do this before attempting to resolve
3757             Objects.requireNonNull(name);
3758             Objects.requireNonNull(type);
3759             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3760                                             NoSuchFieldException.class);
3761         }
3762 
3763         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3764             checkSymbolicClass(refc);  // do this before attempting to resolve
3765             Objects.requireNonNull(type);
3766             checkMethodName(refKind, name);  // implicit null-check of name
3767             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3768                                             NoSuchMethodException.class);
3769         }
3770 
3771         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3772             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3773             Objects.requireNonNull(member.getName());
3774             Objects.requireNonNull(member.getType());
3775             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3776                                             ReflectiveOperationException.class);
3777         }
3778 
3779         MemberName resolveOrNull(byte refKind, MemberName member) {
3780             // do this before attempting to resolve
3781             if (!isClassAccessible(member.getDeclaringClass())) {
3782                 return null;
3783             }
3784             Objects.requireNonNull(member.getName());
3785             Objects.requireNonNull(member.getType());
3786             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3787         }
3788 
3789         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3790             // do this before attempting to resolve
3791             if (!isClassAccessible(refc)) {
3792                 return null;
3793             }
3794             Objects.requireNonNull(type);
3795             // implicit null-check of name
3796             if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3797                 return null;
3798             }
3799             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3800         }
3801 
3802         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3803             if (!isClassAccessible(refc)) {
3804                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3805             }
3806         }
3807 
3808         boolean isClassAccessible(Class<?> refc) {
3809             Objects.requireNonNull(refc);
3810             Class<?> caller = lookupClassOrNull();
3811             Class<?> type = refc;
3812             while (type.isArray()) {
3813                 type = type.getComponentType();
3814             }
3815             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3816         }
3817 
3818         /** Check name for an illegal leading "&lt;" character. */
3819         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3820             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
3821                 throw new NoSuchMethodException("illegal method name: "+name);
3822         }
3823 
3824         /**
3825          * Find my trustable caller class if m is a caller sensitive method.
3826          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3827          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3828          */
3829         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3830             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3831                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3832                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3833             }
3834             return this;
3835         }
3836 
3837         /**
3838          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3839          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3840          *
3841          * @deprecated This method was originally designed to test {@code PRIVATE} access
3842          * that implies full privilege access but {@code MODULE} access has since become
3843          * independent of {@code PRIVATE} access.  It is recommended to call
3844          * {@link #hasFullPrivilegeAccess()} instead.
3845          * @since 9
3846          */
3847         @Deprecated(since="14")
3848         public boolean hasPrivateAccess() {
3849             return hasFullPrivilegeAccess();
3850         }
3851 
3852         /**
3853          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3854          * i.e. {@code PRIVATE} and {@code MODULE} access.
3855          * A {@code Lookup} object must have full privilege access in order to
3856          * access all members that are allowed to the
3857          * {@linkplain #lookupClass() lookup class}.
3858          *
3859          * @return {@code true} if this lookup has full privilege access.
3860          * @since 14
3861          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3862          */
3863         public boolean hasFullPrivilegeAccess() {
3864             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3865         }
3866 
3867         /**
3868          * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a>
3869          * for ensureInitialized, findClass or accessClass.
3870          */
3871         void checkSecurityManager(Class<?> refc) {
3872             if (allowedModes == TRUSTED)  return;
3873 
3874             @SuppressWarnings("removal")
3875             SecurityManager smgr = System.getSecurityManager();
3876             if (smgr == null)  return;
3877 
3878             // Step 1:
3879             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3880             if (!fullPrivilegeLookup ||
3881                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3882                 ReflectUtil.checkPackageAccess(refc);
3883             }
3884 
3885             // Step 2b:
3886             if (!fullPrivilegeLookup) {
3887                 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
3888             }
3889         }
3890 
3891         /**
3892          * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
3893          * Determines a trustable caller class to compare with refc, the symbolic reference class.
3894          * If this lookup object has full privilege access except original access,
3895          * then the caller class is the lookupClass.
3896          *
3897          * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)}
3898          * from the same module skips the security permission check.
3899          */
3900         void checkSecurityManager(Class<?> refc, MemberName m) {
3901             Objects.requireNonNull(refc);
3902             Objects.requireNonNull(m);
3903 
3904             if (allowedModes == TRUSTED)  return;
3905 
3906             @SuppressWarnings("removal")
3907             SecurityManager smgr = System.getSecurityManager();
3908             if (smgr == null)  return;
3909 
3910             // Step 1:
3911             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3912             if (!fullPrivilegeLookup ||
3913                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3914                 ReflectUtil.checkPackageAccess(refc);
3915             }
3916 
3917             // Step 2a:
3918             if (m.isPublic()) return;
3919             if (!fullPrivilegeLookup) {
3920                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3921             }
3922 
3923             // Step 3:
3924             Class<?> defc = m.getDeclaringClass();
3925             if (!fullPrivilegeLookup && defc != refc) {
3926                 ReflectUtil.checkPackageAccess(defc);
3927             }
3928         }
3929 
3930         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3931             boolean wantStatic = (refKind == REF_invokeStatic);
3932             String message;
3933             if (m.isConstructor())
3934                 message = "expected a method, not a constructor";
3935             else if (!m.isMethod())
3936                 message = "expected a method";
3937             else if (wantStatic != m.isStatic())
3938                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3939             else
3940                 { checkAccess(refKind, refc, m); return; }
3941             throw m.makeAccessException(message, this);
3942         }
3943 
3944         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3945             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3946             String message;
3947             if (wantStatic != m.isStatic())
3948                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3949             else
3950                 { checkAccess(refKind, refc, m); return; }
3951             throw m.makeAccessException(message, this);
3952         }
3953 
3954         private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) {
3955             return Modifier.isProtected(m.getModifiers()) &&
3956                     refKind == REF_invokeVirtual &&
3957                     m.getDeclaringClass() == Object.class &&
3958                     m.getName().equals("clone") &&
3959                     refc.isArray();
3960         }
3961 
3962         /** Check public/protected/private bits on the symbolic reference class and its member. */
3963         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3964             assert(m.referenceKindIsConsistentWith(refKind) &&
3965                    MethodHandleNatives.refKindIsValid(refKind) &&
3966                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3967             int allowedModes = this.allowedModes;
3968             if (allowedModes == TRUSTED)  return;
3969             int mods = m.getModifiers();
3970             if (isArrayClone(refKind, refc, m)) {
3971                 // The JVM does this hack also.
3972                 // (See ClassVerifier::verify_invoke_instructions
3973                 // and LinkResolver::check_method_accessability.)
3974                 // Because the JVM does not allow separate methods on array types,
3975                 // there is no separate method for int[].clone.
3976                 // All arrays simply inherit Object.clone.
3977                 // But for access checking logic, we make Object.clone
3978                 // (normally protected) appear to be public.
3979                 // Later on, when the DirectMethodHandle is created,
3980                 // its leading argument will be restricted to the
3981                 // requested array type.
3982                 // N.B. The return type is not adjusted, because
3983                 // that is *not* the bytecode behavior.
3984                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3985             }
3986             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3987                 // cannot "new" a protected ctor in a different package
3988                 mods ^= Modifier.PROTECTED;
3989             }
3990             if (Modifier.isFinal(mods) &&
3991                     MethodHandleNatives.refKindIsSetter(refKind))
3992                 throw m.makeAccessException("unexpected set of a final field", this);
3993             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3994             if ((requestedModes & allowedModes) != 0) {
3995                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3996                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3997                     return;
3998             } else {
3999                 // Protected members can also be checked as if they were package-private.
4000                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
4001                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
4002                     return;
4003             }
4004             throw m.makeAccessException(accessFailedMessage(refc, m), this);
4005         }
4006 
4007         String accessFailedMessage(Class<?> refc, MemberName m) {
4008             Class<?> defc = m.getDeclaringClass();
4009             int mods = m.getModifiers();
4010             // check the class first:
4011             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
4012                                (defc == refc ||
4013                                 Modifier.isPublic(refc.getModifiers())));
4014             if (!classOK && (allowedModes & PACKAGE) != 0) {
4015                 // ignore previous lookup class to check if default package access
4016                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
4017                            (defc == refc ||
4018                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
4019             }
4020             if (!classOK)
4021                 return "class is not public";
4022             if (Modifier.isPublic(mods))
4023                 return "access to public member failed";  // (how?, module not readable?)
4024             if (Modifier.isPrivate(mods))
4025                 return "member is private";
4026             if (Modifier.isProtected(mods))
4027                 return "member is protected";
4028             return "member is private to package";
4029         }
4030 
4031         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
4032             int allowedModes = this.allowedModes;
4033             if (allowedModes == TRUSTED)  return;
4034             if ((lookupModes() & PRIVATE) == 0
4035                 || (specialCaller != lookupClass()
4036                        // ensure non-abstract methods in superinterfaces can be special-invoked
4037                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
4038                 throw new MemberName(specialCaller).
4039                     makeAccessException("no private access for invokespecial", this);
4040         }
4041 
4042         private boolean restrictProtectedReceiver(MemberName method) {
4043             // The accessing class only has the right to use a protected member
4044             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
4045             if (!method.isProtected() || method.isStatic()
4046                 || allowedModes == TRUSTED
4047                 || method.getDeclaringClass() == lookupClass()
4048                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
4049                 return false;
4050             return true;
4051         }
4052         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
4053             assert(!method.isStatic());
4054             // receiver type of mh is too wide; narrow to caller
4055             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
4056                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
4057             }
4058             MethodType rawType = mh.type();
4059             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
4060             MethodType narrowType = rawType.changeParameterType(0, caller);
4061             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
4062             assert(mh.viewAsTypeChecks(narrowType, true));
4063             return mh.copyWith(narrowType, mh.form);
4064         }
4065 
4066         /** Check access and get the requested method. */
4067         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4068             final boolean doRestrict    = true;
4069             final boolean checkSecurity = true;
4070             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4071         }
4072         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
4073         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4074             final boolean doRestrict    = false;
4075             final boolean checkSecurity = true;
4076             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
4077         }
4078         /** Check access and get the requested method, eliding security manager checks. */
4079         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4080             final boolean doRestrict    = true;
4081             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4082             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4083         }
4084         /** Common code for all methods; do not call directly except from immediately above. */
4085         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
4086                                                    boolean checkSecurity,
4087                                                    boolean doRestrict,
4088                                                    Lookup boundCaller) throws IllegalAccessException {
4089             checkMethod(refKind, refc, method);
4090             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4091             if (checkSecurity)
4092                 checkSecurityManager(refc, method);
4093             assert(!method.isMethodHandleInvoke());
4094             if (refKind == REF_invokeSpecial &&
4095                 refc != lookupClass() &&
4096                 !refc.isInterface() && !lookupClass().isInterface() &&
4097                 refc != lookupClass().getSuperclass() &&
4098                 refc.isAssignableFrom(lookupClass())) {
4099                 assert(!method.getName().equals(ConstantDescs.INIT_NAME));  // not this code path
4100 
4101                 // Per JVMS 6.5, desc. of invokespecial instruction:
4102                 // If the method is in a superclass of the LC,
4103                 // and if our original search was above LC.super,
4104                 // repeat the search (symbolic lookup) from LC.super
4105                 // and continue with the direct superclass of that class,
4106                 // and so forth, until a match is found or no further superclasses exist.
4107                 // FIXME: MemberName.resolve should handle this instead.
4108                 Class<?> refcAsSuper = lookupClass();
4109                 MemberName m2;
4110                 do {
4111                     refcAsSuper = refcAsSuper.getSuperclass();
4112                     m2 = new MemberName(refcAsSuper,
4113                                         method.getName(),
4114                                         method.getMethodType(),
4115                                         REF_invokeSpecial);
4116                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
4117                 } while (m2 == null &&         // no method is found yet
4118                          refc != refcAsSuper); // search up to refc
4119                 if (m2 == null)  throw new InternalError(method.toString());
4120                 method = m2;
4121                 refc = refcAsSuper;
4122                 // redo basic checks
4123                 checkMethod(refKind, refc, method);
4124             }
4125             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
4126             MethodHandle mh = dmh;
4127             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
4128             if ((doRestrict && refKind == REF_invokeSpecial) ||
4129                     (MethodHandleNatives.refKindHasReceiver(refKind) &&
4130                             restrictProtectedReceiver(method) &&
4131                             // All arrays simply inherit the protected Object.clone method.
4132                             // The leading argument is already restricted to the requested
4133                             // array type (not the lookup class).
4134                             !isArrayClone(refKind, refc, method))) {
4135                 mh = restrictReceiver(method, dmh, lookupClass());
4136             }
4137             mh = maybeBindCaller(method, mh, boundCaller);
4138             mh = mh.setVarargs(method);
4139             return mh;
4140         }
4141         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
4142                                              throws IllegalAccessException {
4143             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
4144                 return mh;
4145 
4146             // boundCaller must have full privilege access.
4147             // It should have been checked by findBoundCallerLookup. Safe to check this again.
4148             if ((boundCaller.lookupModes() & ORIGINAL) == 0)
4149                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
4150 
4151             assert boundCaller.hasFullPrivilegeAccess();
4152 
4153             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
4154             // Note: caller will apply varargs after this step happens.
4155             return cbmh;
4156         }
4157 
4158         /** Check access and get the requested field. */
4159         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4160             final boolean checkSecurity = true;
4161             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4162         }
4163         /** Check access and get the requested field, eliding security manager checks. */
4164         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4165             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4166             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4167         }
4168         /** Common code for all fields; do not call directly except from immediately above. */
4169         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
4170                                                   boolean checkSecurity) throws IllegalAccessException {
4171             checkField(refKind, refc, field);
4172             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4173             if (checkSecurity)
4174                 checkSecurityManager(refc, field);
4175             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
4176             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
4177                                     restrictProtectedReceiver(field));
4178             if (doRestrict)
4179                 return restrictReceiver(field, dmh, lookupClass());
4180             return dmh;
4181         }
4182         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
4183                                             Class<?> refc, MemberName getField, MemberName putField)
4184                 throws IllegalAccessException {
4185             final boolean checkSecurity = true;
4186             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4187         }
4188         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
4189                                                              Class<?> refc, MemberName getField, MemberName putField)
4190                 throws IllegalAccessException {
4191             final boolean checkSecurity = false;
4192             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4193         }
4194         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
4195                                                   Class<?> refc, MemberName getField, MemberName putField,
4196                                                   boolean checkSecurity) throws IllegalAccessException {
4197             assert getField.isStatic() == putField.isStatic();
4198             assert getField.isGetter() && putField.isSetter();
4199             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
4200             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
4201 
4202             checkField(getRefKind, refc, getField);
4203             if (checkSecurity)
4204                 checkSecurityManager(refc, getField);
4205 
4206             if (!putField.isFinal()) {
4207                 // A VarHandle does not support updates to final fields, any
4208                 // such VarHandle to a final field will be read-only and
4209                 // therefore the following write-based accessibility checks are
4210                 // only required for non-final fields
4211                 checkField(putRefKind, refc, putField);
4212                 if (checkSecurity)
4213                     checkSecurityManager(refc, putField);
4214             }
4215 
4216             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
4217                                   restrictProtectedReceiver(getField));
4218             if (doRestrict) {
4219                 assert !getField.isStatic();
4220                 // receiver type of VarHandle is too wide; narrow to caller
4221                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
4222                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4223                 }
4224                 refc = lookupClass();
4225             }
4226             return VarHandles.makeFieldHandle(getField, refc,
4227                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4228         }
4229         /** Check access and get the requested constructor. */
4230         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4231             final boolean checkSecurity = true;
4232             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4233         }
4234         /** Check access and get the requested constructor, eliding security manager checks. */
4235         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4236             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4237             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4238         }
4239         /** Common code for all constructors; do not call directly except from immediately above. */
4240         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4241                                                   boolean checkSecurity) throws IllegalAccessException {
4242             assert(ctor.isConstructor());
4243             checkAccess(REF_newInvokeSpecial, refc, ctor);
4244             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4245             if (checkSecurity)
4246                 checkSecurityManager(refc, ctor);
4247             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4248             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4249         }
4250 
4251         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4252          */
4253         /*non-public*/
4254         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4255                 throws ReflectiveOperationException {
4256             if (!(type instanceof Class || type instanceof MethodType))
4257                 throw new InternalError("unresolved MemberName");
4258             MemberName member = new MemberName(refKind, defc, name, type);
4259             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4260             if (mh != null) {
4261                 checkSymbolicClass(defc);
4262                 return mh;
4263             }
4264             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
4265                 // Treat MethodHandle.invoke and invokeExact specially.
4266                 mh = findVirtualForMH(member.getName(), member.getMethodType());
4267                 if (mh != null) {
4268                     return mh;
4269                 }
4270             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4271                 // Treat signature-polymorphic methods on VarHandle specially.
4272                 mh = findVirtualForVH(member.getName(), member.getMethodType());
4273                 if (mh != null) {
4274                     return mh;
4275                 }
4276             }
4277             MemberName resolved = resolveOrFail(refKind, member);
4278             mh = getDirectMethodForConstant(refKind, defc, resolved);
4279             if (mh instanceof DirectMethodHandle dmh
4280                     && canBeCached(refKind, defc, resolved)) {
4281                 MemberName key = mh.internalMemberName();
4282                 if (key != null) {
4283                     key = key.asNormalOriginal();
4284                 }
4285                 if (member.equals(key)) {  // better safe than sorry
4286                     LOOKASIDE_TABLE.put(key, dmh);
4287                 }
4288             }
4289             return mh;
4290         }
4291         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4292             if (refKind == REF_invokeSpecial) {
4293                 return false;
4294             }
4295             if (!Modifier.isPublic(defc.getModifiers()) ||
4296                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4297                     !member.isPublic() ||
4298                     member.isCallerSensitive()) {
4299                 return false;
4300             }
4301             ClassLoader loader = defc.getClassLoader();
4302             if (loader != null) {
4303                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4304                 boolean found = false;
4305                 while (sysl != null) {
4306                     if (loader == sysl) { found = true; break; }
4307                     sysl = sysl.getParent();
4308                 }
4309                 if (!found) {
4310                     return false;
4311                 }
4312             }
4313             try {
4314                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4315                     new MemberName(refKind, defc, member.getName(), member.getType()));
4316                 if (resolved2 == null) {
4317                     return false;
4318                 }
4319                 checkSecurityManager(defc, resolved2);
4320             } catch (SecurityException ex) {
4321                 return false;
4322             }
4323             return true;
4324         }
4325         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4326                 throws ReflectiveOperationException {
4327             if (MethodHandleNatives.refKindIsField(refKind)) {
4328                 return getDirectFieldNoSecurityManager(refKind, defc, member);
4329             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4330                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
4331             } else if (refKind == REF_newInvokeSpecial) {
4332                 return getDirectConstructorNoSecurityManager(defc, member);
4333             }
4334             // oops
4335             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4336         }
4337 
4338         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4339     }
4340 
4341     /**
4342      * Produces a method handle constructing arrays of a desired type,
4343      * as if by the {@code anewarray} bytecode.
4344      * The return type of the method handle will be the array type.
4345      * The type of its sole argument will be {@code int}, which specifies the size of the array.
4346      *
4347      * <p> If the returned method handle is invoked with a negative
4348      * array size, a {@code NegativeArraySizeException} will be thrown.
4349      *
4350      * @param arrayClass an array type
4351      * @return a method handle which can create arrays of the given type
4352      * @throws NullPointerException if the argument is {@code null}
4353      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4354      * @see java.lang.reflect.Array#newInstance(Class, int)
4355      * @jvms 6.5 {@code anewarray} Instruction
4356      * @since 9
4357      */
4358     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4359         if (!arrayClass.isArray()) {
4360             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4361         }
4362         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4363                 bindTo(arrayClass.getComponentType());
4364         return ani.asType(ani.type().changeReturnType(arrayClass));
4365     }
4366 
4367     /**
4368      * Produces a method handle returning the length of an array,
4369      * as if by the {@code arraylength} bytecode.
4370      * The type of the method handle will have {@code int} as return type,
4371      * and its sole argument will be the array type.
4372      *
4373      * <p> If the returned method handle is invoked with a {@code null}
4374      * array reference, a {@code NullPointerException} will be thrown.
4375      *
4376      * @param arrayClass an array type
4377      * @return a method handle which can retrieve the length of an array of the given array type
4378      * @throws NullPointerException if the argument is {@code null}
4379      * @throws IllegalArgumentException if arrayClass is not an array type
4380      * @jvms 6.5 {@code arraylength} Instruction
4381      * @since 9
4382      */
4383     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4384         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4385     }
4386 
4387     /**
4388      * Produces a method handle giving read access to elements of an array,
4389      * as if by the {@code aaload} bytecode.
4390      * The type of the method handle will have a return type of the array's
4391      * element type.  Its first argument will be the array type,
4392      * and the second will be {@code int}.
4393      *
4394      * <p> When the returned method handle is invoked,
4395      * the array reference and array index are checked.
4396      * A {@code NullPointerException} will be thrown if the array reference
4397      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4398      * thrown if the index is negative or if it is greater than or equal to
4399      * the length of the array.
4400      *
4401      * @param arrayClass an array type
4402      * @return a method handle which can load values from the given array type
4403      * @throws NullPointerException if the argument is null
4404      * @throws  IllegalArgumentException if arrayClass is not an array type
4405      * @jvms 6.5 {@code aaload} Instruction
4406      */
4407     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4408         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4409     }
4410 
4411     /**
4412      * Produces a method handle giving write access to elements of an array,
4413      * as if by the {@code astore} bytecode.
4414      * The type of the method handle will have a void return type.
4415      * Its last argument will be the array's element type.
4416      * The first and second arguments will be the array type and int.
4417      *
4418      * <p> When the returned method handle is invoked,
4419      * the array reference and array index are checked.
4420      * A {@code NullPointerException} will be thrown if the array reference
4421      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4422      * thrown if the index is negative or if it is greater than or equal to
4423      * the length of the array.
4424      *
4425      * @param arrayClass the class of an array
4426      * @return a method handle which can store values into the array type
4427      * @throws NullPointerException if the argument is null
4428      * @throws IllegalArgumentException if arrayClass is not an array type
4429      * @jvms 6.5 {@code aastore} Instruction
4430      */
4431     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4432         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4433     }
4434 
4435     /**
4436      * Produces a VarHandle giving access to elements of an array of type
4437      * {@code arrayClass}.  The VarHandle's variable type is the component type
4438      * of {@code arrayClass} and the list of coordinate types is
4439      * {@code (arrayClass, int)}, where the {@code int} coordinate type
4440      * corresponds to an argument that is an index into an array.
4441      * <p>
4442      * Certain access modes of the returned VarHandle are unsupported under
4443      * the following conditions:
4444      * <ul>
4445      * <li>if the component type is anything other than {@code byte},
4446      *     {@code short}, {@code char}, {@code int}, {@code long},
4447      *     {@code float}, or {@code double} then numeric atomic update access
4448      *     modes are unsupported.
4449      * <li>if the component type is anything other than {@code boolean},
4450      *     {@code byte}, {@code short}, {@code char}, {@code int} or
4451      *     {@code long} then bitwise atomic update access modes are
4452      *     unsupported.
4453      * </ul>
4454      * <p>
4455      * If the component type is {@code float} or {@code double} then numeric
4456      * and atomic update access modes compare values using their bitwise
4457      * representation (see {@link Float#floatToRawIntBits} and
4458      * {@link Double#doubleToRawLongBits}, respectively).
4459      *
4460      * <p> When the returned {@code VarHandle} is invoked,
4461      * the array reference and array index are checked.
4462      * A {@code NullPointerException} will be thrown if the array reference
4463      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4464      * thrown if the index is negative or if it is greater than or equal to
4465      * the length of the array.
4466      *
4467      * @apiNote
4468      * Bitwise comparison of {@code float} values or {@code double} values,
4469      * as performed by the numeric and atomic update access modes, differ
4470      * from the primitive {@code ==} operator and the {@link Float#equals}
4471      * and {@link Double#equals} methods, specifically with respect to
4472      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4473      * Care should be taken when performing a compare and set or a compare
4474      * and exchange operation with such values since the operation may
4475      * unexpectedly fail.
4476      * There are many possible NaN values that are considered to be
4477      * {@code NaN} in Java, although no IEEE 754 floating-point operation
4478      * provided by Java can distinguish between them.  Operation failure can
4479      * occur if the expected or witness value is a NaN value and it is
4480      * transformed (perhaps in a platform specific manner) into another NaN
4481      * value, and thus has a different bitwise representation (see
4482      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4483      * details).
4484      * The values {@code -0.0} and {@code +0.0} have different bitwise
4485      * representations but are considered equal when using the primitive
4486      * {@code ==} operator.  Operation failure can occur if, for example, a
4487      * numeric algorithm computes an expected value to be say {@code -0.0}
4488      * and previously computed the witness value to be say {@code +0.0}.
4489      * @param arrayClass the class of an array, of type {@code T[]}
4490      * @return a VarHandle giving access to elements of an array
4491      * @throws NullPointerException if the arrayClass is null
4492      * @throws IllegalArgumentException if arrayClass is not an array type
4493      * @since 9
4494      */
4495     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4496         return VarHandles.makeArrayElementHandle(arrayClass);
4497     }
4498 
4499     /**
4500      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4501      * viewed as if it were a different primitive array type, such as
4502      * {@code int[]} or {@code long[]}.
4503      * The VarHandle's variable type is the component type of
4504      * {@code viewArrayClass} and the list of coordinate types is
4505      * {@code (byte[], int)}, where the {@code int} coordinate type
4506      * corresponds to an argument that is an index into a {@code byte[]} array.
4507      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4508      * array, composing bytes to or from a value of the component type of
4509      * {@code viewArrayClass} according to the given endianness.
4510      * <p>
4511      * The supported component types (variables types) are {@code short},
4512      * {@code char}, {@code int}, {@code long}, {@code float} and
4513      * {@code double}.
4514      * <p>
4515      * Access of bytes at a given index will result in an
4516      * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4517      * or greater than the {@code byte[]} array length minus the size (in bytes)
4518      * of {@code T}.
4519      * <p>
4520      * Access of bytes at an index may be aligned or misaligned for {@code T},
4521      * with respect to the underlying memory address, {@code A} say, associated
4522      * with the array and index.
4523      * If access is misaligned then access for anything other than the
4524      * {@code get} and {@code set} access modes will result in an
4525      * {@code IllegalStateException}.  In such cases atomic access is only
4526      * guaranteed with respect to the largest power of two that divides the GCD
4527      * of {@code A} and the size (in bytes) of {@code T}.
4528      * If access is aligned then following access modes are supported and are
4529      * guaranteed to support atomic access:
4530      * <ul>
4531      * <li>read write access modes for all {@code T}, with the exception of
4532      *     access modes {@code get} and {@code set} for {@code long} and
4533      *     {@code double} on 32-bit platforms.
4534      * <li>atomic update access modes for {@code int}, {@code long},
4535      *     {@code float} or {@code double}.
4536      *     (Future major platform releases of the JDK may support additional
4537      *     types for certain currently unsupported access modes.)
4538      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4539      *     (Future major platform releases of the JDK may support additional
4540      *     numeric types for certain currently unsupported access modes.)
4541      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4542      *     (Future major platform releases of the JDK may support additional
4543      *     numeric types for certain currently unsupported access modes.)
4544      * </ul>
4545      * <p>
4546      * Misaligned access, and therefore atomicity guarantees, may be determined
4547      * for {@code byte[]} arrays without operating on a specific array.  Given
4548      * an {@code index}, {@code T} and its corresponding boxed type,
4549      * {@code T_BOX}, misalignment may be determined as follows:
4550      * <pre>{@code
4551      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4552      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
4553      *     alignmentOffset(0, sizeOfT);
4554      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
4555      * boolean isMisaligned = misalignedAtIndex != 0;
4556      * }</pre>
4557      * <p>
4558      * If the variable type is {@code float} or {@code double} then atomic
4559      * update access modes compare values using their bitwise representation
4560      * (see {@link Float#floatToRawIntBits} and
4561      * {@link Double#doubleToRawLongBits}, respectively).
4562      * @param viewArrayClass the view array class, with a component type of
4563      * type {@code T}
4564      * @param byteOrder the endianness of the view array elements, as
4565      * stored in the underlying {@code byte} array
4566      * @return a VarHandle giving access to elements of a {@code byte[]} array
4567      * viewed as if elements corresponding to the components type of the view
4568      * array class
4569      * @throws NullPointerException if viewArrayClass or byteOrder is null
4570      * @throws IllegalArgumentException if viewArrayClass is not an array type
4571      * @throws UnsupportedOperationException if the component type of
4572      * viewArrayClass is not supported as a variable type
4573      * @since 9
4574      */
4575     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4576                                      ByteOrder byteOrder) throws IllegalArgumentException {
4577         Objects.requireNonNull(byteOrder);
4578         return VarHandles.byteArrayViewHandle(viewArrayClass,
4579                                               byteOrder == ByteOrder.BIG_ENDIAN);
4580     }
4581 
4582     /**
4583      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4584      * viewed as if it were an array of elements of a different primitive
4585      * component type to that of {@code byte}, such as {@code int[]} or
4586      * {@code long[]}.
4587      * The VarHandle's variable type is the component type of
4588      * {@code viewArrayClass} and the list of coordinate types is
4589      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4590      * corresponds to an argument that is an index into a {@code byte[]} array.
4591      * The returned VarHandle accesses bytes at an index in a
4592      * {@code ByteBuffer}, composing bytes to or from a value of the component
4593      * type of {@code viewArrayClass} according to the given endianness.
4594      * <p>
4595      * The supported component types (variables types) are {@code short},
4596      * {@code char}, {@code int}, {@code long}, {@code float} and
4597      * {@code double}.
4598      * <p>
4599      * Access will result in a {@code ReadOnlyBufferException} for anything
4600      * other than the read access modes if the {@code ByteBuffer} is read-only.
4601      * <p>
4602      * Access of bytes at a given index will result in an
4603      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4604      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4605      * {@code T}.
4606      * <p>
4607      * Access of bytes at an index may be aligned or misaligned for {@code T},
4608      * with respect to the underlying memory address, {@code A} say, associated
4609      * with the {@code ByteBuffer} and index.
4610      * If access is misaligned then access for anything other than the
4611      * {@code get} and {@code set} access modes will result in an
4612      * {@code IllegalStateException}.  In such cases atomic access is only
4613      * guaranteed with respect to the largest power of two that divides the GCD
4614      * of {@code A} and the size (in bytes) of {@code T}.
4615      * If access is aligned then following access modes are supported and are
4616      * guaranteed to support atomic access:
4617      * <ul>
4618      * <li>read write access modes for all {@code T}, with the exception of
4619      *     access modes {@code get} and {@code set} for {@code long} and
4620      *     {@code double} on 32-bit platforms.
4621      * <li>atomic update access modes for {@code int}, {@code long},
4622      *     {@code float} or {@code double}.
4623      *     (Future major platform releases of the JDK may support additional
4624      *     types for certain currently unsupported access modes.)
4625      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4626      *     (Future major platform releases of the JDK may support additional
4627      *     numeric types for certain currently unsupported access modes.)
4628      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4629      *     (Future major platform releases of the JDK may support additional
4630      *     numeric types for certain currently unsupported access modes.)
4631      * </ul>
4632      * <p>
4633      * Misaligned access, and therefore atomicity guarantees, may be determined
4634      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4635      * {@code index}, {@code T} and its corresponding boxed type,
4636      * {@code T_BOX}, as follows:
4637      * <pre>{@code
4638      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4639      * ByteBuffer bb = ...
4640      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4641      * boolean isMisaligned = misalignedAtIndex != 0;
4642      * }</pre>
4643      * <p>
4644      * If the variable type is {@code float} or {@code double} then atomic
4645      * update access modes compare values using their bitwise representation
4646      * (see {@link Float#floatToRawIntBits} and
4647      * {@link Double#doubleToRawLongBits}, respectively).
4648      * @param viewArrayClass the view array class, with a component type of
4649      * type {@code T}
4650      * @param byteOrder the endianness of the view array elements, as
4651      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4652      * endianness of a {@code ByteBuffer})
4653      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4654      * viewed as if elements corresponding to the components type of the view
4655      * array class
4656      * @throws NullPointerException if viewArrayClass or byteOrder is null
4657      * @throws IllegalArgumentException if viewArrayClass is not an array type
4658      * @throws UnsupportedOperationException if the component type of
4659      * viewArrayClass is not supported as a variable type
4660      * @since 9
4661      */
4662     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4663                                       ByteOrder byteOrder) throws IllegalArgumentException {
4664         Objects.requireNonNull(byteOrder);
4665         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4666                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4667     }
4668 
4669 
4670     /// method handle invocation (reflective style)
4671 
4672     /**
4673      * Produces a method handle which will invoke any method handle of the
4674      * given {@code type}, with a given number of trailing arguments replaced by
4675      * a single trailing {@code Object[]} array.
4676      * The resulting invoker will be a method handle with the following
4677      * arguments:
4678      * <ul>
4679      * <li>a single {@code MethodHandle} target
4680      * <li>zero or more leading values (counted by {@code leadingArgCount})
4681      * <li>an {@code Object[]} array containing trailing arguments
4682      * </ul>
4683      * <p>
4684      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4685      * the indicated {@code type}.
4686      * That is, if the target is exactly of the given {@code type}, it will behave
4687      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4688      * is used to convert the target to the required {@code type}.
4689      * <p>
4690      * The type of the returned invoker will not be the given {@code type}, but rather
4691      * will have all parameters except the first {@code leadingArgCount}
4692      * replaced by a single array of type {@code Object[]}, which will be
4693      * the final parameter.
4694      * <p>
4695      * Before invoking its target, the invoker will spread the final array, apply
4696      * reference casts as necessary, and unbox and widen primitive arguments.
4697      * If, when the invoker is called, the supplied array argument does
4698      * not have the correct number of elements, the invoker will throw
4699      * an {@link IllegalArgumentException} instead of invoking the target.
4700      * <p>
4701      * This method is equivalent to the following code (though it may be more efficient):
4702      * {@snippet lang="java" :
4703 MethodHandle invoker = MethodHandles.invoker(type);
4704 int spreadArgCount = type.parameterCount() - leadingArgCount;
4705 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4706 return invoker;
4707      * }
4708      * This method throws no reflective or security exceptions.
4709      * @param type the desired target type
4710      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4711      * @return a method handle suitable for invoking any method handle of the given type
4712      * @throws NullPointerException if {@code type} is null
4713      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4714      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4715      *                  or if the resulting method handle's type would have
4716      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4717      */
4718     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4719         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4720             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4721         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4722         return type.invokers().spreadInvoker(leadingArgCount);
4723     }
4724 
4725     /**
4726      * Produces a special <em>invoker method handle</em> which can be used to
4727      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4728      * The resulting invoker will have a type which is
4729      * exactly equal to the desired type, except that it will accept
4730      * an additional leading argument of type {@code MethodHandle}.
4731      * <p>
4732      * This method is equivalent to the following code (though it may be more efficient):
4733      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4734      *
4735      * <p style="font-size:smaller;">
4736      * <em>Discussion:</em>
4737      * Invoker method handles can be useful when working with variable method handles
4738      * of unknown types.
4739      * For example, to emulate an {@code invokeExact} call to a variable method
4740      * handle {@code M}, extract its type {@code T},
4741      * look up the invoker method {@code X} for {@code T},
4742      * and call the invoker method, as {@code X.invoke(T, A...)}.
4743      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4744      * is unknown.)
4745      * If spreading, collecting, or other argument transformations are required,
4746      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4747      * method handle values, as long as they are compatible with the type of {@code X}.
4748      * <p style="font-size:smaller;">
4749      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4750      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4751      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4752      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4753      * <p>
4754      * This method throws no reflective or security exceptions.
4755      * @param type the desired target type
4756      * @return a method handle suitable for invoking any method handle of the given type
4757      * @throws IllegalArgumentException if the resulting method handle's type would have
4758      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4759      */
4760     public static MethodHandle exactInvoker(MethodType type) {
4761         return type.invokers().exactInvoker();
4762     }
4763 
4764     /**
4765      * Produces a special <em>invoker method handle</em> which can be used to
4766      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4767      * The resulting invoker will have a type which is
4768      * exactly equal to the desired type, except that it will accept
4769      * an additional leading argument of type {@code MethodHandle}.
4770      * <p>
4771      * Before invoking its target, if the target differs from the expected type,
4772      * the invoker will apply reference casts as
4773      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4774      * Similarly, the return value will be converted as necessary.
4775      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4776      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4777      * <p>
4778      * This method is equivalent to the following code (though it may be more efficient):
4779      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4780      * <p style="font-size:smaller;">
4781      * <em>Discussion:</em>
4782      * A {@linkplain MethodType#genericMethodType general method type} is one which
4783      * mentions only {@code Object} arguments and return values.
4784      * An invoker for such a type is capable of calling any method handle
4785      * of the same arity as the general type.
4786      * <p style="font-size:smaller;">
4787      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4788      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4789      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4790      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4791      * <p>
4792      * This method throws no reflective or security exceptions.
4793      * @param type the desired target type
4794      * @return a method handle suitable for invoking any method handle convertible to the given type
4795      * @throws IllegalArgumentException if the resulting method handle's type would have
4796      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4797      */
4798     public static MethodHandle invoker(MethodType type) {
4799         return type.invokers().genericInvoker();
4800     }
4801 
4802     /**
4803      * Produces a special <em>invoker method handle</em> which can be used to
4804      * invoke a signature-polymorphic access mode method on any VarHandle whose
4805      * associated access mode type is compatible with the given type.
4806      * The resulting invoker will have a type which is exactly equal to the
4807      * desired given type, except that it will accept an additional leading
4808      * argument of type {@code VarHandle}.
4809      *
4810      * @param accessMode the VarHandle access mode
4811      * @param type the desired target type
4812      * @return a method handle suitable for invoking an access mode method of
4813      *         any VarHandle whose access mode type is of the given type.
4814      * @since 9
4815      */
4816     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4817         return type.invokers().varHandleMethodExactInvoker(accessMode);
4818     }
4819 
4820     /**
4821      * Produces a special <em>invoker method handle</em> which can be used to
4822      * invoke a signature-polymorphic access mode method on any VarHandle whose
4823      * associated access mode type is compatible with the given type.
4824      * The resulting invoker will have a type which is exactly equal to the
4825      * desired given type, except that it will accept an additional leading
4826      * argument of type {@code VarHandle}.
4827      * <p>
4828      * Before invoking its target, if the access mode type differs from the
4829      * desired given type, the invoker will apply reference casts as necessary
4830      * and box, unbox, or widen primitive values, as if by
4831      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4832      * converted as necessary.
4833      * <p>
4834      * This method is equivalent to the following code (though it may be more
4835      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4836      *
4837      * @param accessMode the VarHandle access mode
4838      * @param type the desired target type
4839      * @return a method handle suitable for invoking an access mode method of
4840      *         any VarHandle whose access mode type is convertible to the given
4841      *         type.
4842      * @since 9
4843      */
4844     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4845         return type.invokers().varHandleMethodInvoker(accessMode);
4846     }
4847 
4848     /*non-public*/
4849     static MethodHandle basicInvoker(MethodType type) {
4850         return type.invokers().basicInvoker();
4851     }
4852 
4853      /// method handle modification (creation from other method handles)
4854 
4855     /**
4856      * Produces a method handle which adapts the type of the
4857      * given method handle to a new type by pairwise argument and return type conversion.
4858      * The original type and new type must have the same number of arguments.
4859      * The resulting method handle is guaranteed to report a type
4860      * which is equal to the desired new type.
4861      * <p>
4862      * If the original type and new type are equal, returns target.
4863      * <p>
4864      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4865      * and some additional conversions are also applied if those conversions fail.
4866      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4867      * if possible, before or instead of any conversions done by {@code asType}:
4868      * <ul>
4869      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4870      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4871      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4872      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4873      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4874      *     (This treatment follows the usage of the bytecode verifier.)
4875      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4876      *     <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}),
4877      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4878      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4879      *     then a Java casting conversion (JLS {@jls 5.5}) is applied.
4880      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4881      *     widening and/or narrowing.)
4882      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4883      *     conversion will be applied at runtime, possibly followed
4884      *     by a Java casting conversion (JLS {@jls 5.5}) on the primitive value,
4885      *     possibly followed by a conversion from byte to boolean by testing
4886      *     the low-order bit.
4887      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4888      *     and if the reference is null at runtime, a zero value is introduced.
4889      * </ul>
4890      * @param target the method handle to invoke after arguments are retyped
4891      * @param newType the expected type of the new method handle
4892      * @return a method handle which delegates to the target after performing
4893      *           any necessary argument conversions, and arranges for any
4894      *           necessary return value conversions
4895      * @throws NullPointerException if either argument is null
4896      * @throws WrongMethodTypeException if the conversion cannot be made
4897      * @see MethodHandle#asType
4898      */
4899     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4900         explicitCastArgumentsChecks(target, newType);
4901         // use the asTypeCache when possible:
4902         MethodType oldType = target.type();
4903         if (oldType == newType)  return target;
4904         if (oldType.explicitCastEquivalentToAsType(newType)) {
4905             return target.asFixedArity().asType(newType);
4906         }
4907         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4908     }
4909 
4910     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4911         if (target.type().parameterCount() != newType.parameterCount()) {
4912             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4913         }
4914     }
4915 
4916     /**
4917      * Produces a method handle which adapts the calling sequence of the
4918      * given method handle to a new type, by reordering the arguments.
4919      * The resulting method handle is guaranteed to report a type
4920      * which is equal to the desired new type.
4921      * <p>
4922      * The given array controls the reordering.
4923      * Call {@code #I} the number of incoming parameters (the value
4924      * {@code newType.parameterCount()}, and call {@code #O} the number
4925      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4926      * Then the length of the reordering array must be {@code #O},
4927      * and each element must be a non-negative number less than {@code #I}.
4928      * For every {@code N} less than {@code #O}, the {@code N}-th
4929      * outgoing argument will be taken from the {@code I}-th incoming
4930      * argument, where {@code I} is {@code reorder[N]}.
4931      * <p>
4932      * No argument or return value conversions are applied.
4933      * The type of each incoming argument, as determined by {@code newType},
4934      * must be identical to the type of the corresponding outgoing parameter
4935      * or parameters in the target method handle.
4936      * The return type of {@code newType} must be identical to the return
4937      * type of the original target.
4938      * <p>
4939      * The reordering array need not specify an actual permutation.
4940      * An incoming argument will be duplicated if its index appears
4941      * more than once in the array, and an incoming argument will be dropped
4942      * if its index does not appear in the array.
4943      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4944      * incoming arguments which are not mentioned in the reordering array
4945      * may be of any type, as determined only by {@code newType}.
4946      * {@snippet lang="java" :
4947 import static java.lang.invoke.MethodHandles.*;
4948 import static java.lang.invoke.MethodType.*;
4949 ...
4950 MethodType intfn1 = methodType(int.class, int.class);
4951 MethodType intfn2 = methodType(int.class, int.class, int.class);
4952 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4953 assert(sub.type().equals(intfn2));
4954 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4955 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4956 assert((int)rsub.invokeExact(1, 100) == 99);
4957 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4958 assert(add.type().equals(intfn2));
4959 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4960 assert(twice.type().equals(intfn1));
4961 assert((int)twice.invokeExact(21) == 42);
4962      * }
4963      * <p>
4964      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4965      * variable-arity method handle}, even if the original target method handle was.
4966      * @param target the method handle to invoke after arguments are reordered
4967      * @param newType the expected type of the new method handle
4968      * @param reorder an index array which controls the reordering
4969      * @return a method handle which delegates to the target after it
4970      *           drops unused arguments and moves and/or duplicates the other arguments
4971      * @throws NullPointerException if any argument is null
4972      * @throws IllegalArgumentException if the index array length is not equal to
4973      *                  the arity of the target, or if any index array element
4974      *                  not a valid index for a parameter of {@code newType},
4975      *                  or if two corresponding parameter types in
4976      *                  {@code target.type()} and {@code newType} are not identical,
4977      */
4978     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4979         reorder = reorder.clone();  // get a private copy
4980         MethodType oldType = target.type();
4981         permuteArgumentChecks(reorder, newType, oldType);
4982         // first detect dropped arguments and handle them separately
4983         int[] originalReorder = reorder;
4984         BoundMethodHandle result = target.rebind();
4985         LambdaForm form = result.form;
4986         int newArity = newType.parameterCount();
4987         // Normalize the reordering into a real permutation,
4988         // by removing duplicates and adding dropped elements.
4989         // This somewhat improves lambda form caching, as well
4990         // as simplifying the transform by breaking it up into steps.
4991         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4992             if (ddIdx > 0) {
4993                 // We found a duplicated entry at reorder[ddIdx].
4994                 // Example:  (x,y,z)->asList(x,y,z)
4995                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4996                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4997                 // The starred element corresponds to the argument
4998                 // deleted by the dupArgumentForm transform.
4999                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
5000                 boolean killFirst = false;
5001                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
5002                     // Set killFirst if the dup is larger than an intervening position.
5003                     // This will remove at least one inversion from the permutation.
5004                     if (dupVal > val) killFirst = true;
5005                 }
5006                 if (!killFirst) {
5007                     srcPos = dstPos;
5008                     dstPos = ddIdx;
5009                 }
5010                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
5011                 assert (reorder[srcPos] == reorder[dstPos]);
5012                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
5013                 // contract the reordering by removing the element at dstPos
5014                 int tailPos = dstPos + 1;
5015                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
5016                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
5017             } else {
5018                 int dropVal = ~ddIdx, insPos = 0;
5019                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
5020                     // Find first element of reorder larger than dropVal.
5021                     // This is where we will insert the dropVal.
5022                     insPos += 1;
5023                 }
5024                 Class<?> ptype = newType.parameterType(dropVal);
5025                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
5026                 oldType = oldType.insertParameterTypes(insPos, ptype);
5027                 // expand the reordering by inserting an element at insPos
5028                 int tailPos = insPos + 1;
5029                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
5030                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
5031                 reorder[insPos] = dropVal;
5032             }
5033             assert (permuteArgumentChecks(reorder, newType, oldType));
5034         }
5035         assert (reorder.length == newArity);  // a perfect permutation
5036         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
5037         form = form.editor().permuteArgumentsForm(1, reorder);
5038         if (newType == result.type() && form == result.internalForm())
5039             return result;
5040         return result.copyWith(newType, form);
5041     }
5042 
5043     /**
5044      * Return an indication of any duplicate or omission in reorder.
5045      * If the reorder contains a duplicate entry, return the index of the second occurrence.
5046      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
5047      * Otherwise, return zero.
5048      * If an element not in [0..newArity-1] is encountered, return reorder.length.
5049      */
5050     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
5051         final int BIT_LIMIT = 63;  // max number of bits in bit mask
5052         if (newArity < BIT_LIMIT) {
5053             long mask = 0;
5054             for (int i = 0; i < reorder.length; i++) {
5055                 int arg = reorder[i];
5056                 if (arg >= newArity) {
5057                     return reorder.length;
5058                 }
5059                 long bit = 1L << arg;
5060                 if ((mask & bit) != 0) {
5061                     return i;  // >0 indicates a dup
5062                 }
5063                 mask |= bit;
5064             }
5065             if (mask == (1L << newArity) - 1) {
5066                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
5067                 return 0;
5068             }
5069             // find first zero
5070             long zeroBit = Long.lowestOneBit(~mask);
5071             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
5072             assert(zeroPos <= newArity);
5073             if (zeroPos == newArity) {
5074                 return 0;
5075             }
5076             return ~zeroPos;
5077         } else {
5078             // same algorithm, different bit set
5079             BitSet mask = new BitSet(newArity);
5080             for (int i = 0; i < reorder.length; i++) {
5081                 int arg = reorder[i];
5082                 if (arg >= newArity) {
5083                     return reorder.length;
5084                 }
5085                 if (mask.get(arg)) {
5086                     return i;  // >0 indicates a dup
5087                 }
5088                 mask.set(arg);
5089             }
5090             int zeroPos = mask.nextClearBit(0);
5091             assert(zeroPos <= newArity);
5092             if (zeroPos == newArity) {
5093                 return 0;
5094             }
5095             return ~zeroPos;
5096         }
5097     }
5098 
5099     static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
5100         if (newType.returnType() != oldType.returnType())
5101             throw newIllegalArgumentException("return types do not match",
5102                     oldType, newType);
5103         if (reorder.length != oldType.parameterCount())
5104             throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
5105                     oldType, Arrays.toString(reorder));
5106 
5107         int limit = newType.parameterCount();
5108         for (int j = 0; j < reorder.length; j++) {
5109             int i = reorder[j];
5110             if (i < 0 || i >= limit) {
5111                 throw newIllegalArgumentException("index is out of bounds for new type",
5112                         i, newType);
5113             }
5114             Class<?> src = newType.parameterType(i);
5115             Class<?> dst = oldType.parameterType(j);
5116             if (src != dst)
5117                 throw newIllegalArgumentException("parameter types do not match after reorder",
5118                         oldType, newType);
5119         }
5120         return true;
5121     }
5122 
5123     /**
5124      * Produces a method handle of the requested return type which returns the given
5125      * constant value every time it is invoked.
5126      * <p>
5127      * Before the method handle is returned, the passed-in value is converted to the requested type.
5128      * If the requested type is primitive, widening primitive conversions are attempted,
5129      * else reference conversions are attempted.
5130      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5131      * @param type the return type of the desired method handle
5132      * @param value the value to return
5133      * @return a method handle of the given return type and no arguments, which always returns the given value
5134      * @throws NullPointerException if the {@code type} argument is null
5135      * @throws ClassCastException if the value cannot be converted to the required return type
5136      * @throws IllegalArgumentException if the given type is {@code void.class}
5137      */
5138     public static MethodHandle constant(Class<?> type, Object value) {
5139         if (type.isPrimitive()) {
5140             if (type == void.class)
5141                 throw newIllegalArgumentException("void type");
5142             Wrapper w = Wrapper.forPrimitiveType(type);
5143             value = w.convert(value, type);
5144             if (w.zero().equals(value))
5145                 return zero(w, type);
5146             return insertArguments(identity(type), 0, value);
5147         } else {
5148             if (value == null)
5149                 return zero(Wrapper.OBJECT, type);
5150             return identity(type).bindTo(value);
5151         }
5152     }
5153 
5154     /**
5155      * Produces a method handle which returns its sole argument when invoked.
5156      * @param type the type of the sole parameter and return value of the desired method handle
5157      * @return a unary method handle which accepts and returns the given type
5158      * @throws NullPointerException if the argument is null
5159      * @throws IllegalArgumentException if the given type is {@code void.class}
5160      */
5161     public static MethodHandle identity(Class<?> type) {
5162         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5163         int pos = btw.ordinal();
5164         MethodHandle ident = IDENTITY_MHS[pos];
5165         if (ident == null) {
5166             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5167         }
5168         if (ident.type().returnType() == type)
5169             return ident;
5170         // something like identity(Foo.class); do not bother to intern these
5171         assert (btw == Wrapper.OBJECT);
5172         return makeIdentity(type);
5173     }
5174 
5175     /**
5176      * Produces a constant method handle of the requested return type which
5177      * returns the default value for that type every time it is invoked.
5178      * The resulting constant method handle will have no side effects.
5179      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5180      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5181      * since {@code explicitCastArguments} converts {@code null} to default values.
5182      * @param type the expected return type of the desired method handle
5183      * @return a constant method handle that takes no arguments
5184      *         and returns the default value of the given type (or void, if the type is void)
5185      * @throws NullPointerException if the argument is null
5186      * @see MethodHandles#constant
5187      * @see MethodHandles#empty
5188      * @see MethodHandles#explicitCastArguments
5189      * @since 9
5190      */
5191     public static MethodHandle zero(Class<?> type) {
5192         Objects.requireNonNull(type);
5193         if (type.isPrimitive()) {
5194             return zero(Wrapper.forPrimitiveType(type), type);
5195         } else {
5196             return zero(Wrapper.OBJECT, type);
5197         }
5198     }
5199 
5200     private static MethodHandle identityOrVoid(Class<?> type) {
5201         return type == void.class ? zero(type) : identity(type);
5202     }
5203 
5204     /**
5205      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5206      * and returns a suitable default depending on the return type.
5207      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
5208      * <p>The returned method handle is equivalent to
5209      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5210      *
5211      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5212      * {@code guardWithTest(pred, target, empty(target.type())}.
5213      * @param type the type of the desired method handle
5214      * @return a constant method handle of the given type, which returns a default value of the given return type
5215      * @throws NullPointerException if the argument is null
5216      * @see MethodHandles#zero
5217      * @see MethodHandles#constant
5218      * @since 9
5219      */
5220     public static  MethodHandle empty(MethodType type) {
5221         Objects.requireNonNull(type);
5222         return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes());
5223     }
5224 
5225     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5226     private static MethodHandle makeIdentity(Class<?> ptype) {
5227         MethodType mtype = methodType(ptype, ptype);
5228         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5229         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5230     }
5231 
5232     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5233         int pos = btw.ordinal();
5234         MethodHandle zero = ZERO_MHS[pos];
5235         if (zero == null) {
5236             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5237         }
5238         if (zero.type().returnType() == rtype)
5239             return zero;
5240         assert(btw == Wrapper.OBJECT);
5241         return makeZero(rtype);
5242     }
5243     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5244     private static MethodHandle makeZero(Class<?> rtype) {
5245         MethodType mtype = methodType(rtype);
5246         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5247         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
5248     }
5249 
5250     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
5251         // Simulate a CAS, to avoid racy duplication of results.
5252         MethodHandle prev = cache[pos];
5253         if (prev != null) return prev;
5254         return cache[pos] = value;
5255     }
5256 
5257     /**
5258      * Provides a target method handle with one or more <em>bound arguments</em>
5259      * in advance of the method handle's invocation.
5260      * The formal parameters to the target corresponding to the bound
5261      * arguments are called <em>bound parameters</em>.
5262      * Returns a new method handle which saves away the bound arguments.
5263      * When it is invoked, it receives arguments for any non-bound parameters,
5264      * binds the saved arguments to their corresponding parameters,
5265      * and calls the original target.
5266      * <p>
5267      * The type of the new method handle will drop the types for the bound
5268      * parameters from the original target type, since the new method handle
5269      * will no longer require those arguments to be supplied by its callers.
5270      * <p>
5271      * Each given argument object must match the corresponding bound parameter type.
5272      * If a bound parameter type is a primitive, the argument object
5273      * must be a wrapper, and will be unboxed to produce the primitive value.
5274      * <p>
5275      * The {@code pos} argument selects which parameters are to be bound.
5276      * It may range between zero and <i>N-L</i> (inclusively),
5277      * where <i>N</i> is the arity of the target method handle
5278      * and <i>L</i> is the length of the values array.
5279      * <p>
5280      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5281      * variable-arity method handle}, even if the original target method handle was.
5282      * @param target the method handle to invoke after the argument is inserted
5283      * @param pos where to insert the argument (zero for the first)
5284      * @param values the series of arguments to insert
5285      * @return a method handle which inserts an additional argument,
5286      *         before calling the original method handle
5287      * @throws NullPointerException if the target or the {@code values} array is null
5288      * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than
5289      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
5290      *         is the length of the values array.
5291      * @throws ClassCastException if an argument does not match the corresponding bound parameter
5292      *         type.
5293      * @see MethodHandle#bindTo
5294      */
5295     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
5296         int insCount = values.length;
5297         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
5298         if (insCount == 0)  return target;
5299         BoundMethodHandle result = target.rebind();
5300         for (int i = 0; i < insCount; i++) {
5301             Object value = values[i];
5302             Class<?> ptype = ptypes[pos+i];
5303             if (ptype.isPrimitive()) {
5304                 result = insertArgumentPrimitive(result, pos, ptype, value);
5305             } else {
5306                 value = ptype.cast(value);  // throw CCE if needed
5307                 result = result.bindArgumentL(pos, value);
5308             }
5309         }
5310         return result;
5311     }
5312 
5313     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5314                                                              Class<?> ptype, Object value) {
5315         Wrapper w = Wrapper.forPrimitiveType(ptype);
5316         // perform unboxing and/or primitive conversion
5317         value = w.convert(value, ptype);
5318         return switch (w) {
5319             case INT    -> result.bindArgumentI(pos, (int) value);
5320             case LONG   -> result.bindArgumentJ(pos, (long) value);
5321             case FLOAT  -> result.bindArgumentF(pos, (float) value);
5322             case DOUBLE -> result.bindArgumentD(pos, (double) value);
5323             default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5324         };
5325     }
5326 
5327     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5328         MethodType oldType = target.type();
5329         int outargs = oldType.parameterCount();
5330         int inargs  = outargs - insCount;
5331         if (inargs < 0)
5332             throw newIllegalArgumentException("too many values to insert");
5333         if (pos < 0 || pos > inargs)
5334             throw newIllegalArgumentException("no argument type to append");
5335         return oldType.ptypes();
5336     }
5337 
5338     /**
5339      * Produces a method handle which will discard some dummy arguments
5340      * before calling some other specified <i>target</i> method handle.
5341      * The type of the new method handle will be the same as the target's type,
5342      * except it will also include the dummy argument types,
5343      * at some given position.
5344      * <p>
5345      * The {@code pos} argument may range between zero and <i>N</i>,
5346      * where <i>N</i> is the arity of the target.
5347      * If {@code pos} is zero, the dummy arguments will precede
5348      * the target's real arguments; if {@code pos} is <i>N</i>
5349      * they will come after.
5350      * <p>
5351      * <b>Example:</b>
5352      * {@snippet lang="java" :
5353 import static java.lang.invoke.MethodHandles.*;
5354 import static java.lang.invoke.MethodType.*;
5355 ...
5356 MethodHandle cat = lookup().findVirtual(String.class,
5357   "concat", methodType(String.class, String.class));
5358 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5359 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5360 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5361 assertEquals(bigType, d0.type());
5362 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5363      * }
5364      * <p>
5365      * This method is also equivalent to the following code:
5366      * <blockquote><pre>
5367      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5368      * </pre></blockquote>
5369      * @param target the method handle to invoke after the arguments are dropped
5370      * @param pos position of first argument to drop (zero for the leftmost)
5371      * @param valueTypes the type(s) of the argument(s) to drop
5372      * @return a method handle which drops arguments of the given types,
5373      *         before calling the original method handle
5374      * @throws NullPointerException if the target is null,
5375      *                              or if the {@code valueTypes} list or any of its elements is null
5376      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5377      *                  or if {@code pos} is negative or greater than the arity of the target,
5378      *                  or if the new method handle's type would have too many parameters
5379      */
5380     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5381         return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone());
5382     }
5383 
5384     static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) {
5385         MethodType oldType = target.type();  // get NPE
5386         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5387         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5388         if (dropped == 0)  return target;
5389         BoundMethodHandle result = target.rebind();
5390         LambdaForm lform = result.form;
5391         int insertFormArg = 1 + pos;
5392         for (Class<?> ptype : valueTypes) {
5393             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5394         }
5395         result = result.copyWith(newType, lform);
5396         return result;
5397     }
5398 
5399     private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) {
5400         int dropped = valueTypes.length;
5401         MethodType.checkSlotCount(dropped);
5402         int outargs = oldType.parameterCount();
5403         int inargs  = outargs + dropped;
5404         if (pos < 0 || pos > outargs)
5405             throw newIllegalArgumentException("no argument type to remove"
5406                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5407                     );
5408         return dropped;
5409     }
5410 
5411     /**
5412      * Produces a method handle which will discard some dummy arguments
5413      * before calling some other specified <i>target</i> method handle.
5414      * The type of the new method handle will be the same as the target's type,
5415      * except it will also include the dummy argument types,
5416      * at some given position.
5417      * <p>
5418      * The {@code pos} argument may range between zero and <i>N</i>,
5419      * where <i>N</i> is the arity of the target.
5420      * If {@code pos} is zero, the dummy arguments will precede
5421      * the target's real arguments; if {@code pos} is <i>N</i>
5422      * they will come after.
5423      * @apiNote
5424      * {@snippet lang="java" :
5425 import static java.lang.invoke.MethodHandles.*;
5426 import static java.lang.invoke.MethodType.*;
5427 ...
5428 MethodHandle cat = lookup().findVirtual(String.class,
5429   "concat", methodType(String.class, String.class));
5430 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5431 MethodHandle d0 = dropArguments(cat, 0, String.class);
5432 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5433 MethodHandle d1 = dropArguments(cat, 1, String.class);
5434 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5435 MethodHandle d2 = dropArguments(cat, 2, String.class);
5436 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5437 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5438 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5439      * }
5440      * <p>
5441      * This method is also equivalent to the following code:
5442      * <blockquote><pre>
5443      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5444      * </pre></blockquote>
5445      * @param target the method handle to invoke after the arguments are dropped
5446      * @param pos position of first argument to drop (zero for the leftmost)
5447      * @param valueTypes the type(s) of the argument(s) to drop
5448      * @return a method handle which drops arguments of the given types,
5449      *         before calling the original method handle
5450      * @throws NullPointerException if the target is null,
5451      *                              or if the {@code valueTypes} array or any of its elements is null
5452      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5453      *                  or if {@code pos} is negative or greater than the arity of the target,
5454      *                  or if the new method handle's type would have
5455      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
5456      */
5457     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5458         return dropArgumentsTrusted(target, pos, valueTypes.clone());
5459     }
5460 
5461     /* Convenience overloads for trusting internal low-arity call-sites */
5462     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) {
5463         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 });
5464     }
5465     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) {
5466         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 });
5467     }
5468 
5469     // private version which allows caller some freedom with error handling
5470     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos,
5471                                       boolean nullOnFailure) {
5472         Class<?>[] oldTypes = target.type().ptypes();
5473         int match = oldTypes.length;
5474         if (skip != 0) {
5475             if (skip < 0 || skip > match) {
5476                 throw newIllegalArgumentException("illegal skip", skip, target);
5477             }
5478             oldTypes = Arrays.copyOfRange(oldTypes, skip, match);
5479             match -= skip;
5480         }
5481         Class<?>[] addTypes = newTypes;
5482         int add = addTypes.length;
5483         if (pos != 0) {
5484             if (pos < 0 || pos > add) {
5485                 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes));
5486             }
5487             addTypes = Arrays.copyOfRange(addTypes, pos, add);
5488             add -= pos;
5489             assert(addTypes.length == add);
5490         }
5491         // Do not add types which already match the existing arguments.
5492         if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) {
5493             if (nullOnFailure) {
5494                 return null;
5495             }
5496             throw newIllegalArgumentException("argument lists do not match",
5497                 Arrays.toString(oldTypes), Arrays.toString(newTypes));
5498         }
5499         addTypes = Arrays.copyOfRange(addTypes, match, add);
5500         add -= match;
5501         assert(addTypes.length == add);
5502         // newTypes:     (   P*[pos], M*[match], A*[add] )
5503         // target: ( S*[skip],        M*[match]  )
5504         MethodHandle adapter = target;
5505         if (add > 0) {
5506             adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes);
5507         }
5508         // adapter: (S*[skip],        M*[match], A*[add] )
5509         if (pos > 0) {
5510             adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos));
5511         }
5512         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5513         return adapter;
5514     }
5515 
5516     /**
5517      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5518      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5519      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5520      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5521      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5522      * {@link #dropArguments(MethodHandle, int, Class[])}.
5523      * <p>
5524      * The resulting handle will have the same return type as the target handle.
5525      * <p>
5526      * In more formal terms, assume these two type lists:<ul>
5527      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5528      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5529      * {@code newTypes}.
5530      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5531      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5532      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5533      * sub-list.
5534      * </ul>
5535      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5536      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5537      * {@link #dropArguments(MethodHandle, int, Class[])}.
5538      *
5539      * @apiNote
5540      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5541      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5542      * {@snippet lang="java" :
5543 import static java.lang.invoke.MethodHandles.*;
5544 import static java.lang.invoke.MethodType.*;
5545 ...
5546 ...
5547 MethodHandle h0 = constant(boolean.class, true);
5548 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5549 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5550 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5551 if (h1.type().parameterCount() < h2.type().parameterCount())
5552     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5553 else
5554     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5555 MethodHandle h3 = guardWithTest(h0, h1, h2);
5556 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5557      * }
5558      * @param target the method handle to adapt
5559      * @param skip number of targets parameters to disregard (they will be unchanged)
5560      * @param newTypes the list of types to match {@code target}'s parameter type list to
5561      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5562      * @return a possibly adapted method handle
5563      * @throws NullPointerException if either argument is null
5564      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5565      *         or if {@code skip} is negative or greater than the arity of the target,
5566      *         or if {@code pos} is negative or greater than the newTypes list size,
5567      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5568      *         {@code pos}.
5569      * @since 9
5570      */
5571     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5572         Objects.requireNonNull(target);
5573         Objects.requireNonNull(newTypes);
5574         return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false);
5575     }
5576 
5577     /**
5578      * Drop the return value of the target handle (if any).
5579      * The returned method handle will have a {@code void} return type.
5580      *
5581      * @param target the method handle to adapt
5582      * @return a possibly adapted method handle
5583      * @throws NullPointerException if {@code target} is null
5584      * @since 16
5585      */
5586     public static MethodHandle dropReturn(MethodHandle target) {
5587         Objects.requireNonNull(target);
5588         MethodType oldType = target.type();
5589         Class<?> oldReturnType = oldType.returnType();
5590         if (oldReturnType == void.class)
5591             return target;
5592         MethodType newType = oldType.changeReturnType(void.class);
5593         BoundMethodHandle result = target.rebind();
5594         LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5595         result = result.copyWith(newType, lform);
5596         return result;
5597     }
5598 
5599     /**
5600      * Adapts a target method handle by pre-processing
5601      * one or more of its arguments, each with its own unary filter function,
5602      * and then calling the target with each pre-processed argument
5603      * replaced by the result of its corresponding filter function.
5604      * <p>
5605      * The pre-processing is performed by one or more method handles,
5606      * specified in the elements of the {@code filters} array.
5607      * The first element of the filter array corresponds to the {@code pos}
5608      * argument of the target, and so on in sequence.
5609      * The filter functions are invoked in left to right order.
5610      * <p>
5611      * Null arguments in the array are treated as identity functions,
5612      * and the corresponding arguments left unchanged.
5613      * (If there are no non-null elements in the array, the original target is returned.)
5614      * Each filter is applied to the corresponding argument of the adapter.
5615      * <p>
5616      * If a filter {@code F} applies to the {@code N}th argument of
5617      * the target, then {@code F} must be a method handle which
5618      * takes exactly one argument.  The type of {@code F}'s sole argument
5619      * replaces the corresponding argument type of the target
5620      * in the resulting adapted method handle.
5621      * The return type of {@code F} must be identical to the corresponding
5622      * parameter type of the target.
5623      * <p>
5624      * It is an error if there are elements of {@code filters}
5625      * (null or not)
5626      * which do not correspond to argument positions in the target.
5627      * <p><b>Example:</b>
5628      * {@snippet lang="java" :
5629 import static java.lang.invoke.MethodHandles.*;
5630 import static java.lang.invoke.MethodType.*;
5631 ...
5632 MethodHandle cat = lookup().findVirtual(String.class,
5633   "concat", methodType(String.class, String.class));
5634 MethodHandle upcase = lookup().findVirtual(String.class,
5635   "toUpperCase", methodType(String.class));
5636 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5637 MethodHandle f0 = filterArguments(cat, 0, upcase);
5638 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5639 MethodHandle f1 = filterArguments(cat, 1, upcase);
5640 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5641 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5642 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5643      * }
5644      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5645      * denotes the return type of both the {@code target} and resulting adapter.
5646      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5647      * of the parameters and arguments that precede and follow the filter position
5648      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5649      * values of the filtered parameters and arguments; they also represent the
5650      * return types of the {@code filter[i]} handles. The latter accept arguments
5651      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5652      * the resulting adapter.
5653      * {@snippet lang="java" :
5654      * T target(P... p, A[i]... a[i], B... b);
5655      * A[i] filter[i](V[i]);
5656      * T adapter(P... p, V[i]... v[i], B... b) {
5657      *   return target(p..., filter[i](v[i])..., b...);
5658      * }
5659      * }
5660      * <p>
5661      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5662      * variable-arity method handle}, even if the original target method handle was.
5663      *
5664      * @param target the method handle to invoke after arguments are filtered
5665      * @param pos the position of the first argument to filter
5666      * @param filters method handles to call initially on filtered arguments
5667      * @return method handle which incorporates the specified argument filtering logic
5668      * @throws NullPointerException if the target is null
5669      *                              or if the {@code filters} array is null
5670      * @throws IllegalArgumentException if a non-null element of {@code filters}
5671      *          does not match a corresponding argument type of target as described above,
5672      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5673      *          or if the resulting method handle's type would have
5674      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5675      */
5676     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5677         // In method types arguments start at index 0, while the LF
5678         // editor have the MH receiver at position 0 - adjust appropriately.
5679         final int MH_RECEIVER_OFFSET = 1;
5680         filterArgumentsCheckArity(target, pos, filters);
5681         MethodHandle adapter = target;
5682 
5683         // keep track of currently matched filters, as to optimize repeated filters
5684         int index = 0;
5685         int[] positions = new int[filters.length];
5686         MethodHandle filter = null;
5687 
5688         // process filters in reverse order so that the invocation of
5689         // the resulting adapter will invoke the filters in left-to-right order
5690         for (int i = filters.length - 1; i >= 0; --i) {
5691             MethodHandle newFilter = filters[i];
5692             if (newFilter == null) continue;  // ignore null elements of filters
5693 
5694             // flush changes on update
5695             if (filter != newFilter) {
5696                 if (filter != null) {
5697                     if (index > 1) {
5698                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5699                     } else {
5700                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5701                     }
5702                 }
5703                 filter = newFilter;
5704                 index = 0;
5705             }
5706 
5707             filterArgumentChecks(target, pos + i, newFilter);
5708             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5709         }
5710         if (index > 1) {
5711             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5712         } else if (index == 1) {
5713             adapter = filterArgument(adapter, positions[0] - 1, filter);
5714         }
5715         return adapter;
5716     }
5717 
5718     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5719         MethodType targetType = adapter.type();
5720         MethodType filterType = filter.type();
5721         BoundMethodHandle result = adapter.rebind();
5722         Class<?> newParamType = filterType.parameterType(0);
5723 
5724         Class<?>[] ptypes = targetType.ptypes().clone();
5725         for (int pos : positions) {
5726             ptypes[pos - 1] = newParamType;
5727         }
5728         MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true);
5729 
5730         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5731         return result.copyWithExtendL(newType, lform, filter);
5732     }
5733 
5734     /*non-public*/
5735     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5736         filterArgumentChecks(target, pos, filter);
5737         MethodType targetType = target.type();
5738         MethodType filterType = filter.type();
5739         BoundMethodHandle result = target.rebind();
5740         Class<?> newParamType = filterType.parameterType(0);
5741         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5742         MethodType newType = targetType.changeParameterType(pos, newParamType);
5743         result = result.copyWithExtendL(newType, lform, filter);
5744         return result;
5745     }
5746 
5747     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5748         MethodType targetType = target.type();
5749         int maxPos = targetType.parameterCount();
5750         if (pos + filters.length > maxPos)
5751             throw newIllegalArgumentException("too many filters");
5752     }
5753 
5754     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5755         MethodType targetType = target.type();
5756         MethodType filterType = filter.type();
5757         if (filterType.parameterCount() != 1
5758             || filterType.returnType() != targetType.parameterType(pos))
5759             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5760     }
5761 
5762     /**
5763      * Adapts a target method handle by pre-processing
5764      * a sub-sequence of its arguments with a filter (another method handle).
5765      * The pre-processed arguments are replaced by the result (if any) of the
5766      * filter function.
5767      * The target is then called on the modified (usually shortened) argument list.
5768      * <p>
5769      * If the filter returns a value, the target must accept that value as
5770      * its argument in position {@code pos}, preceded and/or followed by
5771      * any arguments not passed to the filter.
5772      * If the filter returns void, the target must accept all arguments
5773      * not passed to the filter.
5774      * No arguments are reordered, and a result returned from the filter
5775      * replaces (in order) the whole subsequence of arguments originally
5776      * passed to the adapter.
5777      * <p>
5778      * The argument types (if any) of the filter
5779      * replace zero or one argument types of the target, at position {@code pos},
5780      * in the resulting adapted method handle.
5781      * The return type of the filter (if any) must be identical to the
5782      * argument type of the target at position {@code pos}, and that target argument
5783      * is supplied by the return value of the filter.
5784      * <p>
5785      * In all cases, {@code pos} must be greater than or equal to zero, and
5786      * {@code pos} must also be less than or equal to the target's arity.
5787      * <p><b>Example:</b>
5788      * {@snippet lang="java" :
5789 import static java.lang.invoke.MethodHandles.*;
5790 import static java.lang.invoke.MethodType.*;
5791 ...
5792 MethodHandle deepToString = publicLookup()
5793   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5794 
5795 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5796 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5797 
5798 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5799 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5800 
5801 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5802 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5803 assertEquals("[top, [up, down], strange]",
5804              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5805 
5806 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5807 assertEquals("[top, [up, down], [strange]]",
5808              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5809 
5810 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5811 assertEquals("[top, [[up, down, strange], charm], bottom]",
5812              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5813      * }
5814      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5815      * represents the return type of the {@code target} and resulting adapter.
5816      * {@code V}/{@code v} stand for the return type and value of the
5817      * {@code filter}, which are also found in the signature and arguments of
5818      * the {@code target}, respectively, unless {@code V} is {@code void}.
5819      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5820      * and values preceding and following the collection position, {@code pos},
5821      * in the {@code target}'s signature. They also turn up in the resulting
5822      * adapter's signature and arguments, where they surround
5823      * {@code B}/{@code b}, which represent the parameter types and arguments
5824      * to the {@code filter} (if any).
5825      * {@snippet lang="java" :
5826      * T target(A...,V,C...);
5827      * V filter(B...);
5828      * T adapter(A... a,B... b,C... c) {
5829      *   V v = filter(b...);
5830      *   return target(a...,v,c...);
5831      * }
5832      * // and if the filter has no arguments:
5833      * T target2(A...,V,C...);
5834      * V filter2();
5835      * T adapter2(A... a,C... c) {
5836      *   V v = filter2();
5837      *   return target2(a...,v,c...);
5838      * }
5839      * // and if the filter has a void return:
5840      * T target3(A...,C...);
5841      * void filter3(B...);
5842      * T adapter3(A... a,B... b,C... c) {
5843      *   filter3(b...);
5844      *   return target3(a...,c...);
5845      * }
5846      * }
5847      * <p>
5848      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5849      * one which first "folds" the affected arguments, and then drops them, in separate
5850      * steps as follows:
5851      * {@snippet lang="java" :
5852      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5853      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5854      * }
5855      * If the target method handle consumes no arguments besides than the result
5856      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5857      * is equivalent to {@code filterReturnValue(coll, mh)}.
5858      * If the filter method handle {@code coll} consumes one argument and produces
5859      * a non-void result, then {@code collectArguments(mh, N, coll)}
5860      * is equivalent to {@code filterArguments(mh, N, coll)}.
5861      * Other equivalences are possible but would require argument permutation.
5862      * <p>
5863      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5864      * variable-arity method handle}, even if the original target method handle was.
5865      *
5866      * @param target the method handle to invoke after filtering the subsequence of arguments
5867      * @param pos the position of the first adapter argument to pass to the filter,
5868      *            and/or the target argument which receives the result of the filter
5869      * @param filter method handle to call on the subsequence of arguments
5870      * @return method handle which incorporates the specified argument subsequence filtering logic
5871      * @throws NullPointerException if either argument is null
5872      * @throws IllegalArgumentException if the return type of {@code filter}
5873      *          is non-void and is not the same as the {@code pos} argument of the target,
5874      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5875      *          or if the resulting method handle's type would have
5876      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5877      * @see MethodHandles#foldArguments
5878      * @see MethodHandles#filterArguments
5879      * @see MethodHandles#filterReturnValue
5880      */
5881     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5882         MethodType newType = collectArgumentsChecks(target, pos, filter);
5883         MethodType collectorType = filter.type();
5884         BoundMethodHandle result = target.rebind();
5885         LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5886         return result.copyWithExtendL(newType, lform, filter);
5887     }
5888 
5889     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5890         MethodType targetType = target.type();
5891         MethodType filterType = filter.type();
5892         Class<?> rtype = filterType.returnType();
5893         Class<?>[] filterArgs = filterType.ptypes();
5894         if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5895                        (rtype != void.class && pos >= targetType.parameterCount())) {
5896             throw newIllegalArgumentException("position is out of range for target", target, pos);
5897         }
5898         if (rtype == void.class) {
5899             return targetType.insertParameterTypes(pos, filterArgs);
5900         }
5901         if (rtype != targetType.parameterType(pos)) {
5902             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5903         }
5904         return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs);
5905     }
5906 
5907     /**
5908      * Adapts a target method handle by post-processing
5909      * its return value (if any) with a filter (another method handle).
5910      * The result of the filter is returned from the adapter.
5911      * <p>
5912      * If the target returns a value, the filter must accept that value as
5913      * its only argument.
5914      * If the target returns void, the filter must accept no arguments.
5915      * <p>
5916      * The return type of the filter
5917      * replaces the return type of the target
5918      * in the resulting adapted method handle.
5919      * The argument type of the filter (if any) must be identical to the
5920      * return type of the target.
5921      * <p><b>Example:</b>
5922      * {@snippet lang="java" :
5923 import static java.lang.invoke.MethodHandles.*;
5924 import static java.lang.invoke.MethodType.*;
5925 ...
5926 MethodHandle cat = lookup().findVirtual(String.class,
5927   "concat", methodType(String.class, String.class));
5928 MethodHandle length = lookup().findVirtual(String.class,
5929   "length", methodType(int.class));
5930 System.out.println((String) cat.invokeExact("x", "y")); // xy
5931 MethodHandle f0 = filterReturnValue(cat, length);
5932 System.out.println((int) f0.invokeExact("x", "y")); // 2
5933      * }
5934      * <p>Here is pseudocode for the resulting adapter. In the code,
5935      * {@code T}/{@code t} represent the result type and value of the
5936      * {@code target}; {@code V}, the result type of the {@code filter}; and
5937      * {@code A}/{@code a}, the types and values of the parameters and arguments
5938      * of the {@code target} as well as the resulting adapter.
5939      * {@snippet lang="java" :
5940      * T target(A...);
5941      * V filter(T);
5942      * V adapter(A... a) {
5943      *   T t = target(a...);
5944      *   return filter(t);
5945      * }
5946      * // and if the target has a void return:
5947      * void target2(A...);
5948      * V filter2();
5949      * V adapter2(A... a) {
5950      *   target2(a...);
5951      *   return filter2();
5952      * }
5953      * // and if the filter has a void return:
5954      * T target3(A...);
5955      * void filter3(V);
5956      * void adapter3(A... a) {
5957      *   T t = target3(a...);
5958      *   filter3(t);
5959      * }
5960      * }
5961      * <p>
5962      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5963      * variable-arity method handle}, even if the original target method handle was.
5964      * @param target the method handle to invoke before filtering the return value
5965      * @param filter method handle to call on the return value
5966      * @return method handle which incorporates the specified return value filtering logic
5967      * @throws NullPointerException if either argument is null
5968      * @throws IllegalArgumentException if the argument list of {@code filter}
5969      *          does not match the return type of target as described above
5970      */
5971     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5972         MethodType targetType = target.type();
5973         MethodType filterType = filter.type();
5974         filterReturnValueChecks(targetType, filterType);
5975         BoundMethodHandle result = target.rebind();
5976         BasicType rtype = BasicType.basicType(filterType.returnType());
5977         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5978         MethodType newType = targetType.changeReturnType(filterType.returnType());
5979         result = result.copyWithExtendL(newType, lform, filter);
5980         return result;
5981     }
5982 
5983     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5984         Class<?> rtype = targetType.returnType();
5985         int filterValues = filterType.parameterCount();
5986         if (filterValues == 0
5987                 ? (rtype != void.class)
5988                 : (rtype != filterType.parameterType(0) || filterValues != 1))
5989             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5990     }
5991 
5992     /**
5993      * Filter the return value of a target method handle with a filter function. The filter function is
5994      * applied to the return value of the original handle; if the filter specifies more than one parameters,
5995      * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5996      * as follows:
5997      * {@snippet lang="java" :
5998      * T target(A...)
5999      * V filter(B... , T)
6000      * V adapter(A... a, B... b) {
6001      *     T t = target(a...);
6002      *     return filter(b..., t);
6003      * }
6004      * }
6005      * <p>
6006      * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
6007      *
6008      * @param target the target method handle
6009      * @param filter the filter method handle
6010      * @return the adapter method handle
6011      */
6012     /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
6013         MethodType targetType = target.type();
6014         MethodType filterType = filter.type();
6015         BoundMethodHandle result = target.rebind();
6016         LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
6017         MethodType newType = targetType.changeReturnType(filterType.returnType());
6018         if (filterType.parameterCount() > 1) {
6019             for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
6020                 newType = newType.appendParameterTypes(filterType.parameterType(i));
6021             }
6022         }
6023         result = result.copyWithExtendL(newType, lform, filter);
6024         return result;
6025     }
6026 
6027     /**
6028      * Adapts a target method handle by pre-processing
6029      * some of its arguments, and then calling the target with
6030      * the result of the pre-processing, inserted into the original
6031      * sequence of arguments.
6032      * <p>
6033      * The pre-processing is performed by {@code combiner}, a second method handle.
6034      * Of the arguments passed to the adapter, the first {@code N} arguments
6035      * are copied to the combiner, which is then called.
6036      * (Here, {@code N} is defined as the parameter count of the combiner.)
6037      * After this, control passes to the target, with any result
6038      * from the combiner inserted before the original {@code N} incoming
6039      * arguments.
6040      * <p>
6041      * If the combiner returns a value, the first parameter type of the target
6042      * must be identical with the return type of the combiner, and the next
6043      * {@code N} parameter types of the target must exactly match the parameters
6044      * of the combiner.
6045      * <p>
6046      * If the combiner has a void return, no result will be inserted,
6047      * and the first {@code N} parameter types of the target
6048      * must exactly match the parameters of the combiner.
6049      * <p>
6050      * The resulting adapter is the same type as the target, except that the
6051      * first parameter type is dropped,
6052      * if it corresponds to the result of the combiner.
6053      * <p>
6054      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
6055      * that either the combiner or the target does not wish to receive.
6056      * If some of the incoming arguments are destined only for the combiner,
6057      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
6058      * arguments will not need to be live on the stack on entry to the
6059      * target.)
6060      * <p><b>Example:</b>
6061      * {@snippet lang="java" :
6062 import static java.lang.invoke.MethodHandles.*;
6063 import static java.lang.invoke.MethodType.*;
6064 ...
6065 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6066   "println", methodType(void.class, String.class))
6067     .bindTo(System.out);
6068 MethodHandle cat = lookup().findVirtual(String.class,
6069   "concat", methodType(String.class, String.class));
6070 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6071 MethodHandle catTrace = foldArguments(cat, trace);
6072 // also prints "boo":
6073 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6074      * }
6075      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6076      * represents the result type of the {@code target} and resulting adapter.
6077      * {@code V}/{@code v} represent the type and value of the parameter and argument
6078      * of {@code target} that precedes the folding position; {@code V} also is
6079      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6080      * types and values of the {@code N} parameters and arguments at the folding
6081      * position. {@code B}/{@code b} represent the types and values of the
6082      * {@code target} parameters and arguments that follow the folded parameters
6083      * and arguments.
6084      * {@snippet lang="java" :
6085      * // there are N arguments in A...
6086      * T target(V, A[N]..., B...);
6087      * V combiner(A...);
6088      * T adapter(A... a, B... b) {
6089      *   V v = combiner(a...);
6090      *   return target(v, a..., b...);
6091      * }
6092      * // and if the combiner has a void return:
6093      * T target2(A[N]..., B...);
6094      * void combiner2(A...);
6095      * T adapter2(A... a, B... b) {
6096      *   combiner2(a...);
6097      *   return target2(a..., b...);
6098      * }
6099      * }
6100      * <p>
6101      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6102      * variable-arity method handle}, even if the original target method handle was.
6103      * @param target the method handle to invoke after arguments are combined
6104      * @param combiner method handle to call initially on the incoming arguments
6105      * @return method handle which incorporates the specified argument folding logic
6106      * @throws NullPointerException if either argument is null
6107      * @throws IllegalArgumentException if {@code combiner}'s return type
6108      *          is non-void and not the same as the first argument type of
6109      *          the target, or if the initial {@code N} argument types
6110      *          of the target
6111      *          (skipping one matching the {@code combiner}'s return type)
6112      *          are not identical with the argument types of {@code combiner}
6113      */
6114     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
6115         return foldArguments(target, 0, combiner);
6116     }
6117 
6118     /**
6119      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
6120      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
6121      * before the folded arguments.
6122      * <p>
6123      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
6124      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
6125      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
6126      * 0.
6127      *
6128      * @apiNote Example:
6129      * {@snippet lang="java" :
6130     import static java.lang.invoke.MethodHandles.*;
6131     import static java.lang.invoke.MethodType.*;
6132     ...
6133     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6134     "println", methodType(void.class, String.class))
6135     .bindTo(System.out);
6136     MethodHandle cat = lookup().findVirtual(String.class,
6137     "concat", methodType(String.class, String.class));
6138     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6139     MethodHandle catTrace = foldArguments(cat, 1, trace);
6140     // also prints "jum":
6141     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6142      * }
6143      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6144      * represents the result type of the {@code target} and resulting adapter.
6145      * {@code V}/{@code v} represent the type and value of the parameter and argument
6146      * of {@code target} that precedes the folding position; {@code V} also is
6147      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6148      * types and values of the {@code N} parameters and arguments at the folding
6149      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
6150      * and values of the {@code target} parameters and arguments that precede and
6151      * follow the folded parameters and arguments starting at {@code pos},
6152      * respectively.
6153      * {@snippet lang="java" :
6154      * // there are N arguments in A...
6155      * T target(Z..., V, A[N]..., B...);
6156      * V combiner(A...);
6157      * T adapter(Z... z, A... a, B... b) {
6158      *   V v = combiner(a...);
6159      *   return target(z..., v, a..., b...);
6160      * }
6161      * // and if the combiner has a void return:
6162      * T target2(Z..., A[N]..., B...);
6163      * void combiner2(A...);
6164      * T adapter2(Z... z, A... a, B... b) {
6165      *   combiner2(a...);
6166      *   return target2(z..., a..., b...);
6167      * }
6168      * }
6169      * <p>
6170      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6171      * variable-arity method handle}, even if the original target method handle was.
6172      *
6173      * @param target the method handle to invoke after arguments are combined
6174      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
6175      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6176      * @param combiner method handle to call initially on the incoming arguments
6177      * @return method handle which incorporates the specified argument folding logic
6178      * @throws NullPointerException if either argument is null
6179      * @throws IllegalArgumentException if either of the following two conditions holds:
6180      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6181      *              {@code pos} of the target signature;
6182      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
6183      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
6184      *
6185      * @see #foldArguments(MethodHandle, MethodHandle)
6186      * @since 9
6187      */
6188     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
6189         MethodType targetType = target.type();
6190         MethodType combinerType = combiner.type();
6191         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
6192         BoundMethodHandle result = target.rebind();
6193         boolean dropResult = rtype == void.class;
6194         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
6195         MethodType newType = targetType;
6196         if (!dropResult) {
6197             newType = newType.dropParameterTypes(pos, pos + 1);
6198         }
6199         result = result.copyWithExtendL(newType, lform, combiner);
6200         return result;
6201     }
6202 
6203     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
6204         int foldArgs   = combinerType.parameterCount();
6205         Class<?> rtype = combinerType.returnType();
6206         int foldVals = rtype == void.class ? 0 : 1;
6207         int afterInsertPos = foldPos + foldVals;
6208         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
6209         if (ok) {
6210             for (int i = 0; i < foldArgs; i++) {
6211                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
6212                     ok = false;
6213                     break;
6214                 }
6215             }
6216         }
6217         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
6218             ok = false;
6219         if (!ok)
6220             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6221         return rtype;
6222     }
6223 
6224     /**
6225      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
6226      * of the pre-processing replacing the argument at the given position.
6227      *
6228      * @param target the method handle to invoke after arguments are combined
6229      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6230      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6231      * @param combiner method handle to call initially on the incoming arguments
6232      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6233      * @return method handle which incorporates the specified argument folding logic
6234      * @throws NullPointerException if either argument is null
6235      * @throws IllegalArgumentException if either of the following two conditions holds:
6236      *          (1) {@code combiner}'s return type is not the same as the argument type at position
6237      *              {@code pos} of the target signature;
6238      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
6239      *              not identical with the argument types of {@code combiner}.
6240      */
6241     /*non-public*/
6242     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6243         return argumentsWithCombiner(true, target, position, combiner, argPositions);
6244     }
6245 
6246     /**
6247      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
6248      * the pre-processing inserted into the original sequence of arguments at the given position.
6249      *
6250      * @param target the method handle to invoke after arguments are combined
6251      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6252      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6253      * @param combiner method handle to call initially on the incoming arguments
6254      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6255      * @return method handle which incorporates the specified argument folding logic
6256      * @throws NullPointerException if either argument is null
6257      * @throws IllegalArgumentException if either of the following two conditions holds:
6258      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6259      *              {@code pos} of the target signature;
6260      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
6261      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
6262      *              with the argument types of {@code combiner}.
6263      */
6264     /*non-public*/
6265     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6266         return argumentsWithCombiner(false, target, position, combiner, argPositions);
6267     }
6268 
6269     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6270         MethodType targetType = target.type();
6271         MethodType combinerType = combiner.type();
6272         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
6273         BoundMethodHandle result = target.rebind();
6274 
6275         MethodType newType = targetType;
6276         LambdaForm lform;
6277         if (filter) {
6278             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
6279         } else {
6280             boolean dropResult = rtype == void.class;
6281             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
6282             if (!dropResult) {
6283                 newType = newType.dropParameterTypes(position, position + 1);
6284             }
6285         }
6286         result = result.copyWithExtendL(newType, lform, combiner);
6287         return result;
6288     }
6289 
6290     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
6291         int combinerArgs = combinerType.parameterCount();
6292         if (argPos.length != combinerArgs) {
6293             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
6294         }
6295         Class<?> rtype = combinerType.returnType();
6296 
6297         for (int i = 0; i < combinerArgs; i++) {
6298             int arg = argPos[i];
6299             if (arg < 0 || arg > targetType.parameterCount()) {
6300                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
6301             }
6302             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
6303                 throw newIllegalArgumentException("target argument type at position " + arg
6304                         + " must match combiner argument type at index " + i + ": " + targetType
6305                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6306             }
6307         }
6308         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6309             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6310         }
6311         return rtype;
6312     }
6313 
6314     /**
6315      * Makes a method handle which adapts a target method handle,
6316      * by guarding it with a test, a boolean-valued method handle.
6317      * If the guard fails, a fallback handle is called instead.
6318      * All three method handles must have the same corresponding
6319      * argument and return types, except that the return type
6320      * of the test must be boolean, and the test is allowed
6321      * to have fewer arguments than the other two method handles.
6322      * <p>
6323      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6324      * represents the uniform result type of the three involved handles;
6325      * {@code A}/{@code a}, the types and values of the {@code target}
6326      * parameters and arguments that are consumed by the {@code test}; and
6327      * {@code B}/{@code b}, those types and values of the {@code target}
6328      * parameters and arguments that are not consumed by the {@code test}.
6329      * {@snippet lang="java" :
6330      * boolean test(A...);
6331      * T target(A...,B...);
6332      * T fallback(A...,B...);
6333      * T adapter(A... a,B... b) {
6334      *   if (test(a...))
6335      *     return target(a..., b...);
6336      *   else
6337      *     return fallback(a..., b...);
6338      * }
6339      * }
6340      * Note that the test arguments ({@code a...} in the pseudocode) cannot
6341      * be modified by execution of the test, and so are passed unchanged
6342      * from the caller to the target or fallback as appropriate.
6343      * @param test method handle used for test, must return boolean
6344      * @param target method handle to call if test passes
6345      * @param fallback method handle to call if test fails
6346      * @return method handle which incorporates the specified if/then/else logic
6347      * @throws NullPointerException if any argument is null
6348      * @throws IllegalArgumentException if {@code test} does not return boolean,
6349      *          or if all three method types do not match (with the return
6350      *          type of {@code test} changed to match that of the target).
6351      */
6352     public static MethodHandle guardWithTest(MethodHandle test,
6353                                MethodHandle target,
6354                                MethodHandle fallback) {
6355         MethodType gtype = test.type();
6356         MethodType ttype = target.type();
6357         MethodType ftype = fallback.type();
6358         if (!ttype.equals(ftype))
6359             throw misMatchedTypes("target and fallback types", ttype, ftype);
6360         if (gtype.returnType() != boolean.class)
6361             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6362 
6363         test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true);
6364         if (test == null) {
6365             throw misMatchedTypes("target and test types", ttype, gtype);
6366         }
6367         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6368     }
6369 
6370     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6371         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6372     }
6373 
6374     /**
6375      * Makes a method handle which adapts a target method handle,
6376      * by running it inside an exception handler.
6377      * If the target returns normally, the adapter returns that value.
6378      * If an exception matching the specified type is thrown, the fallback
6379      * handle is called instead on the exception, plus the original arguments.
6380      * <p>
6381      * The target and handler must have the same corresponding
6382      * argument and return types, except that handler may omit trailing arguments
6383      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6384      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6385      * <p>
6386      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6387      * represents the return type of the {@code target} and {@code handler},
6388      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6389      * the types and values of arguments to the resulting handle consumed by
6390      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6391      * resulting handle discarded by {@code handler}.
6392      * {@snippet lang="java" :
6393      * T target(A..., B...);
6394      * T handler(ExType, A...);
6395      * T adapter(A... a, B... b) {
6396      *   try {
6397      *     return target(a..., b...);
6398      *   } catch (ExType ex) {
6399      *     return handler(ex, a...);
6400      *   }
6401      * }
6402      * }
6403      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6404      * be modified by execution of the target, and so are passed unchanged
6405      * from the caller to the handler, if the handler is invoked.
6406      * <p>
6407      * The target and handler must return the same type, even if the handler
6408      * always throws.  (This might happen, for instance, because the handler
6409      * is simulating a {@code finally} clause).
6410      * To create such a throwing handler, compose the handler creation logic
6411      * with {@link #throwException throwException},
6412      * in order to create a method handle of the correct return type.
6413      * @param target method handle to call
6414      * @param exType the type of exception which the handler will catch
6415      * @param handler method handle to call if a matching exception is thrown
6416      * @return method handle which incorporates the specified try/catch logic
6417      * @throws NullPointerException if any argument is null
6418      * @throws IllegalArgumentException if {@code handler} does not accept
6419      *          the given exception type, or if the method handle types do
6420      *          not match in their return types and their
6421      *          corresponding parameters
6422      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6423      */
6424     public static MethodHandle catchException(MethodHandle target,
6425                                 Class<? extends Throwable> exType,
6426                                 MethodHandle handler) {
6427         MethodType ttype = target.type();
6428         MethodType htype = handler.type();
6429         if (!Throwable.class.isAssignableFrom(exType))
6430             throw new ClassCastException(exType.getName());
6431         if (htype.parameterCount() < 1 ||
6432             !htype.parameterType(0).isAssignableFrom(exType))
6433             throw newIllegalArgumentException("handler does not accept exception type "+exType);
6434         if (htype.returnType() != ttype.returnType())
6435             throw misMatchedTypes("target and handler return types", ttype, htype);
6436         handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true);
6437         if (handler == null) {
6438             throw misMatchedTypes("target and handler types", ttype, htype);
6439         }
6440         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6441     }
6442 
6443     /**
6444      * Produces a method handle which will throw exceptions of the given {@code exType}.
6445      * The method handle will accept a single argument of {@code exType},
6446      * and immediately throw it as an exception.
6447      * The method type will nominally specify a return of {@code returnType}.
6448      * The return type may be anything convenient:  It doesn't matter to the
6449      * method handle's behavior, since it will never return normally.
6450      * @param returnType the return type of the desired method handle
6451      * @param exType the parameter type of the desired method handle
6452      * @return method handle which can throw the given exceptions
6453      * @throws NullPointerException if either argument is null
6454      */
6455     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6456         if (!Throwable.class.isAssignableFrom(exType))
6457             throw new ClassCastException(exType.getName());
6458         return MethodHandleImpl.throwException(methodType(returnType, exType));
6459     }
6460 
6461     /**
6462      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6463      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6464      * delivers the loop's result, which is the return value of the resulting handle.
6465      * <p>
6466      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6467      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6468      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6469      * terms of method handles, each clause will specify up to four independent actions:<ul>
6470      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6471      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6472      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6473      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6474      * </ul>
6475      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6476      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
6477      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6478      * <p>
6479      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6480      * this case. See below for a detailed description.
6481      * <p>
6482      * <em>Parameters optional everywhere:</em>
6483      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6484      * As an exception, the init functions cannot take any {@code v} parameters,
6485      * because those values are not yet computed when the init functions are executed.
6486      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6487      * In fact, any clause function may take no arguments at all.
6488      * <p>
6489      * <em>Loop parameters:</em>
6490      * A clause function may take all the iteration variable values it is entitled to, in which case
6491      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6492      * with their types and values notated as {@code (A...)} and {@code (a...)}.
6493      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6494      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6495      * init function is automatically a loop parameter {@code a}.)
6496      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6497      * These loop parameters act as loop-invariant values visible across the whole loop.
6498      * <p>
6499      * <em>Parameters visible everywhere:</em>
6500      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6501      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6502      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6503      * Most clause functions will not need all of this information, but they will be formally connected to it
6504      * as if by {@link #dropArguments}.
6505      * <a id="astar"></a>
6506      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6507      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6508      * In that notation, the general form of an init function parameter list
6509      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6510      * <p>
6511      * <em>Checking clause structure:</em>
6512      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6513      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6514      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6515      * met by the inputs to the loop combinator.
6516      * <p>
6517      * <em>Effectively identical sequences:</em>
6518      * <a id="effid"></a>
6519      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6520      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6521      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6522      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6523      * that longest list.
6524      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6525      * and the same is true if more sequences of the form {@code (V... A*)} are added.
6526      * <p>
6527      * <em>Step 0: Determine clause structure.</em><ol type="a">
6528      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6529      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6530      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6531      * four. Padding takes place by appending elements to the array.
6532      * <li>Clauses with all {@code null}s are disregarded.
6533      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6534      * </ol>
6535      * <p>
6536      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6537      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6538      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6539      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6540      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6541      * iteration variable type.
6542      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6543      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6544      * </ol>
6545      * <p>
6546      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6547      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6548      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6549      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6550      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6551      * (These types will be checked in step 2, along with all the clause function types.)
6552      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6553      * <li>All of the collected parameter lists must be effectively identical.
6554      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6555      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6556      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6557      * the "internal parameter list".
6558      * </ul>
6559      * <p>
6560      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6561      * <li>Examine fini function return types, disregarding omitted fini functions.
6562      * <li>If there are no fini functions, the loop return type is {@code void}.
6563      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6564      * type.
6565      * </ol>
6566      * <p>
6567      * <em>Step 1D: Check other types.</em><ol type="a">
6568      * <li>There must be at least one non-omitted pred function.
6569      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6570      * </ol>
6571      * <p>
6572      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6573      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6574      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6575      * (Note that their parameter lists are already effectively identical to this list.)
6576      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6577      * effectively identical to the internal parameter list {@code (V... A...)}.
6578      * </ol>
6579      * <p>
6580      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6581      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6582      * type.
6583      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6584      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6585      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6586      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6587      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6588      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6589      * loop return type.
6590      * </ol>
6591      * <p>
6592      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6593      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6594      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6595      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6596      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6597      * pad out the end of the list.
6598      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6599      * </ol>
6600      * <p>
6601      * <em>Final observations.</em><ol type="a">
6602      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6603      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6604      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6605      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6606      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6607      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6608      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6609      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6610      * </ol>
6611      * <p>
6612      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6613      * <ul>
6614      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6615      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6616      * (Only one {@code Pn} has to be non-{@code null}.)
6617      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6618      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6619      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6620      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6621      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6622      * the resulting loop handle's parameter types {@code (A...)}.
6623      * </ul>
6624      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6625      * which is natural if most of the loop computation happens in the steps.  For some loops,
6626      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6627      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6628      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6629      * where the init functions will need the extra parameters.  For such reasons, the rules for
6630      * determining these parameters are as symmetric as possible, across all clause parts.
6631      * In general, the loop parameters function as common invariant values across the whole
6632      * loop, while the iteration variables function as common variant values, or (if there is
6633      * no step function) as internal loop invariant temporaries.
6634      * <p>
6635      * <em>Loop execution.</em><ol type="a">
6636      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6637      * every clause function. These locals are loop invariant.
6638      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6639      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6640      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6641      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6642      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6643      * (in argument order).
6644      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6645      * returns {@code false}.
6646      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6647      * sequence {@code (v...)} of loop variables.
6648      * The updated value is immediately visible to all subsequent function calls.
6649      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6650      * (of type {@code R}) is returned from the loop as a whole.
6651      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6652      * except by throwing an exception.
6653      * </ol>
6654      * <p>
6655      * <em>Usage tips.</em>
6656      * <ul>
6657      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6658      * sometimes a step function only needs to observe the current value of its own variable.
6659      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6660      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6661      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6662      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6663      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6664      * <li>If some of the clause functions are virtual methods on an instance, the instance
6665      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6666      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6667      * will be the first iteration variable value, and it will be easy to use virtual
6668      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6669      * </ul>
6670      * <p>
6671      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6672      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6673      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6674      * {@snippet lang="java" :
6675      * V... init...(A...);
6676      * boolean pred...(V..., A...);
6677      * V... step...(V..., A...);
6678      * R fini...(V..., A...);
6679      * R loop(A... a) {
6680      *   V... v... = init...(a...);
6681      *   for (;;) {
6682      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6683      *       v = s(v..., a...);
6684      *       if (!p(v..., a...)) {
6685      *         return f(v..., a...);
6686      *       }
6687      *     }
6688      *   }
6689      * }
6690      * }
6691      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6692      * to their full length, even though individual clause functions may neglect to take them all.
6693      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6694      *
6695      * @apiNote Example:
6696      * {@snippet lang="java" :
6697      * // iterative implementation of the factorial function as a loop handle
6698      * static int one(int k) { return 1; }
6699      * static int inc(int i, int acc, int k) { return i + 1; }
6700      * static int mult(int i, int acc, int k) { return i * acc; }
6701      * static boolean pred(int i, int acc, int k) { return i < k; }
6702      * static int fin(int i, int acc, int k) { return acc; }
6703      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6704      * // null initializer for counter, should initialize to 0
6705      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6706      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6707      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6708      * assertEquals(120, loop.invoke(5));
6709      * }
6710      * The same example, dropping arguments and using combinators:
6711      * {@snippet lang="java" :
6712      * // simplified implementation of the factorial function as a loop handle
6713      * static int inc(int i) { return i + 1; } // drop acc, k
6714      * static int mult(int i, int acc) { return i * acc; } //drop k
6715      * static boolean cmp(int i, int k) { return i < k; }
6716      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6717      * // null initializer for counter, should initialize to 0
6718      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6719      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6720      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6721      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6722      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6723      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6724      * assertEquals(720, loop.invoke(6));
6725      * }
6726      * A similar example, using a helper object to hold a loop parameter:
6727      * {@snippet lang="java" :
6728      * // instance-based implementation of the factorial function as a loop handle
6729      * static class FacLoop {
6730      *   final int k;
6731      *   FacLoop(int k) { this.k = k; }
6732      *   int inc(int i) { return i + 1; }
6733      *   int mult(int i, int acc) { return i * acc; }
6734      *   boolean pred(int i) { return i < k; }
6735      *   int fin(int i, int acc) { return acc; }
6736      * }
6737      * // assume MH_FacLoop is a handle to the constructor
6738      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6739      * // null initializer for counter, should initialize to 0
6740      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6741      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6742      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6743      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6744      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6745      * assertEquals(5040, loop.invoke(7));
6746      * }
6747      *
6748      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6749      *
6750      * @return a method handle embodying the looping behavior as defined by the arguments.
6751      *
6752      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6753      *
6754      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6755      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6756      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6757      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6758      * @since 9
6759      */
6760     public static MethodHandle loop(MethodHandle[]... clauses) {
6761         // Step 0: determine clause structure.
6762         loopChecks0(clauses);
6763 
6764         List<MethodHandle> init = new ArrayList<>();
6765         List<MethodHandle> step = new ArrayList<>();
6766         List<MethodHandle> pred = new ArrayList<>();
6767         List<MethodHandle> fini = new ArrayList<>();
6768 
6769         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6770             init.add(clause[0]); // all clauses have at least length 1
6771             step.add(clause.length <= 1 ? null : clause[1]);
6772             pred.add(clause.length <= 2 ? null : clause[2]);
6773             fini.add(clause.length <= 3 ? null : clause[3]);
6774         });
6775 
6776         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6777         final int nclauses = init.size();
6778 
6779         // Step 1A: determine iteration variables (V...).
6780         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6781         for (int i = 0; i < nclauses; ++i) {
6782             MethodHandle in = init.get(i);
6783             MethodHandle st = step.get(i);
6784             if (in == null && st == null) {
6785                 iterationVariableTypes.add(void.class);
6786             } else if (in != null && st != null) {
6787                 loopChecks1a(i, in, st);
6788                 iterationVariableTypes.add(in.type().returnType());
6789             } else {
6790                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6791             }
6792         }
6793         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6794 
6795         // Step 1B: determine loop parameters (A...).
6796         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6797         loopChecks1b(init, commonSuffix);
6798 
6799         // Step 1C: determine loop return type.
6800         // Step 1D: check other types.
6801         // local variable required here; see JDK-8223553
6802         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6803                 .map(MethodType::returnType);
6804         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6805         loopChecks1cd(pred, fini, loopReturnType);
6806 
6807         // Step 2: determine parameter lists.
6808         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6809         commonParameterSequence.addAll(commonSuffix);
6810         loopChecks2(step, pred, fini, commonParameterSequence);
6811         // Step 3: fill in omitted functions.
6812         for (int i = 0; i < nclauses; ++i) {
6813             Class<?> t = iterationVariableTypes.get(i);
6814             if (init.get(i) == null) {
6815                 init.set(i, empty(methodType(t, commonSuffix)));
6816             }
6817             if (step.get(i) == null) {
6818                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6819             }
6820             if (pred.get(i) == null) {
6821                 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
6822             }
6823             if (fini.get(i) == null) {
6824                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6825             }
6826         }
6827 
6828         // Step 4: fill in missing parameter types.
6829         // Also convert all handles to fixed-arity handles.
6830         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6831         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6832         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6833         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6834 
6835         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6836                 allMatch(pl -> pl.equals(commonSuffix));
6837         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6838                 allMatch(pl -> pl.equals(commonParameterSequence));
6839 
6840         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6841     }
6842 
6843     private static void loopChecks0(MethodHandle[][] clauses) {
6844         if (clauses == null || clauses.length == 0) {
6845             throw newIllegalArgumentException("null or no clauses passed");
6846         }
6847         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6848             throw newIllegalArgumentException("null clauses are not allowed");
6849         }
6850         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6851             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6852         }
6853     }
6854 
6855     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6856         if (in.type().returnType() != st.type().returnType()) {
6857             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6858                     st.type().returnType());
6859         }
6860     }
6861 
6862     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6863         return mhs.filter(Objects::nonNull)
6864                 // take only those that can contribute to a common suffix because they are longer than the prefix
6865                 .map(MethodHandle::type)
6866                 .filter(t -> t.parameterCount() > skipSize)
6867                 .max(Comparator.comparingInt(MethodType::parameterCount))
6868                 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount())))
6869                 .orElse(List.of());
6870     }
6871 
6872     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6873         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6874         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6875         return longest1.size() >= longest2.size() ? longest1 : longest2;
6876     }
6877 
6878     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6879         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6880                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6881             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6882                     " (common suffix: " + commonSuffix + ")");
6883         }
6884     }
6885 
6886     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6887         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6888                 anyMatch(t -> t != loopReturnType)) {
6889             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6890                     loopReturnType + ")");
6891         }
6892 
6893         if (pred.stream().noneMatch(Objects::nonNull)) {
6894             throw newIllegalArgumentException("no predicate found", pred);
6895         }
6896         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6897                 anyMatch(t -> t != boolean.class)) {
6898             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6899         }
6900     }
6901 
6902     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6903         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6904                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6905             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6906                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6907         }
6908     }
6909 
6910     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6911         return hs.stream().map(h -> {
6912             int pc = h.type().parameterCount();
6913             int tpsize = targetParams.size();
6914             return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
6915         }).toList();
6916     }
6917 
6918     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6919         return hs.stream().map(MethodHandle::asFixedArity).toList();
6920     }
6921 
6922     /**
6923      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6924      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6925      * <p>
6926      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6927      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6928      * evaluates to {@code true}).
6929      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6930      * <p>
6931      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6932      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6933      * and updated with the value returned from its invocation. The result of loop execution will be
6934      * the final value of the additional loop-local variable (if present).
6935      * <p>
6936      * The following rules hold for these argument handles:<ul>
6937      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6938      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6939      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6940      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6941      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6942      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6943      * It will constrain the parameter lists of the other loop parts.
6944      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6945      * list {@code (A...)} is called the <em>external parameter list</em>.
6946      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6947      * additional state variable of the loop.
6948      * The body must both accept and return a value of this type {@code V}.
6949      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6950      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6951      * <a href="MethodHandles.html#effid">effectively identical</a>
6952      * to the external parameter list {@code (A...)}.
6953      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6954      * {@linkplain #empty default value}.
6955      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6956      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6957      * effectively identical to the internal parameter list.
6958      * </ul>
6959      * <p>
6960      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6961      * <li>The loop handle's result type is the result type {@code V} of the body.
6962      * <li>The loop handle's parameter types are the types {@code (A...)},
6963      * from the external parameter list.
6964      * </ul>
6965      * <p>
6966      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6967      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6968      * passed to the loop.
6969      * {@snippet lang="java" :
6970      * V init(A...);
6971      * boolean pred(V, A...);
6972      * V body(V, A...);
6973      * V whileLoop(A... a...) {
6974      *   V v = init(a...);
6975      *   while (pred(v, a...)) {
6976      *     v = body(v, a...);
6977      *   }
6978      *   return v;
6979      * }
6980      * }
6981      *
6982      * @apiNote Example:
6983      * {@snippet lang="java" :
6984      * // implement the zip function for lists as a loop handle
6985      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6986      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6987      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6988      *   zip.add(a.next());
6989      *   zip.add(b.next());
6990      *   return zip;
6991      * }
6992      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6993      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6994      * List<String> a = Arrays.asList("a", "b", "c", "d");
6995      * List<String> b = Arrays.asList("e", "f", "g", "h");
6996      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6997      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6998      * }
6999      *
7000      *
7001      * @apiNote The implementation of this method can be expressed as follows:
7002      * {@snippet lang="java" :
7003      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
7004      *     MethodHandle fini = (body.type().returnType() == void.class
7005      *                         ? null : identity(body.type().returnType()));
7006      *     MethodHandle[]
7007      *         checkExit = { null, null, pred, fini },
7008      *         varBody   = { init, body };
7009      *     return loop(checkExit, varBody);
7010      * }
7011      * }
7012      *
7013      * @param init optional initializer, providing the initial value of the loop variable.
7014      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7015      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7016      *             above for other constraints.
7017      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7018      *             See above for other constraints.
7019      *
7020      * @return a method handle implementing the {@code while} loop as described by the arguments.
7021      * @throws IllegalArgumentException if the rules for the arguments are violated.
7022      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7023      *
7024      * @see #loop(MethodHandle[][])
7025      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
7026      * @since 9
7027      */
7028     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
7029         whileLoopChecks(init, pred, body);
7030         MethodHandle fini = identityOrVoid(body.type().returnType());
7031         MethodHandle[] checkExit = { null, null, pred, fini };
7032         MethodHandle[] varBody = { init, body };
7033         return loop(checkExit, varBody);
7034     }
7035 
7036     /**
7037      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
7038      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7039      * <p>
7040      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
7041      * method will, in each iteration, first execute its body and then evaluate the predicate.
7042      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
7043      * <p>
7044      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
7045      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
7046      * and updated with the value returned from its invocation. The result of loop execution will be
7047      * the final value of the additional loop-local variable (if present).
7048      * <p>
7049      * The following rules hold for these argument handles:<ul>
7050      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7051      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
7052      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7053      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
7054      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
7055      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
7056      * It will constrain the parameter lists of the other loop parts.
7057      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
7058      * list {@code (A...)} is called the <em>external parameter list</em>.
7059      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7060      * additional state variable of the loop.
7061      * The body must both accept and return a value of this type {@code V}.
7062      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7063      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7064      * <a href="MethodHandles.html#effid">effectively identical</a>
7065      * to the external parameter list {@code (A...)}.
7066      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7067      * {@linkplain #empty default value}.
7068      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
7069      * Its parameter list (either empty or of the form {@code (V A*)}) must be
7070      * effectively identical to the internal parameter list.
7071      * </ul>
7072      * <p>
7073      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7074      * <li>The loop handle's result type is the result type {@code V} of the body.
7075      * <li>The loop handle's parameter types are the types {@code (A...)},
7076      * from the external parameter list.
7077      * </ul>
7078      * <p>
7079      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7080      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
7081      * passed to the loop.
7082      * {@snippet lang="java" :
7083      * V init(A...);
7084      * boolean pred(V, A...);
7085      * V body(V, A...);
7086      * V doWhileLoop(A... a...) {
7087      *   V v = init(a...);
7088      *   do {
7089      *     v = body(v, a...);
7090      *   } while (pred(v, a...));
7091      *   return v;
7092      * }
7093      * }
7094      *
7095      * @apiNote Example:
7096      * {@snippet lang="java" :
7097      * // int i = 0; while (i < limit) { ++i; } return i; => limit
7098      * static int zero(int limit) { return 0; }
7099      * static int step(int i, int limit) { return i + 1; }
7100      * static boolean pred(int i, int limit) { return i < limit; }
7101      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
7102      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
7103      * assertEquals(23, loop.invoke(23));
7104      * }
7105      *
7106      *
7107      * @apiNote The implementation of this method can be expressed as follows:
7108      * {@snippet lang="java" :
7109      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7110      *     MethodHandle fini = (body.type().returnType() == void.class
7111      *                         ? null : identity(body.type().returnType()));
7112      *     MethodHandle[] clause = { init, body, pred, fini };
7113      *     return loop(clause);
7114      * }
7115      * }
7116      *
7117      * @param init optional initializer, providing the initial value of the loop variable.
7118      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7119      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7120      *             See above for other constraints.
7121      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7122      *             above for other constraints.
7123      *
7124      * @return a method handle implementing the {@code while} loop as described by the arguments.
7125      * @throws IllegalArgumentException if the rules for the arguments are violated.
7126      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7127      *
7128      * @see #loop(MethodHandle[][])
7129      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
7130      * @since 9
7131      */
7132     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7133         whileLoopChecks(init, pred, body);
7134         MethodHandle fini = identityOrVoid(body.type().returnType());
7135         MethodHandle[] clause = {init, body, pred, fini };
7136         return loop(clause);
7137     }
7138 
7139     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
7140         Objects.requireNonNull(pred);
7141         Objects.requireNonNull(body);
7142         MethodType bodyType = body.type();
7143         Class<?> returnType = bodyType.returnType();
7144         List<Class<?>> innerList = bodyType.parameterList();
7145         List<Class<?>> outerList = innerList;
7146         if (returnType == void.class) {
7147             // OK
7148         } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
7149             // leading V argument missing => error
7150             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7151             throw misMatchedTypes("body function", bodyType, expected);
7152         } else {
7153             outerList = innerList.subList(1, innerList.size());
7154         }
7155         MethodType predType = pred.type();
7156         if (predType.returnType() != boolean.class ||
7157                 !predType.effectivelyIdenticalParameters(0, innerList)) {
7158             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
7159         }
7160         if (init != null) {
7161             MethodType initType = init.type();
7162             if (initType.returnType() != returnType ||
7163                     !initType.effectivelyIdenticalParameters(0, outerList)) {
7164                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7165             }
7166         }
7167     }
7168 
7169     /**
7170      * Constructs a loop that runs a given number of iterations.
7171      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7172      * <p>
7173      * The number of iterations is determined by the {@code iterations} handle evaluation result.
7174      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
7175      * It will be initialized to 0 and incremented by 1 in each iteration.
7176      * <p>
7177      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7178      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7179      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7180      * <p>
7181      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7182      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7183      * iteration variable.
7184      * The result of the loop handle execution will be the final {@code V} value of that variable
7185      * (or {@code void} if there is no {@code V} variable).
7186      * <p>
7187      * The following rules hold for the argument handles:<ul>
7188      * <li>The {@code iterations} handle must not be {@code null}, and must return
7189      * the type {@code int}, referred to here as {@code I} in parameter type lists.
7190      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7191      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7192      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7193      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7194      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7195      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7196      * of types called the <em>internal parameter list</em>.
7197      * It will constrain the parameter lists of the other loop parts.
7198      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7199      * with no additional {@code A} types, then the internal parameter list is extended by
7200      * the argument types {@code A...} of the {@code iterations} handle.
7201      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7202      * list {@code (A...)} is called the <em>external parameter list</em>.
7203      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7204      * additional state variable of the loop.
7205      * The body must both accept a leading parameter and return a value of this type {@code V}.
7206      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7207      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7208      * <a href="MethodHandles.html#effid">effectively identical</a>
7209      * to the external parameter list {@code (A...)}.
7210      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7211      * {@linkplain #empty default value}.
7212      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
7213      * effectively identical to the external parameter list {@code (A...)}.
7214      * </ul>
7215      * <p>
7216      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7217      * <li>The loop handle's result type is the result type {@code V} of the body.
7218      * <li>The loop handle's parameter types are the types {@code (A...)},
7219      * from the external parameter list.
7220      * </ul>
7221      * <p>
7222      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7223      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7224      * arguments passed to the loop.
7225      * {@snippet lang="java" :
7226      * int iterations(A...);
7227      * V init(A...);
7228      * V body(V, int, A...);
7229      * V countedLoop(A... a...) {
7230      *   int end = iterations(a...);
7231      *   V v = init(a...);
7232      *   for (int i = 0; i < end; ++i) {
7233      *     v = body(v, i, a...);
7234      *   }
7235      *   return v;
7236      * }
7237      * }
7238      *
7239      * @apiNote Example with a fully conformant body method:
7240      * {@snippet lang="java" :
7241      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7242      * // => a variation on a well known theme
7243      * static String step(String v, int counter, String init) { return "na " + v; }
7244      * // assume MH_step is a handle to the method above
7245      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
7246      * MethodHandle start = MethodHandles.identity(String.class);
7247      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
7248      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
7249      * }
7250      *
7251      * @apiNote Example with the simplest possible body method type,
7252      * and passing the number of iterations to the loop invocation:
7253      * {@snippet lang="java" :
7254      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7255      * // => a variation on a well known theme
7256      * static String step(String v, int counter ) { return "na " + v; }
7257      * // assume MH_step is a handle to the method above
7258      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
7259      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
7260      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
7261      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
7262      * }
7263      *
7264      * @apiNote Example that treats the number of iterations, string to append to, and string to append
7265      * as loop parameters:
7266      * {@snippet lang="java" :
7267      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7268      * // => a variation on a well known theme
7269      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
7270      * // assume MH_step is a handle to the method above
7271      * MethodHandle count = MethodHandles.identity(int.class);
7272      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
7273      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
7274      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
7275      * }
7276      *
7277      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
7278      * to enforce a loop type:
7279      * {@snippet lang="java" :
7280      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7281      * // => a variation on a well known theme
7282      * static String step(String v, int counter, String pre) { return pre + " " + v; }
7283      * // assume MH_step is a handle to the method above
7284      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
7285      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
7286      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
7287      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
7288      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
7289      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
7290      * }
7291      *
7292      * @apiNote The implementation of this method can be expressed as follows:
7293      * {@snippet lang="java" :
7294      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7295      *     return countedLoop(empty(iterations.type()), iterations, init, body);
7296      * }
7297      * }
7298      *
7299      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
7300      *                   result type must be {@code int}. See above for other constraints.
7301      * @param init optional initializer, providing the initial value of the loop variable.
7302      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7303      * @param body body of the loop, which may not be {@code null}.
7304      *             It controls the loop parameters and result type in the standard case (see above for details).
7305      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7306      *             and may accept any number of additional types.
7307      *             See above for other constraints.
7308      *
7309      * @return a method handle representing the loop.
7310      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7311      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7312      *
7313      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7314      * @since 9
7315      */
7316     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7317         return countedLoop(empty(iterations.type()), iterations, init, body);
7318     }
7319 
7320     /**
7321      * Constructs a loop that counts over a range of numbers.
7322      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7323      * <p>
7324      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7325      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7326      * values of the loop counter.
7327      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7328      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7329      * <p>
7330      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7331      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7332      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7333      * <p>
7334      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7335      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7336      * iteration variable.
7337      * The result of the loop handle execution will be the final {@code V} value of that variable
7338      * (or {@code void} if there is no {@code V} variable).
7339      * <p>
7340      * The following rules hold for the argument handles:<ul>
7341      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7342      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7343      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7344      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7345      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7346      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7347      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7348      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7349      * of types called the <em>internal parameter list</em>.
7350      * It will constrain the parameter lists of the other loop parts.
7351      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7352      * with no additional {@code A} types, then the internal parameter list is extended by
7353      * the argument types {@code A...} of the {@code end} handle.
7354      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7355      * list {@code (A...)} is called the <em>external parameter list</em>.
7356      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7357      * additional state variable of the loop.
7358      * The body must both accept a leading parameter and return a value of this type {@code V}.
7359      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7360      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7361      * <a href="MethodHandles.html#effid">effectively identical</a>
7362      * to the external parameter list {@code (A...)}.
7363      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7364      * {@linkplain #empty default value}.
7365      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7366      * effectively identical to the external parameter list {@code (A...)}.
7367      * <li>Likewise, the parameter list of {@code end} must be effectively identical
7368      * to the external parameter list.
7369      * </ul>
7370      * <p>
7371      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7372      * <li>The loop handle's result type is the result type {@code V} of the body.
7373      * <li>The loop handle's parameter types are the types {@code (A...)},
7374      * from the external parameter list.
7375      * </ul>
7376      * <p>
7377      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7378      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7379      * arguments passed to the loop.
7380      * {@snippet lang="java" :
7381      * int start(A...);
7382      * int end(A...);
7383      * V init(A...);
7384      * V body(V, int, A...);
7385      * V countedLoop(A... a...) {
7386      *   int e = end(a...);
7387      *   int s = start(a...);
7388      *   V v = init(a...);
7389      *   for (int i = s; i < e; ++i) {
7390      *     v = body(v, i, a...);
7391      *   }
7392      *   return v;
7393      * }
7394      * }
7395      *
7396      * @apiNote The implementation of this method can be expressed as follows:
7397      * {@snippet lang="java" :
7398      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7399      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7400      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7401      *     // the following semantics:
7402      *     // MH_increment: (int limit, int counter) -> counter + 1
7403      *     // MH_predicate: (int limit, int counter) -> counter < limit
7404      *     Class<?> counterType = start.type().returnType();  // int
7405      *     Class<?> returnType = body.type().returnType();
7406      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7407      *     if (returnType != void.class) {  // ignore the V variable
7408      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7409      *         pred = dropArguments(pred, 1, returnType);  // ditto
7410      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7411      *     }
7412      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
7413      *     MethodHandle[]
7414      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7415      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
7416      *         indexVar   = { start, incr };           // i = start(); i = i + 1
7417      *     return loop(loopLimit, bodyClause, indexVar);
7418      * }
7419      * }
7420      *
7421      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7422      *              See above for other constraints.
7423      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7424      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
7425      * @param init optional initializer, providing the initial value of the loop variable.
7426      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7427      * @param body body of the loop, which may not be {@code null}.
7428      *             It controls the loop parameters and result type in the standard case (see above for details).
7429      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7430      *             and may accept any number of additional types.
7431      *             See above for other constraints.
7432      *
7433      * @return a method handle representing the loop.
7434      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7435      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7436      *
7437      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7438      * @since 9
7439      */
7440     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7441         countedLoopChecks(start, end, init, body);
7442         Class<?> counterType = start.type().returnType();  // int, but who's counting?
7443         Class<?> limitType   = end.type().returnType();    // yes, int again
7444         Class<?> returnType  = body.type().returnType();
7445         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7446         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7447         MethodHandle retv = null;
7448         if (returnType != void.class) {
7449             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7450             pred = dropArguments(pred, 1, returnType);  // ditto
7451             retv = dropArguments(identity(returnType), 0, counterType);
7452         }
7453         body = dropArguments(body, 0, counterType);  // ignore the limit variable
7454         MethodHandle[]
7455             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7456             bodyClause = { init, body },            // v = init(); v = body(v, i)
7457             indexVar   = { start, incr };           // i = start(); i = i + 1
7458         return loop(loopLimit, bodyClause, indexVar);
7459     }
7460 
7461     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7462         Objects.requireNonNull(start);
7463         Objects.requireNonNull(end);
7464         Objects.requireNonNull(body);
7465         Class<?> counterType = start.type().returnType();
7466         if (counterType != int.class) {
7467             MethodType expected = start.type().changeReturnType(int.class);
7468             throw misMatchedTypes("start function", start.type(), expected);
7469         } else if (end.type().returnType() != counterType) {
7470             MethodType expected = end.type().changeReturnType(counterType);
7471             throw misMatchedTypes("end function", end.type(), expected);
7472         }
7473         MethodType bodyType = body.type();
7474         Class<?> returnType = bodyType.returnType();
7475         List<Class<?>> innerList = bodyType.parameterList();
7476         // strip leading V value if present
7477         int vsize = (returnType == void.class ? 0 : 1);
7478         if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7479             // argument list has no "V" => error
7480             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7481             throw misMatchedTypes("body function", bodyType, expected);
7482         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7483             // missing I type => error
7484             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7485             throw misMatchedTypes("body function", bodyType, expected);
7486         }
7487         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7488         if (outerList.isEmpty()) {
7489             // special case; take lists from end handle
7490             outerList = end.type().parameterList();
7491             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7492         }
7493         MethodType expected = methodType(counterType, outerList);
7494         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7495             throw misMatchedTypes("start parameter types", start.type(), expected);
7496         }
7497         if (end.type() != start.type() &&
7498             !end.type().effectivelyIdenticalParameters(0, outerList)) {
7499             throw misMatchedTypes("end parameter types", end.type(), expected);
7500         }
7501         if (init != null) {
7502             MethodType initType = init.type();
7503             if (initType.returnType() != returnType ||
7504                 !initType.effectivelyIdenticalParameters(0, outerList)) {
7505                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7506             }
7507         }
7508     }
7509 
7510     /**
7511      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7512      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7513      * <p>
7514      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7515      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7516      * <p>
7517      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7518      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7519      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7520      * <p>
7521      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7522      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7523      * iteration variable.
7524      * The result of the loop handle execution will be the final {@code V} value of that variable
7525      * (or {@code void} if there is no {@code V} variable).
7526      * <p>
7527      * The following rules hold for the argument handles:<ul>
7528      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7529      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7530      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7531      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7532      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7533      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7534      * of types called the <em>internal parameter list</em>.
7535      * It will constrain the parameter lists of the other loop parts.
7536      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7537      * with no additional {@code A} types, then the internal parameter list is extended by
7538      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7539      * single type {@code Iterable} is added and constitutes the {@code A...} list.
7540      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7541      * list {@code (A...)} is called the <em>external parameter list</em>.
7542      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7543      * additional state variable of the loop.
7544      * The body must both accept a leading parameter and return a value of this type {@code V}.
7545      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7546      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7547      * <a href="MethodHandles.html#effid">effectively identical</a>
7548      * to the external parameter list {@code (A...)}.
7549      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7550      * {@linkplain #empty default value}.
7551      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7552      * type {@code java.util.Iterator} or a subtype thereof.
7553      * The iterator it produces when the loop is executed will be assumed
7554      * to yield values which can be converted to type {@code T}.
7555      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7556      * effectively identical to the external parameter list {@code (A...)}.
7557      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7558      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7559      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7560      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7561      * the {@link MethodHandle#asType asType} conversion method.
7562      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7563      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7564      * </ul>
7565      * <p>
7566      * The type {@code T} may be either a primitive or reference.
7567      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7568      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7569      * as if by the {@link MethodHandle#asType asType} conversion method.
7570      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7571      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7572      * <p>
7573      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7574      * <li>The loop handle's result type is the result type {@code V} of the body.
7575      * <li>The loop handle's parameter types are the types {@code (A...)},
7576      * from the external parameter list.
7577      * </ul>
7578      * <p>
7579      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7580      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7581      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7582      * {@snippet lang="java" :
7583      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7584      * V init(A...);
7585      * V body(V,T,A...);
7586      * V iteratedLoop(A... a...) {
7587      *   Iterator<T> it = iterator(a...);
7588      *   V v = init(a...);
7589      *   while (it.hasNext()) {
7590      *     T t = it.next();
7591      *     v = body(v, t, a...);
7592      *   }
7593      *   return v;
7594      * }
7595      * }
7596      *
7597      * @apiNote Example:
7598      * {@snippet lang="java" :
7599      * // get an iterator from a list
7600      * static List<String> reverseStep(List<String> r, String e) {
7601      *   r.add(0, e);
7602      *   return r;
7603      * }
7604      * static List<String> newArrayList() { return new ArrayList<>(); }
7605      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7606      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7607      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7608      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7609      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7610      * }
7611      *
7612      * @apiNote The implementation of this method can be expressed approximately as follows:
7613      * {@snippet lang="java" :
7614      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7615      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7616      *     Class<?> returnType = body.type().returnType();
7617      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7618      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7619      *     MethodHandle retv = null, step = body, startIter = iterator;
7620      *     if (returnType != void.class) {
7621      *         // the simple thing first:  in (I V A...), drop the I to get V
7622      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7623      *         // body type signature (V T A...), internal loop types (I V A...)
7624      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7625      *     }
7626      *     if (startIter == null)  startIter = MH_getIter;
7627      *     MethodHandle[]
7628      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7629      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7630      *     return loop(iterVar, bodyClause);
7631      * }
7632      * }
7633      *
7634      * @param iterator an optional handle to return the iterator to start the loop.
7635      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7636      *                 See above for other constraints.
7637      * @param init optional initializer, providing the initial value of the loop variable.
7638      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7639      * @param body body of the loop, which may not be {@code null}.
7640      *             It controls the loop parameters and result type in the standard case (see above for details).
7641      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7642      *             and may accept any number of additional types.
7643      *             See above for other constraints.
7644      *
7645      * @return a method handle embodying the iteration loop functionality.
7646      * @throws NullPointerException if the {@code body} handle is {@code null}.
7647      * @throws IllegalArgumentException if any argument violates the above requirements.
7648      *
7649      * @since 9
7650      */
7651     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7652         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7653         Class<?> returnType = body.type().returnType();
7654         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7655         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7656         MethodHandle startIter;
7657         MethodHandle nextVal;
7658         {
7659             MethodType iteratorType;
7660             if (iterator == null) {
7661                 // derive argument type from body, if available, else use Iterable
7662                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7663                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7664             } else {
7665                 // force return type to the internal iterator class
7666                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7667                 startIter = iterator;
7668             }
7669             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7670             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7671 
7672             // perform the asType transforms under an exception transformer, as per spec.:
7673             try {
7674                 startIter = startIter.asType(iteratorType);
7675                 nextVal = nextRaw.asType(nextValType);
7676             } catch (WrongMethodTypeException ex) {
7677                 throw new IllegalArgumentException(ex);
7678             }
7679         }
7680 
7681         MethodHandle retv = null, step = body;
7682         if (returnType != void.class) {
7683             // the simple thing first:  in (I V A...), drop the I to get V
7684             retv = dropArguments(identity(returnType), 0, Iterator.class);
7685             // body type signature (V T A...), internal loop types (I V A...)
7686             step = swapArguments(body, 0, 1);  // swap V <-> T
7687         }
7688 
7689         MethodHandle[]
7690             iterVar    = { startIter, null, hasNext, retv },
7691             bodyClause = { init, filterArgument(step, 0, nextVal) };
7692         return loop(iterVar, bodyClause);
7693     }
7694 
7695     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7696         Objects.requireNonNull(body);
7697         MethodType bodyType = body.type();
7698         Class<?> returnType = bodyType.returnType();
7699         List<Class<?>> internalParamList = bodyType.parameterList();
7700         // strip leading V value if present
7701         int vsize = (returnType == void.class ? 0 : 1);
7702         if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7703             // argument list has no "V" => error
7704             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7705             throw misMatchedTypes("body function", bodyType, expected);
7706         } else if (internalParamList.size() <= vsize) {
7707             // missing T type => error
7708             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7709             throw misMatchedTypes("body function", bodyType, expected);
7710         }
7711         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7712         Class<?> iterableType = null;
7713         if (iterator != null) {
7714             // special case; if the body handle only declares V and T then
7715             // the external parameter list is obtained from iterator handle
7716             if (externalParamList.isEmpty()) {
7717                 externalParamList = iterator.type().parameterList();
7718             }
7719             MethodType itype = iterator.type();
7720             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7721                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7722             }
7723             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7724                 MethodType expected = methodType(itype.returnType(), externalParamList);
7725                 throw misMatchedTypes("iterator parameters", itype, expected);
7726             }
7727         } else {
7728             if (externalParamList.isEmpty()) {
7729                 // special case; if the iterator handle is null and the body handle
7730                 // only declares V and T then the external parameter list consists
7731                 // of Iterable
7732                 externalParamList = List.of(Iterable.class);
7733                 iterableType = Iterable.class;
7734             } else {
7735                 // special case; if the iterator handle is null and the external
7736                 // parameter list is not empty then the first parameter must be
7737                 // assignable to Iterable
7738                 iterableType = externalParamList.get(0);
7739                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7740                     throw newIllegalArgumentException(
7741                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7742                 }
7743             }
7744         }
7745         if (init != null) {
7746             MethodType initType = init.type();
7747             if (initType.returnType() != returnType ||
7748                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7749                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7750             }
7751         }
7752         return iterableType;  // help the caller a bit
7753     }
7754 
7755     /*non-public*/
7756     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7757         // there should be a better way to uncross my wires
7758         int arity = mh.type().parameterCount();
7759         int[] order = new int[arity];
7760         for (int k = 0; k < arity; k++)  order[k] = k;
7761         order[i] = j; order[j] = i;
7762         Class<?>[] types = mh.type().parameterArray();
7763         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7764         MethodType swapType = methodType(mh.type().returnType(), types);
7765         return permuteArguments(mh, swapType, order);
7766     }
7767 
7768     /**
7769      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7770      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7771      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7772      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7773      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7774      * {@code try-finally} handle.
7775      * <p>
7776      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7777      * The first is the exception thrown during the
7778      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7779      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7780      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7781      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7782      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7783      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7784      * <p>
7785      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7786      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7787      * two extra leading parameters:<ul>
7788      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7789      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7790      * the result from the execution of the {@code target} handle.
7791      * This parameter is not present if the {@code target} returns {@code void}.
7792      * </ul>
7793      * <p>
7794      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7795      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7796      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7797      * the cleanup.
7798      * {@snippet lang="java" :
7799      * V target(A..., B...);
7800      * V cleanup(Throwable, V, A...);
7801      * V adapter(A... a, B... b) {
7802      *   V result = (zero value for V);
7803      *   Throwable throwable = null;
7804      *   try {
7805      *     result = target(a..., b...);
7806      *   } catch (Throwable t) {
7807      *     throwable = t;
7808      *     throw t;
7809      *   } finally {
7810      *     result = cleanup(throwable, result, a...);
7811      *   }
7812      *   return result;
7813      * }
7814      * }
7815      * <p>
7816      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7817      * be modified by execution of the target, and so are passed unchanged
7818      * from the caller to the cleanup, if it is invoked.
7819      * <p>
7820      * The target and cleanup must return the same type, even if the cleanup
7821      * always throws.
7822      * To create such a throwing cleanup, compose the cleanup logic
7823      * with {@link #throwException throwException},
7824      * in order to create a method handle of the correct return type.
7825      * <p>
7826      * Note that {@code tryFinally} never converts exceptions into normal returns.
7827      * In rare cases where exceptions must be converted in that way, first wrap
7828      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7829      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7830      * <p>
7831      * It is recommended that the first parameter type of {@code cleanup} be
7832      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7833      * {@code cleanup} will always be invoked with whatever exception that
7834      * {@code target} throws.  Declaring a narrower type may result in a
7835      * {@code ClassCastException} being thrown by the {@code try-finally}
7836      * handle if the type of the exception thrown by {@code target} is not
7837      * assignable to the first parameter type of {@code cleanup}.  Note that
7838      * various exception types of {@code VirtualMachineError},
7839      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7840      * thrown by almost any kind of Java code, and a finally clause that
7841      * catches (say) only {@code IOException} would mask any of the others
7842      * behind a {@code ClassCastException}.
7843      *
7844      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7845      * @param cleanup the handle that is invoked in the finally block.
7846      *
7847      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7848      * @throws NullPointerException if any argument is null
7849      * @throws IllegalArgumentException if {@code cleanup} does not accept
7850      *          the required leading arguments, or if the method handle types do
7851      *          not match in their return types and their
7852      *          corresponding trailing parameters
7853      *
7854      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7855      * @since 9
7856      */
7857     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7858         Class<?>[] targetParamTypes = target.type().ptypes();
7859         Class<?> rtype = target.type().returnType();
7860 
7861         tryFinallyChecks(target, cleanup);
7862 
7863         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7864         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7865         // target parameter list.
7866         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false);
7867 
7868         // Ensure that the intrinsic type checks the instance thrown by the
7869         // target against the first parameter of cleanup
7870         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7871 
7872         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7873         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7874     }
7875 
7876     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7877         Class<?> rtype = target.type().returnType();
7878         if (rtype != cleanup.type().returnType()) {
7879             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7880         }
7881         MethodType cleanupType = cleanup.type();
7882         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7883             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7884         }
7885         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7886             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7887         }
7888         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7889         // target parameter list.
7890         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7891         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7892             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7893                     cleanup.type(), target.type());
7894         }
7895     }
7896 
7897     /**
7898      * Creates a table switch method handle, which can be used to switch over a set of target
7899      * method handles, based on a given target index, called selector.
7900      * <p>
7901      * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7902      * and where {@code N} is the number of target method handles, the table switch method
7903      * handle will invoke the n-th target method handle from the list of target method handles.
7904      * <p>
7905      * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7906      * method handle will invoke the given fallback method handle.
7907      * <p>
7908      * All method handles passed to this method must have the same type, with the additional
7909      * requirement that the leading parameter be of type {@code int}. The leading parameter
7910      * represents the selector.
7911      * <p>
7912      * Any trailing parameters present in the type will appear on the returned table switch
7913      * method handle as well. Any arguments assigned to these parameters will be forwarded,
7914      * together with the selector value, to the selected method handle when invoking it.
7915      *
7916      * @apiNote Example:
7917      * The cases each drop the {@code selector} value they are given, and take an additional
7918      * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7919      * to a specific constant label string for each case:
7920      * {@snippet lang="java" :
7921      * MethodHandles.Lookup lookup = MethodHandles.lookup();
7922      * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7923      *         MethodType.methodType(String.class, String.class));
7924      * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7925      *
7926      * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7927      * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7928      * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7929      *
7930      * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7931      *     caseDefault,
7932      *     case0,
7933      *     case1
7934      * );
7935      *
7936      * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7937      * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7938      * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7939      * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7940      * }
7941      *
7942      * @param fallback the fallback method handle that is called when the selector is not
7943      *                 within the range {@code [0, N)}.
7944      * @param targets array of target method handles.
7945      * @return the table switch method handle.
7946      * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7947      *                              any of the elements of the {@code targets} array are
7948      *                              {@code null}.
7949      * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7950      *                                  parameter of the fallback handle or any of the target
7951      *                                  handles is not {@code int}, or if the types of
7952      *                                  the fallback handle and all of target handles are
7953      *                                  not the same.
7954      */
7955     public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7956         Objects.requireNonNull(fallback);
7957         Objects.requireNonNull(targets);
7958         targets = targets.clone();
7959         MethodType type = tableSwitchChecks(fallback, targets);
7960         return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7961     }
7962 
7963     private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7964         if (caseActions.length == 0)
7965             throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7966 
7967         MethodType expectedType = defaultCase.type();
7968 
7969         if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7970             throw new IllegalArgumentException(
7971                 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7972 
7973         for (MethodHandle mh : caseActions) {
7974             Objects.requireNonNull(mh);
7975             if (mh.type() != expectedType)
7976                 throw new IllegalArgumentException(
7977                     "Case actions must have the same type: " + Arrays.toString(caseActions));
7978         }
7979 
7980         return expectedType;
7981     }
7982 
7983     /**
7984      * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions.
7985      * <p>
7986      * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where
7987      * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed
7988      * to the target var handle.
7989      * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from
7990      * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function)
7991      * is processed using the second filter and returned to the caller. More advanced access mode types, such as
7992      * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time.
7993      * <p>
7994      * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and
7995      * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case,
7996      * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which
7997      * will be appended to the coordinates of the target var handle).
7998      * <p>
7999      * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will
8000      * throw an {@link IllegalStateException}.
8001      * <p>
8002      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8003      * atomic access guarantees as those featured by the target var handle.
8004      *
8005      * @param target the target var handle
8006      * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target}
8007      * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S}
8008      * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions.
8009      * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types
8010      * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle,
8011      * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions.
8012      * @throws NullPointerException if any of the arguments is {@code null}.
8013      * @since 22
8014      */
8015     public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
8016         return VarHandles.filterValue(target, filterToTarget, filterFromTarget);
8017     }
8018 
8019     /**
8020      * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions.
8021      * <p>
8022      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values
8023      * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types
8024      * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the
8025      * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered
8026      * by the adaptation) to the target var handle.
8027      * <p>
8028      * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn},
8029      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
8030      * <p>
8031      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8032      * throw an {@link IllegalStateException}.
8033      * <p>
8034      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8035      * atomic access guarantees as those featured by the target var handle.
8036      *
8037      * @param target the target var handle
8038      * @param pos the position of the first coordinate to be transformed
8039      * @param filters the unary functions which are used to transform coordinates starting at position {@code pos}
8040      * @return an adapter var handle which accepts new coordinate types, applying the provided transformation
8041      * to the new coordinate values.
8042      * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types
8043      * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting
8044      * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8045      * or if more filters are provided than the actual number of coordinate types available starting at {@code pos},
8046      * or if it's determined that any of the filters throws any checked exceptions.
8047      * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}.
8048      * @since 22
8049      */
8050     public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
8051         return VarHandles.filterCoordinates(target, pos, filters);
8052     }
8053 
8054     /**
8055      * Provides a target var handle with one or more <em>bound coordinates</em>
8056      * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less
8057      * coordinate types than the target var handle.
8058      * <p>
8059      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values
8060      * are joined with bound coordinate values, and then passed to the target var handle.
8061      * <p>
8062      * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn },
8063      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
8064      * <p>
8065      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8066      * atomic access guarantees as those featured by the target var handle.
8067      *
8068      * @param target the var handle to invoke after the bound coordinates are inserted
8069      * @param pos the position of the first coordinate to be inserted
8070      * @param values the series of bound coordinates to insert
8071      * @return an adapter var handle which inserts additional coordinates,
8072      *         before calling the target var handle
8073      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8074      * or if more values are provided than the actual number of coordinate types available starting at {@code pos}.
8075      * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types
8076      * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos}
8077      * of the target var handle.
8078      * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}.
8079      * @since 22
8080      */
8081     public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
8082         return VarHandles.insertCoordinates(target, pos, values);
8083     }
8084 
8085     /**
8086      * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them
8087      * so that the new coordinates match the provided ones.
8088      * <p>
8089      * The given array controls the reordering.
8090      * Call {@code #I} the number of incoming coordinates (the value
8091      * {@code newCoordinates.size()}), and call {@code #O} the number
8092      * of outgoing coordinates (the number of coordinates associated with the target var handle).
8093      * Then the length of the reordering array must be {@code #O},
8094      * and each element must be a non-negative number less than {@code #I}.
8095      * For every {@code N} less than {@code #O}, the {@code N}-th
8096      * outgoing coordinate will be taken from the {@code I}-th incoming
8097      * coordinate, where {@code I} is {@code reorder[N]}.
8098      * <p>
8099      * No coordinate value conversions are applied.
8100      * The type of each incoming coordinate, as determined by {@code newCoordinates},
8101      * must be identical to the type of the corresponding outgoing coordinate
8102      * in the target var handle.
8103      * <p>
8104      * The reordering array need not specify an actual permutation.
8105      * An incoming coordinate will be duplicated if its index appears
8106      * more than once in the array, and an incoming coordinate will be dropped
8107      * if its index does not appear in the array.
8108      * <p>
8109      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8110      * atomic access guarantees as those featured by the target var handle.
8111      * @param target the var handle to invoke after the coordinates have been reordered
8112      * @param newCoordinates the new coordinate types
8113      * @param reorder an index array which controls the reordering
8114      * @return an adapter var handle which re-arranges the incoming coordinate values,
8115      * before calling the target var handle
8116      * @throws IllegalArgumentException if the index array length is not equal to
8117      * the number of coordinates of the target var handle, or if any index array element is not a valid index for
8118      * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in
8119      * the target var handle and in {@code newCoordinates} are not identical.
8120      * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}.
8121      * @since 22
8122      */
8123     public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
8124         return VarHandles.permuteCoordinates(target, newCoordinates, reorder);
8125     }
8126 
8127     /**
8128      * Adapts a target var handle by pre-processing
8129      * a sub-sequence of its coordinate values with a filter (a method handle).
8130      * The pre-processed coordinates are replaced by the result (if any) of the
8131      * filter function and the target var handle is then called on the modified (usually shortened)
8132      * coordinate list.
8133      * <p>
8134      * If {@code R} is the return type of the filter, then:
8135      * <ul>
8136      * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in
8137      * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos}
8138      * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first,
8139      * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the
8140      * target var handle.</li>
8141      * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the
8142      * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle
8143      * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a
8144      * downstream invocation of the target var handle.</li>
8145      * </ul>
8146      * <p>
8147      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8148      * throw an {@link IllegalStateException}.
8149      * <p>
8150      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8151      * atomic access guarantees as those featured by the target var handle.
8152      *
8153      * @param target the var handle to invoke after the coordinates have been filtered
8154      * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted
8155      * @param filter the filter method handle
8156      * @return an adapter var handle which filters the incoming coordinate values,
8157      * before calling the target var handle
8158      * @throws IllegalArgumentException if the return type of {@code filter}
8159      * is not void, and it is not the same as the {@code pos} coordinate of the target var handle,
8160      * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8161      * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>,
8162      * or if it's determined that {@code filter} throws any checked exceptions.
8163      * @throws NullPointerException if any of the arguments is {@code null}.
8164      * @since 22
8165      */
8166     public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
8167         return VarHandles.collectCoordinates(target, pos, filter);
8168     }
8169 
8170     /**
8171      * Returns a var handle which will discard some dummy coordinates before delegating to the
8172      * target var handle. As a consequence, the resulting var handle will feature more
8173      * coordinate types than the target var handle.
8174      * <p>
8175      * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the
8176      * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede
8177      * the target's real arguments; if {@code pos} is <i>N</i> they will come after.
8178      * <p>
8179      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8180      * atomic access guarantees as those featured by the target var handle.
8181      *
8182      * @param target the var handle to invoke after the dummy coordinates are dropped
8183      * @param pos position of the first coordinate to drop (zero for the leftmost)
8184      * @param valueTypes the type(s) of the coordinate(s) to drop
8185      * @return an adapter var handle which drops some dummy coordinates,
8186      *         before calling the target var handle
8187      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive.
8188      * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}.
8189      * @since 22
8190      */
8191     public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
8192         return VarHandles.dropCoordinates(target, pos, valueTypes);
8193     }
8194 }