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.value.PrimitiveClass;
  30 import jdk.internal.foreign.Utils;
  31 import jdk.internal.javac.PreviewFeature;
  32 import jdk.internal.misc.Unsafe;
  33 import jdk.internal.misc.VM;
  34 import jdk.internal.org.objectweb.asm.ClassReader;
  35 import jdk.internal.org.objectweb.asm.Opcodes;
  36 import jdk.internal.org.objectweb.asm.Type;
  37 import jdk.internal.reflect.CallerSensitive;
  38 import jdk.internal.reflect.CallerSensitiveAdapter;
  39 import jdk.internal.reflect.Reflection;
  40 import jdk.internal.util.ClassFileDumper;
  41 import jdk.internal.vm.annotation.ForceInline;
  42 import sun.invoke.util.ValueConversions;
  43 import sun.invoke.util.VerifyAccess;
  44 import sun.invoke.util.Wrapper;
  45 import sun.reflect.misc.ReflectUtil;
  46 import sun.security.util.SecurityConstants;
  47 
  48 import java.lang.constant.ConstantDescs;
  49 import java.lang.foreign.GroupLayout;
  50 import java.lang.foreign.MemoryLayout;
  51 import java.lang.foreign.MemorySegment;
  52 import java.lang.foreign.ValueLayout;
  53 import java.lang.invoke.LambdaForm.BasicType;
  54 import java.lang.reflect.Constructor;
  55 import java.lang.reflect.Field;
  56 import java.lang.reflect.Member;
  57 import java.lang.reflect.Method;
  58 import java.lang.reflect.Modifier;
  59 import java.nio.ByteOrder;
  60 import java.security.ProtectionDomain;
  61 import java.util.ArrayList;
  62 import java.util.Arrays;
  63 import java.util.BitSet;
  64 import java.util.Comparator;
  65 import java.util.Iterator;
  66 import java.util.List;
  67 import java.util.Objects;
  68 import java.util.Set;
  69 import java.util.concurrent.ConcurrentHashMap;
  70 import java.util.stream.Stream;
  71 
  72 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
  73 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  74 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  75 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
  76 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  77 import static java.lang.invoke.MethodHandleStatics.newInternalError;
  78 import static java.lang.invoke.MethodType.methodType;
  79 
  80 /**
  81  * This class consists exclusively of static methods that operate on or return
  82  * method handles. They fall into several categories:
  83  * <ul>
  84  * <li>Lookup methods which help create method handles for methods and fields.
  85  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  86  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  87  * </ul>
  88  * A lookup, combinator, or factory method will fail and throw an
  89  * {@code IllegalArgumentException} if the created method handle's type
  90  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  91  *
  92  * @author John Rose, JSR 292 EG
  93  * @since 1.7
  94  */
  95 public class MethodHandles {
  96 
  97     private MethodHandles() { }  // do not instantiate
  98 
  99     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
 100 
 101     // See IMPL_LOOKUP below.
 102 
 103     //// Method handle creation from ordinary methods.
 104 
 105     /**
 106      * Returns a {@link Lookup lookup object} with
 107      * full capabilities to emulate all supported bytecode behaviors of the caller.
 108      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
 109      * Factory methods on the lookup object can create
 110      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
 111      * for any member that the caller has access to via bytecodes,
 112      * including protected and private fields and methods.
 113      * This lookup object is created by the original lookup class
 114      * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
 115      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 116      * Do not store it in place where untrusted code can access it.
 117      * <p>
 118      * This method is caller sensitive, which means that it may return different
 119      * values to different callers.
 120      * In cases where {@code MethodHandles.lookup} is called from a context where
 121      * there is no caller frame on the stack (e.g. when called directly
 122      * from a JNI attached thread), {@code IllegalCallerException} is thrown.
 123      * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will
 124      * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()}
 125      * to obtain a low-privileged lookup instead.
 126      * @return a lookup object for the caller of this method, with
 127      * {@linkplain Lookup#ORIGINAL original} and
 128      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
 129      * @throws IllegalCallerException if there is no caller frame on the stack.
 130      */
 131     @CallerSensitive
 132     @ForceInline // to ensure Reflection.getCallerClass optimization
 133     public static Lookup lookup() {
 134         final Class<?> c = Reflection.getCallerClass();
 135         if (c == null) {
 136             throw new IllegalCallerException("no caller frame");
 137         }
 138         return new Lookup(c);
 139     }
 140 
 141     /**
 142      * This lookup method is the alternate implementation of
 143      * the lookup method with a leading caller class argument which is
 144      * non-caller-sensitive.  This method is only invoked by reflection
 145      * and method handle.
 146      */
 147     @CallerSensitiveAdapter
 148     private static Lookup lookup(Class<?> caller) {
 149         if (caller.getClassLoader() == null) {
 150             throw newInternalError("calling lookup() reflectively is not supported: "+caller);
 151         }
 152         return new Lookup(caller);
 153     }
 154 
 155     /**
 156      * Returns a {@link Lookup lookup object} which is trusted minimally.
 157      * The lookup has the {@code UNCONDITIONAL} mode.
 158      * It can only be used to create method handles to public members of
 159      * public classes in packages that are exported unconditionally.
 160      * <p>
 161      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 162      * of this lookup object will be {@link java.lang.Object}.
 163      *
 164      * @apiNote The use of Object is conventional, and because the lookup modes are
 165      * limited, there is no special access provided to the internals of Object, its package
 166      * or its module.  This public lookup object or other lookup object with
 167      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 168      * is not used to determine the lookup context.
 169      *
 170      * <p style="font-size:smaller;">
 171      * <em>Discussion:</em>
 172      * The lookup class can be changed to any other class {@code C} using an expression of the form
 173      * {@link Lookup#in publicLookup().in(C.class)}.
 174      * A public lookup object is always subject to
 175      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 176      * Also, it cannot access
 177      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 178      * @return a lookup object which is trusted minimally
 179      *
 180      * @revised 9
 181      */
 182     public static Lookup publicLookup() {
 183         return Lookup.PUBLIC_LOOKUP;
 184     }
 185 
 186     /**
 187      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 188      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 189      * The returned lookup object can provide access to classes in modules and packages,
 190      * and members of those classes, outside the normal rules of Java access control,
 191      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 192      * <p>
 193      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 194      * allowed to do deep reflection on module {@code M2} and package of the target class
 195      * if and only if all of the following conditions are {@code true}:
 196      * <ul>
 197      * <li>If there is a security manager, its {@code checkPermission} method is
 198      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 199      * that must return normally.
 200      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 201      * full privilege access}.  Specifically:
 202      *   <ul>
 203      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 204      *         (This is because otherwise there would be no way to ensure the original lookup
 205      *         creator was a member of any particular module, and so any subsequent checks
 206      *         for readability and qualified exports would become ineffective.)
 207      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 208      *         (This is because an application intending to share intra-module access
 209      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 210      *         deep reflection to its own module.)
 211      *   </ul>
 212      * <li>The target class must be a proper class, not a primitive or array class.
 213      * (Thus, {@code M2} is well-defined.)
 214      * <li>If the caller module {@code M1} differs from
 215      * the target module {@code M2} then both of the following must be true:
 216      *   <ul>
 217      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 218      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 219      *         containing the target class to at least {@code M1}.</li>
 220      *   </ul>
 221      * </ul>
 222      * <p>
 223      * If any of the above checks is violated, this method fails with an
 224      * exception.
 225      * <p>
 226      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 227      * returns a {@code Lookup} on {@code targetClass} with
 228      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 229      * with {@code null} previous lookup class.
 230      * <p>
 231      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 232      * returns a {@code Lookup} on {@code targetClass} that records
 233      * the lookup class of the caller as the new previous lookup class with
 234      * {@code PRIVATE} access but no {@code MODULE} access.
 235      * <p>
 236      * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
 237      *
 238      * @apiNote The {@code Lookup} object returned by this method is allowed to
 239      * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
 240      * of {@code targetClass}. Extreme caution should be taken when opening a package
 241      * to another module as such defined classes have the same full privilege
 242      * access as other members in {@code targetClass}'s module.
 243      *
 244      * @param targetClass the target class
 245      * @param caller the caller lookup object
 246      * @return a lookup object for the target class, with private access
 247      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 248      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 249      * @throws SecurityException if denied by the security manager
 250      * @throws IllegalAccessException if any of the other access checks specified above fails
 251      * @since 9
 252      * @see Lookup#dropLookupMode
 253      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 254      */
 255     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 256         if (caller.allowedModes == Lookup.TRUSTED) {
 257             return new Lookup(targetClass);
 258         }
 259 
 260         @SuppressWarnings("removal")
 261         SecurityManager sm = System.getSecurityManager();
 262         if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 263         if (targetClass.isPrimitive())
 264             throw new IllegalArgumentException(targetClass + " is a primitive class");
 265         if (targetClass.isArray())
 266             throw new IllegalArgumentException(targetClass + " is an array class");
 267         // Ensure that we can reason accurately about private and module access.
 268         int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
 269         if ((caller.lookupModes() & requireAccess) != requireAccess)
 270             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 271 
 272         // previous lookup class is never set if it has MODULE access
 273         assert caller.previousLookupClass() == null;
 274 
 275         Class<?> callerClass = caller.lookupClass();
 276         Module callerModule = callerClass.getModule();  // M1
 277         Module targetModule = targetClass.getModule();  // M2
 278         Class<?> newPreviousClass = null;
 279         int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
 280 
 281         if (targetModule != callerModule) {
 282             if (!callerModule.canRead(targetModule))
 283                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 284             if (targetModule.isNamed()) {
 285                 String pn = targetClass.getPackageName();
 286                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 287                 if (!targetModule.isOpen(pn, callerModule))
 288                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 289             }
 290 
 291             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 292             newPreviousClass = callerClass;
 293             newModes &= ~Lookup.MODULE;
 294         }
 295         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 296     }
 297 
 298     /**
 299      * Returns the <em>class data</em> associated with the lookup class
 300      * of the given {@code caller} lookup object, or {@code null}.
 301      *
 302      * <p> A hidden class with class data can be created by calling
 303      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 304      * Lookup::defineHiddenClassWithClassData}.
 305      * This method will cause the static class initializer of the lookup
 306      * class of the given {@code caller} lookup object be executed if
 307      * it has not been initialized.
 308      *
 309      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 310      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 311      * {@code null} is returned if this method is called on the lookup object
 312      * on these classes.
 313      *
 314      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 315      * must have {@linkplain Lookup#ORIGINAL original access}
 316      * in order to retrieve the class data.
 317      *
 318      * @apiNote
 319      * This method can be called as a bootstrap method for a dynamically computed
 320      * constant.  A framework can create a hidden class with class data, for
 321      * example that can be {@code Class} or {@code MethodHandle} object.
 322      * The class data is accessible only to the lookup object
 323      * created by the original caller but inaccessible to other members
 324      * in the same nest.  If a framework passes security sensitive objects
 325      * to a hidden class via class data, it is recommended to load the value
 326      * of class data as a dynamically computed constant instead of storing
 327      * the class data in private static field(s) which are accessible to
 328      * other nestmates.
 329      *
 330      * @param <T> the type to cast the class data object to
 331      * @param caller the lookup context describing the class performing the
 332      * operation (normally stacked by the JVM)
 333      * @param name must be {@link ConstantDescs#DEFAULT_NAME}
 334      *             ({@code "_"})
 335      * @param type the type of the class data
 336      * @return the value of the class data if present in the lookup class;
 337      * otherwise {@code null}
 338      * @throws IllegalArgumentException if name is not {@code "_"}
 339      * @throws IllegalAccessException if the lookup context does not have
 340      * {@linkplain Lookup#ORIGINAL original} access
 341      * @throws ClassCastException if the class data cannot be converted to
 342      * the given {@code type}
 343      * @throws NullPointerException if {@code caller} or {@code type} argument
 344      * is {@code null}
 345      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 346      * @see MethodHandles#classDataAt(Lookup, String, Class, int)
 347      * @since 16
 348      * @jvms 5.5 Initialization
 349      */
 350      public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 351          Objects.requireNonNull(caller);
 352          Objects.requireNonNull(type);
 353          if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
 354              throw new IllegalArgumentException("name must be \"_\": " + name);
 355          }
 356 
 357          if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL)  {
 358              throw new IllegalAccessException(caller + " does not have ORIGINAL access");
 359          }
 360 
 361          Object classdata = classData(caller.lookupClass());
 362          if (classdata == null) return null;
 363 
 364          try {
 365              return BootstrapMethodInvoker.widenAndCast(classdata, type);
 366          } catch (RuntimeException|Error e) {
 367              throw e; // let CCE and other runtime exceptions through
 368          } catch (Throwable e) {
 369              throw new InternalError(e);
 370          }
 371     }
 372 
 373     /*
 374      * Returns the class data set by the VM in the Class::classData field.
 375      *
 376      * This is also invoked by LambdaForms as it cannot use condy via
 377      * MethodHandles::classData due to bootstrapping issue.
 378      */
 379     static Object classData(Class<?> c) {
 380         UNSAFE.ensureClassInitialized(c);
 381         return SharedSecrets.getJavaLangAccess().classData(c);
 382     }
 383 
 384     /**
 385      * Returns the element at the specified index in the
 386      * {@linkplain #classData(Lookup, String, Class) class data},
 387      * if the class data associated with the lookup class
 388      * of the given {@code caller} lookup object is a {@code List}.
 389      * If the class data is not present in this lookup class, this method
 390      * returns {@code null}.
 391      *
 392      * <p> A hidden class with class data can be created by calling
 393      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 394      * Lookup::defineHiddenClassWithClassData}.
 395      * This method will cause the static class initializer of the lookup
 396      * class of the given {@code caller} lookup object be executed if
 397      * it has not been initialized.
 398      *
 399      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 400      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 401      * {@code null} is returned if this method is called on the lookup object
 402      * on these classes.
 403      *
 404      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 405      * must have {@linkplain Lookup#ORIGINAL original access}
 406      * in order to retrieve the class data.
 407      *
 408      * @apiNote
 409      * This method can be called as a bootstrap method for a dynamically computed
 410      * constant.  A framework can create a hidden class with class data, for
 411      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 412      * one object and use this method to load one element at a specific index.
 413      * The class data is accessible only to the lookup object
 414      * created by the original caller but inaccessible to other members
 415      * in the same nest.  If a framework passes security sensitive objects
 416      * to a hidden class via class data, it is recommended to load the value
 417      * of class data as a dynamically computed constant instead of storing
 418      * the class data in private static field(s) which are accessible to other
 419      * nestmates.
 420      *
 421      * @param <T> the type to cast the result object to
 422      * @param caller the lookup context describing the class performing the
 423      * operation (normally stacked by the JVM)
 424      * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
 425      *             ({@code "_"})
 426      * @param type the type of the element at the given index in the class data
 427      * @param index index of the element in the class data
 428      * @return the element at the given index in the class data
 429      * if the class data is present; otherwise {@code null}
 430      * @throws IllegalArgumentException if name is not {@code "_"}
 431      * @throws IllegalAccessException if the lookup context does not have
 432      * {@linkplain Lookup#ORIGINAL original} access
 433      * @throws ClassCastException if the class data cannot be converted to {@code List}
 434      * or the element at the specified index cannot be converted to the given type
 435      * @throws IndexOutOfBoundsException if the index is out of range
 436      * @throws NullPointerException if {@code caller} or {@code type} argument is
 437      * {@code null}; or if unboxing operation fails because
 438      * the element at the given index is {@code null}
 439      *
 440      * @since 16
 441      * @see #classData(Lookup, String, Class)
 442      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 443      */
 444     public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
 445             throws IllegalAccessException
 446     {
 447         @SuppressWarnings("unchecked")
 448         List<Object> classdata = (List<Object>)classData(caller, name, List.class);
 449         if (classdata == null) return null;
 450 
 451         try {
 452             Object element = classdata.get(index);
 453             return BootstrapMethodInvoker.widenAndCast(element, type);
 454         } catch (RuntimeException|Error e) {
 455             throw e; // let specified exceptions and other runtime exceptions/errors through
 456         } catch (Throwable e) {
 457             throw new InternalError(e);
 458         }
 459     }
 460 
 461     /**
 462      * Performs an unchecked "crack" of a
 463      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 464      * The result is as if the user had obtained a lookup object capable enough
 465      * to crack the target method handle, called
 466      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 467      * on the target to obtain its symbolic reference, and then called
 468      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 469      * to resolve the symbolic reference to a member.
 470      * <p>
 471      * If there is a security manager, its {@code checkPermission} method
 472      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 473      * @param <T> the desired type of the result, either {@link Member} or a subtype
 474      * @param target a direct method handle to crack into symbolic reference components
 475      * @param expected a class object representing the desired result type {@code T}
 476      * @return a reference to the method, constructor, or field object
 477      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 478      * @throws    NullPointerException if either argument is {@code null}
 479      * @throws    IllegalArgumentException if the target is not a direct method handle
 480      * @throws    ClassCastException if the member is not of the expected type
 481      * @since 1.8
 482      */
 483     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 484         @SuppressWarnings("removal")
 485         SecurityManager smgr = System.getSecurityManager();
 486         if (smgr != null)  smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 487         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 488         return lookup.revealDirect(target).reflectAs(expected, lookup);
 489     }
 490 
 491     /**
 492      * A <em>lookup object</em> is a factory for creating method handles,
 493      * when the creation requires access checking.
 494      * Method handles do not perform
 495      * access checks when they are called, but rather when they are created.
 496      * Therefore, method handle access
 497      * restrictions must be enforced when a method handle is created.
 498      * The caller class against which those restrictions are enforced
 499      * is known as the {@linkplain #lookupClass() lookup class}.
 500      * <p>
 501      * A lookup class which needs to create method handles will call
 502      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 503      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 504      * determined, and securely stored in the {@code Lookup} object.
 505      * The lookup class (or its delegates) may then use factory methods
 506      * on the {@code Lookup} object to create method handles for access-checked members.
 507      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 508      * even private ones.
 509      *
 510      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 511      * The factory methods on a {@code Lookup} object correspond to all major
 512      * use cases for methods, constructors, and fields.
 513      * Each method handle created by a factory method is the functional
 514      * equivalent of a particular <em>bytecode behavior</em>.
 515      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 516      * the Java Virtual Machine Specification.)
 517      * Here is a summary of the correspondence between these factory methods and
 518      * the behavior of the resulting method handles:
 519      * <table class="striped">
 520      * <caption style="display:none">lookup method behaviors</caption>
 521      * <thead>
 522      * <tr>
 523      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 524      *     <th scope="col">member</th>
 525      *     <th scope="col">bytecode behavior</th>
 526      * </tr>
 527      * </thead>
 528      * <tbody>
 529      * <tr>
 530      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 531      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 532      * </tr>
 533      * <tr>
 534      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 535      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 536      * </tr>
 537      * <tr>
 538      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 539      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 540      * </tr>
 541      * <tr>
 542      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 543      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 544      * </tr>
 545      * <tr>
 546      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 547      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 548      * </tr>
 549      * <tr>
 550      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 551      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 552      * </tr>
 553      * <tr>
 554      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 555      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 556      * </tr>
 557      * <tr>
 558      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 559      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 560      * </tr>
 561      * <tr>
 562      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 563      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 564      * </tr>
 565      * <tr>
 566      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 567      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 568      * </tr>
 569      * <tr>
 570      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 571      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 572      * </tr>
 573      * <tr>
 574      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 575      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 576      * </tr>
 577      * <tr>
 578      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 579      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 580      * </tr>
 581      * <tr>
 582      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 583      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 584      * </tr>
 585      * </tbody>
 586      * </table>
 587      *
 588      * Here, the type {@code C} is the class or interface being searched for a member,
 589      * documented as a parameter named {@code refc} in the lookup methods.
 590      * The method type {@code MT} is composed from the return type {@code T}
 591      * and the sequence of argument types {@code A*}.
 592      * The constructor also has a sequence of argument types {@code A*} and
 593      * is deemed to return the newly-created object of type {@code C}.
 594      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 595      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 596      * if it is present, it is always the leading argument to the method handle invocation.
 597      * (In the case of some {@code protected} members, {@code this} may be
 598      * restricted in type to the lookup class; see below.)
 599      * The name {@code arg} stands for all the other method handle arguments.
 600      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 601      * stands for a null reference if the accessed method or field is static,
 602      * and {@code this} otherwise.
 603      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 604      * for reflective objects corresponding to the given members declared in type {@code C}.
 605      * <p>
 606      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 607      * as if by {@code ldc CONSTANT_Class}.
 608      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 609      * <p>
 610      * In cases where the given member is of variable arity (i.e., a method or constructor)
 611      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 612      * In all other cases, the returned method handle will be of fixed arity.
 613      * <p style="font-size:smaller;">
 614      * <em>Discussion:</em>
 615      * The equivalence between looked-up method handles and underlying
 616      * class members and bytecode behaviors
 617      * can break down in a few ways:
 618      * <ul style="font-size:smaller;">
 619      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 620      * the lookup can still succeed, even when there is no equivalent
 621      * Java expression or bytecoded constant.
 622      * <li>Likewise, if {@code T} or {@code MT}
 623      * is not symbolically accessible from the lookup class's loader,
 624      * the lookup can still succeed.
 625      * For example, lookups for {@code MethodHandle.invokeExact} and
 626      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 627      * <li>If there is a security manager installed, it can forbid the lookup
 628      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 629      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 630      * constant is not subject to security manager checks.
 631      * <li>If the looked-up method has a
 632      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 633      * the method handle creation may fail with an
 634      * {@code IllegalArgumentException}, due to the method handle type having
 635      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 636      * </ul>
 637      *
 638      * <h2><a id="access"></a>Access checking</h2>
 639      * Access checks are applied in the factory methods of {@code Lookup},
 640      * when a method handle is created.
 641      * This is a key difference from the Core Reflection API, since
 642      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 643      * performs access checking against every caller, on every call.
 644      * <p>
 645      * All access checks start from a {@code Lookup} object, which
 646      * compares its recorded lookup class against all requests to
 647      * create method handles.
 648      * A single {@code Lookup} object can be used to create any number
 649      * of access-checked method handles, all checked against a single
 650      * lookup class.
 651      * <p>
 652      * A {@code Lookup} object can be shared with other trusted code,
 653      * such as a metaobject protocol.
 654      * A shared {@code Lookup} object delegates the capability
 655      * to create method handles on private members of the lookup class.
 656      * Even if privileged code uses the {@code Lookup} object,
 657      * the access checking is confined to the privileges of the
 658      * original lookup class.
 659      * <p>
 660      * A lookup can fail, because
 661      * the containing class is not accessible to the lookup class, or
 662      * because the desired class member is missing, or because the
 663      * desired class member is not accessible to the lookup class, or
 664      * because the lookup object is not trusted enough to access the member.
 665      * In the case of a field setter function on a {@code final} field,
 666      * finality enforcement is treated as a kind of access control,
 667      * and the lookup will fail, except in special cases of
 668      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 669      * In any of these cases, a {@code ReflectiveOperationException} will be
 670      * thrown from the attempted lookup.  The exact class will be one of
 671      * the following:
 672      * <ul>
 673      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 674      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 675      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 676      * </ul>
 677      * <p>
 678      * In general, the conditions under which a method handle may be
 679      * looked up for a method {@code M} are no more restrictive than the conditions
 680      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 681      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 682      * a method handle lookup will generally raise a corresponding
 683      * checked exception, such as {@code NoSuchMethodException}.
 684      * And the effect of invoking the method handle resulting from the lookup
 685      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 686      * to executing the compiled, verified, and resolved call to {@code M}.
 687      * The same point is true of fields and constructors.
 688      * <p style="font-size:smaller;">
 689      * <em>Discussion:</em>
 690      * Access checks only apply to named and reflected methods,
 691      * constructors, and fields.
 692      * Other method handle creation methods, such as
 693      * {@link MethodHandle#asType MethodHandle.asType},
 694      * do not require any access checks, and are used
 695      * independently of any {@code Lookup} object.
 696      * <p>
 697      * If the desired member is {@code protected}, the usual JVM rules apply,
 698      * including the requirement that the lookup class must either be in the
 699      * same package as the desired member, or must inherit that member.
 700      * (See the Java Virtual Machine Specification, sections {@jvms
 701      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 702      * In addition, if the desired member is a non-static field or method
 703      * in a different package, the resulting method handle may only be applied
 704      * to objects of the lookup class or one of its subclasses.
 705      * This requirement is enforced by narrowing the type of the leading
 706      * {@code this} parameter from {@code C}
 707      * (which will necessarily be a superclass of the lookup class)
 708      * to the lookup class itself.
 709      * <p>
 710      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 711      * that the receiver argument must match both the resolved method <em>and</em>
 712      * the current class.  Again, this requirement is enforced by narrowing the
 713      * type of the leading parameter to the resulting method handle.
 714      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 715      * <p>
 716      * The JVM represents constructors and static initializer blocks as internal methods
 717      * with special names ({@value ConstantDescs#INIT_NAME},
 718      * {@value ConstantDescs#VNEW_NAME} and {@value ConstantDescs#CLASS_INIT_NAME}).
 719      * The internal syntax of invocation instructions allows them to refer to such internal
 720      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 721      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 722      * <p>
 723      * If the relationship between nested types is expressed directly through the
 724      * {@code NestHost} and {@code NestMembers} attributes
 725      * (see the Java Virtual Machine Specification, sections {@jvms
 726      * 4.7.28} and {@jvms 4.7.29}),
 727      * then the associated {@code Lookup} object provides direct access to
 728      * the lookup class and all of its nestmates
 729      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 730      * Otherwise, access between nested classes is obtained by the Java compiler creating
 731      * a wrapper method to access a private method of another class in the same nest.
 732      * For example, a nested class {@code C.D}
 733      * can access private members within other related classes such as
 734      * {@code C}, {@code C.D.E}, or {@code C.B},
 735      * but the Java compiler may need to generate wrapper methods in
 736      * those related classes.  In such cases, a {@code Lookup} object on
 737      * {@code C.E} would be unable to access those private members.
 738      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 739      * which can transform a lookup on {@code C.E} into one on any of those other
 740      * classes, without special elevation of privilege.
 741      * <p>
 742      * The accesses permitted to a given lookup object may be limited,
 743      * according to its set of {@link #lookupModes lookupModes},
 744      * to a subset of members normally accessible to the lookup class.
 745      * For example, the {@link MethodHandles#publicLookup publicLookup}
 746      * method produces a lookup object which is only allowed to access
 747      * public members in public classes of exported packages.
 748      * The caller sensitive method {@link MethodHandles#lookup lookup}
 749      * produces a lookup object with full capabilities relative to
 750      * its caller class, to emulate all supported bytecode behaviors.
 751      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 752      * with fewer access modes than the original lookup object.
 753      *
 754      * <p style="font-size:smaller;">
 755      * <a id="privacc"></a>
 756      * <em>Discussion of private and module access:</em>
 757      * We say that a lookup has <em>private access</em>
 758      * if its {@linkplain #lookupModes lookup modes}
 759      * include the possibility of accessing {@code private} members
 760      * (which includes the private members of nestmates).
 761      * As documented in the relevant methods elsewhere,
 762      * only lookups with private access possess the following capabilities:
 763      * <ul style="font-size:smaller;">
 764      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 765      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 766      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 767      *     for classes accessible to the lookup class
 768      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 769      *     within the same package member
 770      * </ul>
 771      * <p style="font-size:smaller;">
 772      * Similarly, a lookup with module access ensures that the original lookup creator was
 773      * a member in the same module as the lookup class.
 774      * <p style="font-size:smaller;">
 775      * Private and module access are independently determined modes; a lookup may have
 776      * either or both or neither.  A lookup which possesses both access modes is said to
 777      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
 778      * <p style="font-size:smaller;">
 779      * A lookup with <em>original access</em> ensures that this lookup is created by
 780      * the original lookup class and the bootstrap method invoked by the VM.
 781      * Such a lookup with original access also has private and module access
 782      * which has the following additional capability:
 783      * <ul style="font-size:smaller;">
 784      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 785      *     such as {@code Class.forName}
 786      * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
 787      * class data} associated with the lookup class</li>
 788      * </ul>
 789      * <p style="font-size:smaller;">
 790      * Each of these permissions is a consequence of the fact that a lookup object
 791      * with private access can be securely traced back to an originating class,
 792      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 793      * can be reliably determined and emulated by method handles.
 794      *
 795      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 796      * When a lookup class in one module {@code M1} accesses a class in another module
 797      * {@code M2}, extra access checking is performed beyond the access mode bits.
 798      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 799      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 800      * and when the type is in a package of {@code M2} that is exported to
 801      * at least {@code M1}.
 802      * <p>
 803      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 804      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 805      * MethodHandles.privateLookupIn} methods.
 806      * Teleporting across modules will always record the original lookup class as
 807      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 808      * and drops {@link Lookup#MODULE MODULE} access.
 809      * If the target class is in the same module as the lookup class {@code C},
 810      * then the target class becomes the new lookup class
 811      * and there is no change to the previous lookup class.
 812      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 813      * {@code C} becomes the new previous lookup class
 814      * and the target class becomes the new lookup class.
 815      * In that case, if there was already a previous lookup class in {@code M0},
 816      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 817      * drops all privileges.
 818      * For example,
 819      * {@snippet lang="java" :
 820      * Lookup lookup = MethodHandles.lookup();   // in class C
 821      * Lookup lookup2 = lookup.in(D.class);
 822      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 823      * }
 824      * <p>
 825      * The {@link #lookup()} factory method produces a {@code Lookup} object
 826      * with {@code null} previous lookup class.
 827      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 828      * to class {@code D} without elevation of privileges.
 829      * If {@code C} and {@code D} are in the same module,
 830      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 831      * same previous lookup class as the original {@code lookup}, or
 832      * {@code null} if not present.
 833      * <p>
 834      * When a {@code Lookup} teleports from a class
 835      * in one nest to another nest, {@code PRIVATE} access is dropped.
 836      * When a {@code Lookup} teleports from a class in one package to
 837      * another package, {@code PACKAGE} access is dropped.
 838      * When a {@code Lookup} teleports from a class in one module to another module,
 839      * {@code MODULE} access is dropped.
 840      * Teleporting across modules drops the ability to access non-exported classes
 841      * in both the module of the new lookup class and the module of the old lookup class
 842      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 843      * A {@code Lookup} can teleport back and forth to a class in the module of
 844      * the lookup class and the module of the previous class lookup.
 845      * Teleporting across modules can only decrease access but cannot increase it.
 846      * Teleporting to some third module drops all accesses.
 847      * <p>
 848      * In the above example, if {@code C} and {@code D} are in different modules,
 849      * {@code lookup2} records {@code D} as its lookup class and
 850      * {@code C} as its previous lookup class and {@code lookup2} has only
 851      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 852      * {@code C}'s module and {@code D}'s module.
 853      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 854      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 855      * class {@code D} is recorded as its previous lookup class.
 856      * <p>
 857      * Teleporting across modules restricts access to the public types that
 858      * both the lookup class and the previous lookup class can equally access
 859      * (see below).
 860      * <p>
 861      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 862      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 863      * and produce a new {@code Lookup} with <a href="#privacc">private access</a>
 864      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 865      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 866      * to call {@code privateLookupIn}.
 867      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 868      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 869      * produces a new {@code Lookup} on {@code T} with full capabilities.
 870      * A {@code lookup} on {@code C} is also allowed
 871      * to do deep reflection on {@code T} in another module {@code M2} if
 872      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 873      * the package containing {@code T} to at least {@code M1}.
 874      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 875      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 876      * The resulting {@code Lookup} can be used to do member lookup or teleport
 877      * to another lookup class by calling {@link #in Lookup::in}.  But
 878      * it cannot be used to obtain another private {@code Lookup} by calling
 879      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 880      * because it has no {@code MODULE} access.
 881      * <p>
 882      * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to
 883      * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
 884      * of {@code T}. Extreme caution should be taken when opening a package
 885      * to another module as such defined classes have the same full privilege
 886      * access as other members in {@code M2}.
 887      *
 888      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 889      *
 890      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 891      * allows cross-module access. The access checking is performed with respect
 892      * to both the lookup class and the previous lookup class if present.
 893      * <p>
 894      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 895      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 896      * exported unconditionally}.
 897      * <p>
 898      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 899      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 900      * that are readable to {@code M1} and the type is in a package that is exported
 901      * at least to {@code M1}.
 902      * <p>
 903      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 904      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 905      * the intersection of all public types that are accessible to {@code M1}
 906      * with all public types that are accessible to {@code M0}. {@code M0}
 907      * reads {@code M1} and hence the set of accessible types includes:
 908      *
 909      * <ul>
 910      * <li>unconditional-exported packages from {@code M1}</li>
 911      * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li>
 912      * <li>
 913      *     unconditional-exported packages from a third module {@code M2}if both {@code M0}
 914      *     and {@code M1} read {@code M2}
 915      * </li>
 916      * <li>qualified-exported packages from {@code M1} to {@code M0}</li>
 917      * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li>
 918      * <li>
 919      *     qualified-exported packages from a third module {@code M2} to both {@code M0} and
 920      *     {@code M1} if both {@code M0} and {@code M1} read {@code M2}
 921      * </li>
 922      * </ul>
 923      *
 924      * <h2><a id="access-modes"></a>Access modes</h2>
 925      *
 926      * The table below shows the access modes of a {@code Lookup} produced by
 927      * any of the following factory or transformation methods:
 928      * <ul>
 929      * <li>{@link #lookup() MethodHandles::lookup}</li>
 930      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 931      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 932      * <li>{@link Lookup#in Lookup::in}</li>
 933      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 934      * </ul>
 935      *
 936      * <table class="striped">
 937      * <caption style="display:none">
 938      * Access mode summary
 939      * </caption>
 940      * <thead>
 941      * <tr>
 942      * <th scope="col">Lookup object</th>
 943      * <th style="text-align:center">original</th>
 944      * <th style="text-align:center">protected</th>
 945      * <th style="text-align:center">private</th>
 946      * <th style="text-align:center">package</th>
 947      * <th style="text-align:center">module</th>
 948      * <th style="text-align:center">public</th>
 949      * </tr>
 950      * </thead>
 951      * <tbody>
 952      * <tr>
 953      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 954      * <td style="text-align:center">ORI</td>
 955      * <td style="text-align:center">PRO</td>
 956      * <td style="text-align:center">PRI</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 package</th>
 963      * <td></td>
 964      * <td></td>
 965      * <td></td>
 966      * <td style="text-align:center">PAC</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(C1)} same module</th>
 972      * <td></td>
 973      * <td></td>
 974      * <td></td>
 975      * <td></td>
 976      * <td style="text-align:center">MOD</td>
 977      * <td style="text-align:center">1R</td>
 978      * </tr>
 979      * <tr>
 980      * <th scope="row" style="text-align:left">{@code CL.in(D)} different 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 CL.in(D).in(C)} hop back to module</th>
 990      * <td></td>
 991      * <td></td>
 992      * <td></td>
 993      * <td></td>
 994      * <td></td>
 995      * <td style="text-align:center">2R</td>
 996      * </tr>
 997      * <tr>
 998      * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</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 PRI1a = privateLookupIn(C,PRI1)}</th>
1008      * <td></td>
1009      * <td style="text-align:center">PRO</td>
1010      * <td style="text-align:center">PRI</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)} same package</th>
1017      * <td></td>
1018      * <td></td>
1019      * <td></td>
1020      * <td style="text-align:center">PAC</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(C1)} different package</th>
1026      * <td></td>
1027      * <td></td>
1028      * <td></td>
1029      * <td></td>
1030      * <td style="text-align:center">MOD</td>
1031      * <td style="text-align:center">1R</td>
1032      * </tr>
1033      * <tr>
1034      * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th>
1035      * <td></td>
1036      * <td></td>
1037      * <td></td>
1038      * <td></td>
1039      * <td></td>
1040      * <td style="text-align:center">2R</td>
1041      * </tr>
1042      * <tr>
1043      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th>
1044      * <td></td>
1045      * <td></td>
1046      * <td style="text-align:center">PRI</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(PRIVATE)}</th>
1053      * <td></td>
1054      * <td></td>
1055      * <td></td>
1056      * <td style="text-align:center">PAC</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(PACKAGE)}</th>
1062      * <td></td>
1063      * <td></td>
1064      * <td></td>
1065      * <td></td>
1066      * <td style="text-align:center">MOD</td>
1067      * <td style="text-align:center">1R</td>
1068      * </tr>
1069      * <tr>
1070      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th>
1071      * <td></td>
1072      * <td></td>
1073      * <td></td>
1074      * <td></td>
1075      * <td></td>
1076      * <td style="text-align:center">1R</td>
1077      * </tr>
1078      * <tr>
1079      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th>
1080      * <td></td>
1081      * <td></td>
1082      * <td></td>
1083      * <td></td>
1084      * <td></td>
1085      * <td style="text-align:center">none</td>
1086      * <tr>
1087      * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</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(D,PRI1)}</th>
1097      * <td></td>
1098      * <td style="text-align:center">PRO</td>
1099      * <td style="text-align:center">PRI</td>
1100      * <td style="text-align:center">PAC</td>
1101      * <td></td>
1102      * <td style="text-align:center">2R</td>
1103      * </tr>
1104      * <tr>
1105      * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th>
1106      * <td></td>
1107      * <td></td>
1108      * <td></td>
1109      * <td></td>
1110      * <td></td>
1111      * <td style="text-align:center">IAE</td>
1112      * </tr>
1113      * <tr>
1114      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th>
1115      * <td></td>
1116      * <td></td>
1117      * <td></td>
1118      * <td style="text-align:center">PAC</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(D2)} different package</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(C1)} hop back to module</th>
1133      * <td></td>
1134      * <td></td>
1135      * <td></td>
1136      * <td></td>
1137      * <td></td>
1138      * <td style="text-align:center">2R</td>
1139      * </tr>
1140      * <tr>
1141      * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th>
1142      * <td></td>
1143      * <td></td>
1144      * <td></td>
1145      * <td></td>
1146      * <td></td>
1147      * <td style="text-align:center">none</td>
1148      * </tr>
1149      * <tr>
1150      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th>
1151      * <td></td>
1152      * <td></td>
1153      * <td style="text-align:center">PRI</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(PRIVATE)}</th>
1160      * <td></td>
1161      * <td></td>
1162      * <td></td>
1163      * <td style="text-align:center">PAC</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(PACKAGE)}</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(MODULE)}</th>
1178      * <td></td>
1179      * <td></td>
1180      * <td></td>
1181      * <td></td>
1182      * <td></td>
1183      * <td style="text-align:center">2R</td>
1184      * </tr>
1185      * <tr>
1186      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th>
1187      * <td></td>
1188      * <td></td>
1189      * <td></td>
1190      * <td></td>
1191      * <td></td>
1192      * <td style="text-align:center">none</td>
1193      * </tr>
1194      * <tr>
1195      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th>
1196      * <td></td>
1197      * <td></td>
1198      * <td style="text-align:center">PRI</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(PRIVATE)}</th>
1205      * <td></td>
1206      * <td></td>
1207      * <td></td>
1208      * <td style="text-align:center">PAC</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(PACKAGE)}</th>
1214      * <td></td>
1215      * <td></td>
1216      * <td></td>
1217      * <td></td>
1218      * <td style="text-align:center">MOD</td>
1219      * <td style="text-align:center">1R</td>
1220      * </tr>
1221      * <tr>
1222      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th>
1223      * <td></td>
1224      * <td></td>
1225      * <td></td>
1226      * <td></td>
1227      * <td></td>
1228      * <td style="text-align:center">1R</td>
1229      * </tr>
1230      * <tr>
1231      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th>
1232      * <td></td>
1233      * <td></td>
1234      * <td></td>
1235      * <td></td>
1236      * <td></td>
1237      * <td style="text-align:center">none</td>
1238      * </tr>
1239      * <tr>
1240      * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</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)} different 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.in(D).in(E)} third module</th>
1259      * <td></td>
1260      * <td></td>
1261      * <td></td>
1262      * <td></td>
1263      * <td></td>
1264      * <td style="text-align:center">U</td>
1265      * </tr>
1266      * <tr>
1267      * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th>
1268      * <td></td>
1269      * <td></td>
1270      * <td></td>
1271      * <td></td>
1272      * <td></td>
1273      * <td style="text-align:center">none</td>
1274      * </tr>
1275      * <tr>
1276      * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th>
1277      * <td></td>
1278      * <td></td>
1279      * <td></td>
1280      * <td></td>
1281      * <td></td>
1282      * <td style="text-align:center">IAE</td>
1283      * </tr>
1284      * <tr>
1285      * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th>
1286      * <td></td>
1287      * <td></td>
1288      * <td></td>
1289      * <td></td>
1290      * <td></td>
1291      * <td style="text-align:center">none</td>
1292      * </tr>
1293      * </tbody>
1294      * </table>
1295      *
1296      * <p>
1297      * Notes:
1298      * <ul>
1299      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1300      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1301      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1302      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1303      * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1304      *     {@code PRO} indicates {@link #PROTECTED} bit set,
1305      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1306      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1307      *     {@code MOD} indicates {@link #MODULE} bit set,
1308      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1309      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1310      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1311      * <li>Public access comes in three kinds:
1312      * <ul>
1313      * <li>unconditional ({@code U}): the lookup assumes readability.
1314      *     The lookup has {@code null} previous lookup class.
1315      * <li>one-module-reads ({@code 1R}): the module access checking is
1316      *     performed with respect to the lookup class.  The lookup has {@code null}
1317      *     previous lookup class.
1318      * <li>two-module-reads ({@code 2R}): the module access checking is
1319      *     performed with respect to the lookup class and the previous lookup class.
1320      *     The lookup has a non-null previous lookup class which is in a
1321      *     different module from the current lookup class.
1322      * </ul>
1323      * <li>Any attempt to reach a third module loses all access.</li>
1324      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1325      * all access modes are dropped.</li>
1326      * </ul>
1327      *
1328      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1329      * Although bytecode instructions can only refer to classes in
1330      * a related class loader, this API can search for methods in any
1331      * class, as long as a reference to its {@code Class} object is
1332      * available.  Such cross-loader references are also possible with the
1333      * Core Reflection API, and are impossible to bytecode instructions
1334      * such as {@code invokestatic} or {@code getfield}.
1335      * There is a {@linkplain java.lang.SecurityManager security manager API}
1336      * to allow applications to check such cross-loader references.
1337      * These checks apply to both the {@code MethodHandles.Lookup} API
1338      * and the Core Reflection API
1339      * (as found on {@link java.lang.Class Class}).
1340      * <p>
1341      * If a security manager is present, member and class lookups are subject to
1342      * additional checks.
1343      * From one to three calls are made to the security manager.
1344      * Any of these calls can refuse access by throwing a
1345      * {@link java.lang.SecurityException SecurityException}.
1346      * Define {@code smgr} as the security manager,
1347      * {@code lookc} as the lookup class of the current lookup object,
1348      * {@code refc} as the containing class in which the member
1349      * is being sought, and {@code defc} as the class in which the
1350      * member is actually defined.
1351      * (If a class or other type is being accessed,
1352      * the {@code refc} and {@code defc} values are the class itself.)
1353      * The value {@code lookc} is defined as <em>not present</em>
1354      * if the current lookup object does not have
1355      * {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1356      * The calls are made according to the following rules:
1357      * <ul>
1358      * <li><b>Step 1:</b>
1359      *     If {@code lookc} is not present, or if its class loader is not
1360      *     the same as or an ancestor of the class loader of {@code refc},
1361      *     then {@link SecurityManager#checkPackageAccess
1362      *     smgr.checkPackageAccess(refcPkg)} is called,
1363      *     where {@code refcPkg} is the package of {@code refc}.
1364      * <li><b>Step 2a:</b>
1365      *     If the retrieved member is not public and
1366      *     {@code lookc} is not present, then
1367      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1368      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
1369      * <li><b>Step 2b:</b>
1370      *     If the retrieved class has a {@code null} class loader,
1371      *     and {@code lookc} is not present, then
1372      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1373      *     with {@code RuntimePermission("getClassLoader")} is called.
1374      * <li><b>Step 3:</b>
1375      *     If the retrieved member is not public,
1376      *     and if {@code lookc} is not present,
1377      *     and if {@code defc} and {@code refc} are different,
1378      *     then {@link SecurityManager#checkPackageAccess
1379      *     smgr.checkPackageAccess(defcPkg)} is called,
1380      *     where {@code defcPkg} is the package of {@code defc}.
1381      * </ul>
1382      * Security checks are performed after other access checks have passed.
1383      * Therefore, the above rules presuppose a member or class that is public,
1384      * or else that is being accessed from a lookup class that has
1385      * rights to access the member or class.
1386      * <p>
1387      * If a security manager is present and the current lookup object does not have
1388      * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then
1389      * {@link #defineClass(byte[]) defineClass},
1390      * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass},
1391      * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...)
1392      * defineHiddenClassWithClassData}
1393      * calls {@link SecurityManager#checkPermission smgr.checkPermission}
1394      * with {@code RuntimePermission("defineClass")}.
1395      *
1396      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1397      * A small number of Java methods have a special property called caller sensitivity.
1398      * A <em>caller-sensitive</em> method can behave differently depending on the
1399      * identity of its immediate caller.
1400      * <p>
1401      * If a method handle for a caller-sensitive method is requested,
1402      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1403      * but they take account of the lookup class in a special way.
1404      * The resulting method handle behaves as if it were called
1405      * from an instruction contained in the lookup class,
1406      * so that the caller-sensitive method detects the lookup class.
1407      * (By contrast, the invoker of the method handle is disregarded.)
1408      * Thus, in the case of caller-sensitive methods,
1409      * different lookup classes may give rise to
1410      * differently behaving method handles.
1411      * <p>
1412      * In cases where the lookup object is
1413      * {@link MethodHandles#publicLookup() publicLookup()},
1414      * or some other lookup object without the
1415      * {@linkplain #ORIGINAL original access},
1416      * the lookup class is disregarded.
1417      * In such cases, no caller-sensitive method handle can be created,
1418      * access is forbidden, and the lookup fails with an
1419      * {@code IllegalAccessException}.
1420      * <p style="font-size:smaller;">
1421      * <em>Discussion:</em>
1422      * For example, the caller-sensitive method
1423      * {@link java.lang.Class#forName(String) Class.forName(x)}
1424      * can return varying classes or throw varying exceptions,
1425      * depending on the class loader of the class that calls it.
1426      * A public lookup of {@code Class.forName} will fail, because
1427      * there is no reasonable way to determine its bytecode behavior.
1428      * <p style="font-size:smaller;">
1429      * If an application caches method handles for broad sharing,
1430      * it should use {@code publicLookup()} to create them.
1431      * If there is a lookup of {@code Class.forName}, it will fail,
1432      * and the application must take appropriate action in that case.
1433      * It may be that a later lookup, perhaps during the invocation of a
1434      * bootstrap method, can incorporate the specific identity
1435      * of the caller, making the method accessible.
1436      * <p style="font-size:smaller;">
1437      * The function {@code MethodHandles.lookup} is caller sensitive
1438      * so that there can be a secure foundation for lookups.
1439      * Nearly all other methods in the JSR 292 API rely on lookup
1440      * objects to check access requests.
1441      *
1442      * @revised 9
1443      */
1444     public static final
1445     class Lookup {
1446         /** The class on behalf of whom the lookup is being performed. */
1447         private final Class<?> lookupClass;
1448 
1449         /** previous lookup class */
1450         private final Class<?> prevLookupClass;
1451 
1452         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1453         private final int allowedModes;
1454 
1455         static {
1456             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1457         }
1458 
1459         /** A single-bit mask representing {@code public} access,
1460          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1461          *  The value, {@code 0x01}, happens to be the same as the value of the
1462          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1463          *  <p>
1464          *  A {@code Lookup} with this lookup mode performs cross-module access check
1465          *  with respect to the {@linkplain #lookupClass() lookup class} and
1466          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1467          */
1468         public static final int PUBLIC = Modifier.PUBLIC;
1469 
1470         /** A single-bit mask representing {@code private} access,
1471          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1472          *  The value, {@code 0x02}, happens to be the same as the value of the
1473          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1474          */
1475         public static final int PRIVATE = Modifier.PRIVATE;
1476 
1477         /** A single-bit mask representing {@code protected} access,
1478          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1479          *  The value, {@code 0x04}, happens to be the same as the value of the
1480          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1481          */
1482         public static final int PROTECTED = Modifier.PROTECTED;
1483 
1484         /** A single-bit mask representing {@code package} access (default access),
1485          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1486          *  The value is {@code 0x08}, which does not correspond meaningfully to
1487          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1488          */
1489         public static final int PACKAGE = Modifier.STATIC;
1490 
1491         /** A single-bit mask representing {@code module} access,
1492          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1493          *  The value is {@code 0x10}, which does not correspond meaningfully to
1494          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1495          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1496          *  with this lookup mode can access all public types in the module of the
1497          *  lookup class and public types in packages exported by other modules
1498          *  to the module of the lookup class.
1499          *  <p>
1500          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1501          *  previous lookup class} is always {@code null}.
1502          *
1503          *  @since 9
1504          */
1505         public static final int MODULE = PACKAGE << 1;
1506 
1507         /** A single-bit mask representing {@code unconditional} access
1508          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1509          *  The value is {@code 0x20}, which does not correspond meaningfully to
1510          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1511          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1512          *  java.lang.Module#canRead(java.lang.Module) readability}.
1513          *  This lookup mode can access all public members of public types
1514          *  of all modules when the type is in a package that is {@link
1515          *  java.lang.Module#isExported(String) exported unconditionally}.
1516          *
1517          *  <p>
1518          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1519          *  previous lookup class} is always {@code null}.
1520          *
1521          *  @since 9
1522          *  @see #publicLookup()
1523          */
1524         public static final int UNCONDITIONAL = PACKAGE << 2;
1525 
1526         /** A single-bit mask representing {@code original} access
1527          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1528          *  The value is {@code 0x40}, which does not correspond meaningfully to
1529          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1530          *
1531          *  <p>
1532          *  If this lookup mode is set, the {@code Lookup} object must be
1533          *  created by the original lookup class by calling
1534          *  {@link MethodHandles#lookup()} method or by a bootstrap method
1535          *  invoked by the VM.  The {@code Lookup} object with this lookup
1536          *  mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1537          *
1538          *  @since 16
1539          */
1540         public static final int ORIGINAL = PACKAGE << 3;
1541 
1542         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1543         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);   // with original access
1544         private static final int TRUSTED   = -1;
1545 
1546         /*
1547          * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1548          * Adjust 0 => PACKAGE
1549          */
1550         private static int fixmods(int mods) {
1551             mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1552             if (Modifier.isPublic(mods))
1553                 mods |= UNCONDITIONAL;
1554             return (mods != 0) ? mods : PACKAGE;
1555         }
1556 
1557         /** Tells which class is performing the lookup.  It is this class against
1558          *  which checks are performed for visibility and access permissions.
1559          *  <p>
1560          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1561          *  access checks are performed against both the lookup class and the previous lookup class.
1562          *  <p>
1563          *  The class implies a maximum level of access permission,
1564          *  but the permissions may be additionally limited by the bitmask
1565          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1566          *  can be accessed.
1567          *  @return the lookup class, on behalf of which this lookup object finds members
1568          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1569          */
1570         public Class<?> lookupClass() {
1571             return lookupClass;
1572         }
1573 
1574         /** Reports a lookup class in another module that this lookup object
1575          * was previously teleported from, or {@code null}.
1576          * <p>
1577          * A {@code Lookup} object produced by the factory methods, such as the
1578          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1579          * has {@code null} previous lookup class.
1580          * A {@code Lookup} object has a non-null previous lookup class
1581          * when this lookup was teleported from an old lookup class
1582          * in one module to a new lookup class in another module.
1583          *
1584          * @return the lookup class in another module that this lookup object was
1585          *         previously teleported from, or {@code null}
1586          * @since 14
1587          * @see #in(Class)
1588          * @see MethodHandles#privateLookupIn(Class, Lookup)
1589          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1590          */
1591         public Class<?> previousLookupClass() {
1592             return prevLookupClass;
1593         }
1594 
1595         // This is just for calling out to MethodHandleImpl.
1596         private Class<?> lookupClassOrNull() {
1597             return (allowedModes == TRUSTED) ? null : lookupClass;
1598         }
1599 
1600         /** Tells which access-protection classes of members this lookup object can produce.
1601          *  The result is a bit-mask of the bits
1602          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1603          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1604          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1605          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1606          *  {@linkplain #MODULE MODULE (0x10)},
1607          *  {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1608          *  and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1609          *  <p>
1610          *  A freshly-created lookup object
1611          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1612          *  all possible bits set, except {@code UNCONDITIONAL}.
1613          *  A lookup object on a new lookup class
1614          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1615          *  may have some mode bits set to zero.
1616          *  Mode bits can also be
1617          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1618          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1619          *  The purpose of this is to restrict access via the new lookup object,
1620          *  so that it can access only names which can be reached by the original
1621          *  lookup object, and also by the new lookup class.
1622          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1623          *  @see #in
1624          *  @see #dropLookupMode
1625          *
1626          *  @revised 9
1627          */
1628         public int lookupModes() {
1629             return allowedModes & ALL_MODES;
1630         }
1631 
1632         /** Embody the current class (the lookupClass) as a lookup class
1633          * for method handle creation.
1634          * Must be called by from a method in this package,
1635          * which in turn is called by a method not in this package.
1636          */
1637         Lookup(Class<?> lookupClass) {
1638             this(lookupClass, null, FULL_POWER_MODES);
1639         }
1640 
1641         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1642             assert PrimitiveClass.isPrimaryType(lookupClass);
1643             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1644                     && prevLookupClass.getModule() != lookupClass.getModule());
1645             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1646             this.lookupClass = lookupClass;
1647             this.prevLookupClass = prevLookupClass;
1648             this.allowedModes = allowedModes;
1649         }
1650 
1651         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1652             // make sure we haven't accidentally picked up a privileged class:
1653             checkUnprivilegedlookupClass(lookupClass);
1654             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1655         }
1656 
1657         /**
1658          * Creates a lookup on the specified new lookup class.
1659          * The resulting object will report the specified
1660          * class as its own {@link #lookupClass() lookupClass}.
1661          *
1662          * <p>
1663          * However, the resulting {@code Lookup} object is guaranteed
1664          * to have no more access capabilities than the original.
1665          * In particular, access capabilities can be lost as follows:<ul>
1666          * <li>If the new lookup class is different from the old lookup class,
1667          * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1668          * <li>If the new lookup class is in a different module from the old one,
1669          * i.e. {@link #MODULE MODULE} access is lost.
1670          * <li>If the new lookup class is in a different package
1671          * than the old one, protected and default (package) members will not be accessible,
1672          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1673          * <li>If the new lookup class is not within the same package member
1674          * as the old one, private members will not be accessible, and protected members
1675          * will not be accessible by virtue of inheritance,
1676          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1677          * (Protected members may continue to be accessible because of package sharing.)
1678          * <li>If the new lookup class is not
1679          * {@linkplain #accessClass(Class) accessible} to this lookup,
1680          * then no members, not even public members, will be accessible
1681          * i.e. all access modes are lost.
1682          * <li>If the new lookup class, the old lookup class and the previous lookup class
1683          * are all in different modules i.e. teleporting to a third module,
1684          * all access modes are lost.
1685          * </ul>
1686          * <p>
1687          * The new previous lookup class is chosen as follows:
1688          * <ul>
1689          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1690          * the new previous lookup class is {@code null}.
1691          * <li>If the new lookup class is in the same module as the old lookup class,
1692          * the new previous lookup class is the old previous lookup class.
1693          * <li>If the new lookup class is in a different module from the old lookup class,
1694          * the new previous lookup class is the old lookup class.
1695          *</ul>
1696          * <p>
1697          * The resulting lookup's capabilities for loading classes
1698          * (used during {@link #findClass} invocations)
1699          * are determined by the lookup class' loader,
1700          * which may change due to this operation.
1701          *
1702          * @param requestedLookupClass the desired lookup class for the new lookup object
1703          * @return a lookup object which reports the desired lookup class, or the same object
1704          * if there is no change
1705          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1706          * @throws NullPointerException if the argument is null
1707          *
1708          * @revised 9
1709          * @see #accessClass(Class)
1710          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1711          */
1712         public Lookup in(Class<?> requestedLookupClass) {
1713             Objects.requireNonNull(requestedLookupClass);
1714             if (requestedLookupClass.isPrimitive())
1715                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1716             if (requestedLookupClass.isArray())
1717                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1718 
1719             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1720                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1721             if (requestedLookupClass == this.lookupClass)
1722                 return this;  // keep same capabilities
1723             int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1724             Module fromModule = this.lookupClass.getModule();
1725             Module targetModule = requestedLookupClass.getModule();
1726             Class<?> plc = this.previousLookupClass();
1727             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1728                 assert plc == null;
1729                 newModes = UNCONDITIONAL;
1730             } else if (fromModule != targetModule) {
1731                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1732                     // allow hopping back and forth between fromModule and plc's module
1733                     // but not the third module
1734                     newModes = 0;
1735                 }
1736                 // drop MODULE access
1737                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1738                 // teleport from this lookup class
1739                 plc = this.lookupClass;
1740             }
1741             if ((newModes & PACKAGE) != 0
1742                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1743                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1744             }
1745             // Allow nestmate lookups to be created without special privilege:
1746             if ((newModes & PRIVATE) != 0
1747                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1748                 newModes &= ~(PRIVATE|PROTECTED);
1749             }
1750             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1751                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1752                 // The requested class it not accessible from the lookup class.
1753                 // No permissions.
1754                 newModes = 0;
1755             }
1756             return newLookup(requestedLookupClass, plc, newModes);
1757         }
1758 
1759         /**
1760          * Creates a lookup on the same lookup class which this lookup object
1761          * finds members, but with a lookup mode that has lost the given lookup mode.
1762          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1763          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1764          * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1765          * {@link #UNCONDITIONAL UNCONDITIONAL}.
1766          *
1767          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1768          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1769          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1770          * lookup has no access.
1771          *
1772          * <p> If this lookup is not a public lookup, then the following applies
1773          * regardless of its {@linkplain #lookupModes() lookup modes}.
1774          * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1775          * dropped and so the resulting lookup mode will never have these access
1776          * capabilities. When dropping {@code PACKAGE}
1777          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1778          * access. When dropping {@code MODULE} then the resulting lookup will not
1779          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1780          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1781          *
1782          * @apiNote
1783          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1784          * delegate non-public access within the package of the lookup class without
1785          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1786          * A lookup with {@code MODULE} but not
1787          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1788          * the module of the lookup class without conferring package access.
1789          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1790          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1791          * to public classes accessible to both the module of the lookup class
1792          * and the module of the previous lookup class.
1793          *
1794          * @param modeToDrop the lookup mode to drop
1795          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1796          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1797          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1798          * or {@code UNCONDITIONAL}
1799          * @see MethodHandles#privateLookupIn
1800          * @since 9
1801          */
1802         public Lookup dropLookupMode(int modeToDrop) {
1803             int oldModes = lookupModes();
1804             int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1805             switch (modeToDrop) {
1806                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1807                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1808                 case PACKAGE: newModes &= ~(PRIVATE); break;
1809                 case PROTECTED:
1810                 case PRIVATE:
1811                 case ORIGINAL:
1812                 case UNCONDITIONAL: break;
1813                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1814             }
1815             if (newModes == oldModes) return this;  // return self if no change
1816             return newLookup(lookupClass(), previousLookupClass(), newModes);
1817         }
1818 
1819         /**
1820          * Creates and links a class or interface from {@code bytes}
1821          * with the same class loader and in the same runtime package and
1822          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1823          * {@linkplain #lookupClass() lookup class} as if calling
1824          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1825          * ClassLoader::defineClass}.
1826          *
1827          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1828          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1829          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1830          * that the lookup object was created by a caller in the runtime package (or derived
1831          * from a lookup originally created by suitably privileged code to a target class in
1832          * the runtime package). </p>
1833          *
1834          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1835          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1836          * same package as the lookup class. </p>
1837          *
1838          * <p> This method does not run the class initializer. The class initializer may
1839          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1840          * Specification</em>. </p>
1841          *
1842          * <p> If there is a security manager and this lookup does not have {@linkplain
1843          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1844          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1845          *
1846          * @param bytes the class bytes
1847          * @return the {@code Class} object for the class
1848          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1849          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1850          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1851          * than the lookup class or {@code bytes} is not a class or interface
1852          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1853          * @throws VerifyError if the newly created class cannot be verified
1854          * @throws LinkageError if the newly created class cannot be linked for any other reason
1855          * @throws SecurityException if a security manager is present and it
1856          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1857          * @throws NullPointerException if {@code bytes} is {@code null}
1858          * @since 9
1859          * @see Lookup#privateLookupIn
1860          * @see Lookup#dropLookupMode
1861          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1862          */
1863         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1864             ensureDefineClassPermission();
1865             if ((lookupModes() & PACKAGE) == 0)
1866                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1867             return makeClassDefiner(bytes.clone()).defineClass(false);
1868         }
1869 
1870         private void ensureDefineClassPermission() {
1871             if (allowedModes == TRUSTED)  return;
1872 
1873             if (!hasFullPrivilegeAccess()) {
1874                 @SuppressWarnings("removal")
1875                 SecurityManager sm = System.getSecurityManager();
1876                 if (sm != null)
1877                     sm.checkPermission(new RuntimePermission("defineClass"));
1878             }
1879         }
1880 
1881         /**
1882          * The set of class options that specify whether a hidden class created by
1883          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1884          * Lookup::defineHiddenClass} method is dynamically added as a new member
1885          * to the nest of a lookup class and/or whether a hidden class has
1886          * a strong relationship with the class loader marked as its defining loader.
1887          *
1888          * @since 15
1889          */
1890         public enum ClassOption {
1891             /**
1892              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1893              * of a lookup class as a nestmate.
1894              *
1895              * <p> A hidden nestmate class has access to the private members of all
1896              * classes and interfaces in the same nest.
1897              *
1898              * @see Class#getNestHost()
1899              */
1900             NESTMATE(NESTMATE_CLASS),
1901 
1902             /**
1903              * Specifies that a hidden class has a <em>strong</em>
1904              * relationship with the class loader marked as its defining loader,
1905              * as a normal class or interface has with its own defining loader.
1906              * This means that the hidden class may be unloaded if and only if
1907              * its defining loader is not reachable and thus may be reclaimed
1908              * by a garbage collector (JLS {@jls 12.7}).
1909              *
1910              * <p> By default, a hidden class or interface may be unloaded
1911              * even if the class loader that is marked as its defining loader is
1912              * <a href="../ref/package-summary.html#reachability">reachable</a>.
1913 
1914              *
1915              * @jls 12.7 Unloading of Classes and Interfaces
1916              */
1917             STRONG(STRONG_LOADER_LINK);
1918 
1919             /* the flag value is used by VM at define class time */
1920             private final int flag;
1921             ClassOption(int flag) {
1922                 this.flag = flag;
1923             }
1924 
1925             static int optionsToFlag(Set<ClassOption> options) {
1926                 int flags = 0;
1927                 for (ClassOption cp : options) {
1928                     flags |= cp.flag;
1929                 }
1930                 return flags;
1931             }
1932         }
1933 
1934         /**
1935          * Creates a <em>hidden</em> class or interface from {@code bytes},
1936          * returning a {@code Lookup} on the newly created class or interface.
1937          *
1938          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1939          * which either defines {@code C} directly or delegates to another class loader.
1940          * A class loader defines {@code C} directly by invoking
1941          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1942          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1943          * to derive {@code C} from a purported representation in {@code class} file format.
1944          * In situations where use of a class loader is undesirable, a class or interface
1945          * {@code C} can be created by this method instead. This method is capable of
1946          * defining {@code C}, and thereby creating it, without invoking
1947          * {@code ClassLoader::defineClass}.
1948          * Instead, this method defines {@code C} as if by arranging for
1949          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1950          * from a purported representation in {@code class} file format
1951          * using the following rules:
1952          *
1953          * <ol>
1954          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1955          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1956          * This level of access is needed to create {@code C} in the module
1957          * of the lookup class of this {@code Lookup}.</li>
1958          *
1959          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1960          * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1961          * The major and minor version may differ from the {@code class} file version
1962          * of the lookup class of this {@code Lookup}.</li>
1963          *
1964          * <li> The value of {@code this_class} must be a valid index in the
1965          * {@code constant_pool} table, and the entry at that index must be a valid
1966          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1967          * encoded in internal form that is specified by this structure. {@code N} must
1968          * denote a class or interface in the same package as the lookup class.</li>
1969          *
1970          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1971          * where {@code <suffix>} is an unqualified name.
1972          *
1973          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1974          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1975          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1976          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1977          * refers to the new {@code CONSTANT_Utf8_info} structure.
1978          *
1979          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1980          *
1981          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1982          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1983          * with the following adjustments:
1984          * <ul>
1985          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1986          * that includes a single {@code "."} character, even though this is not a valid
1987          * binary class or interface name in internal form.</li>
1988          *
1989          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1990          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1991          *
1992          * <li> {@code C} is considered to have the same runtime
1993          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1994          * and {@linkplain java.security.ProtectionDomain protection domain}
1995          * as the lookup class of this {@code Lookup}.
1996          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1997          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1998          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1999          * <ul>
2000          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
2001          *      even though this is not a valid binary class or interface name.</li>
2002          * <li> {@link Class#descriptorString()} returns the string
2003          *      {@code "L" + N + "." + <suffix> + ";"},
2004          *      even though this is not a valid type descriptor name.</li>
2005          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
2006          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
2007          * </ul>
2008          * </ul>
2009          * </li>
2010          * </ol>
2011          *
2012          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
2013          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
2014          * <ul>
2015          * <li> During verification, whenever it is necessary to load the class named
2016          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
2017          * made of any class loader.</li>
2018          *
2019          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
2020          * by {@code this_class}, the symbolic reference is considered to be resolved to
2021          * {@code C} and resolution always succeeds immediately.</li>
2022          * </ul>
2023          *
2024          * <p> If the {@code initialize} parameter is {@code true},
2025          * then {@code C} is initialized by the Java Virtual Machine.
2026          *
2027          * <p> The newly created class or interface {@code C} serves as the
2028          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
2029          * returned by this method. {@code C} is <em>hidden</em> in the sense that
2030          * no other class or interface can refer to {@code C} via a constant pool entry.
2031          * That is, a hidden class or interface cannot be named as a supertype, a field type,
2032          * a method parameter type, or a method return type by any other class.
2033          * This is because a hidden class or interface does not have a binary name, so
2034          * there is no internal form available to record in any class's constant pool.
2035          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
2036          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
2037          * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class)
2038          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
2039          * JVM Tool Interface</a>.
2040          *
2041          * <p> A class or interface created by
2042          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
2043          * a class loader} has a strong relationship with that class loader.
2044          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
2045          * that {@linkplain Class#getClassLoader() defined it}.
2046          * This means that a class created by a class loader may be unloaded if and
2047          * only if its defining loader is not reachable and thus may be reclaimed
2048          * by a garbage collector (JLS {@jls 12.7}).
2049          *
2050          * By default, however, a hidden class or interface may be unloaded even if
2051          * the class loader that is marked as its defining loader is
2052          * <a href="../ref/package-summary.html#reachability">reachable</a>.
2053          * This behavior is useful when a hidden class or interface serves multiple
2054          * classes defined by arbitrary class loaders.  In other cases, a hidden
2055          * class or interface may be linked to a single class (or a small number of classes)
2056          * with the same defining loader as the hidden class or interface.
2057          * In such cases, where the hidden class or interface must be coterminous
2058          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
2059          * option may be passed in {@code options}.
2060          * This arranges for a hidden class to have the same strong relationship
2061          * with the class loader marked as its defining loader,
2062          * as a normal class or interface has with its own defining loader.
2063          *
2064          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
2065          * may still prevent a hidden class or interface from being
2066          * unloaded by ensuring that the {@code Class} object is reachable.
2067          *
2068          * <p> The unloading characteristics are set for each hidden class when it is
2069          * defined, and cannot be changed later.  An advantage of allowing hidden classes
2070          * to be unloaded independently of the class loader marked as their defining loader
2071          * is that a very large number of hidden classes may be created by an application.
2072          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
2073          * just as if normal classes were created by class loaders.
2074          *
2075          * <p> Classes and interfaces in a nest are allowed to have mutual access to
2076          * their private members.  The nest relationship is determined by
2077          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
2078          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
2079          * By default, a hidden class belongs to a nest consisting only of itself
2080          * because a hidden class has no binary name.
2081          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
2082          * to create a hidden class or interface {@code C} as a member of a nest.
2083          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
2084          * in the {@code ClassFile} structure from which {@code C} was derived.
2085          * Instead, the following rules determine the nest host of {@code C}:
2086          * <ul>
2087          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
2088          *     been determined, then let {@code H} be the nest host of the lookup class.
2089          *     Otherwise, the nest host of the lookup class is determined using the
2090          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
2091          * <li>The nest host of {@code C} is determined to be {@code H},
2092          *     the nest host of the lookup class.</li>
2093          * </ul>
2094          *
2095          * <p> A hidden class or interface may be serializable, but this requires a custom
2096          * serialization mechanism in order to ensure that instances are properly serialized
2097          * and deserialized. The default serialization mechanism supports only classes and
2098          * interfaces that are discoverable by their class name.
2099          *
2100          * @param bytes the bytes that make up the class data,
2101          * in the format of a valid {@code class} file as defined by
2102          * <cite>The Java Virtual Machine Specification</cite>.
2103          * @param initialize if {@code true} the class will be initialized.
2104          * @param options {@linkplain ClassOption class options}
2105          * @return the {@code Lookup} object on the hidden class,
2106          * with {@linkplain #ORIGINAL original} and
2107          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2108          *
2109          * @throws IllegalAccessException if this {@code Lookup} does not have
2110          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2111          * @throws SecurityException if a security manager is present and it
2112          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2113          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2114          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2115          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2116          * than the lookup class or {@code bytes} is not a class or interface
2117          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2118          * @throws IncompatibleClassChangeError if the class or interface named as
2119          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2120          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2121          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2122          * {@code C} is {@code C} itself
2123          * @throws VerifyError if the newly created class cannot be verified
2124          * @throws LinkageError if the newly created class cannot be linked for any other reason
2125          * @throws NullPointerException if any parameter is {@code null}
2126          *
2127          * @since 15
2128          * @see Class#isHidden()
2129          * @jvms 4.2.1 Binary Class and Interface Names
2130          * @jvms 4.2.2 Unqualified Names
2131          * @jvms 4.7.28 The {@code NestHost} Attribute
2132          * @jvms 4.7.29 The {@code NestMembers} Attribute
2133          * @jvms 5.4.3.1 Class and Interface Resolution
2134          * @jvms 5.4.4 Access Control
2135          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2136          * @jvms 5.4 Linking
2137          * @jvms 5.5 Initialization
2138          * @jls 12.7 Unloading of Classes and Interfaces
2139          */
2140         @SuppressWarnings("doclint:reference") // cross-module links
2141         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2142                 throws IllegalAccessException
2143         {
2144             Objects.requireNonNull(bytes);
2145             Objects.requireNonNull(options);
2146 
2147             ensureDefineClassPermission();
2148             if (!hasFullPrivilegeAccess()) {
2149                 throw new IllegalAccessException(this + " does not have full privilege access");
2150             }
2151 
2152             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
2153         }
2154 
2155         /**
2156          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2157          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2158          * returning a {@code Lookup} on the newly created class or interface.
2159          *
2160          * <p> This method is equivalent to calling
2161          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2162          * as if the hidden class is injected with a private static final <i>unnamed</i>
2163          * field which is initialized with the given {@code classData} at
2164          * the first instruction of the class initializer.
2165          * The newly created class is linked by the Java Virtual Machine.
2166          *
2167          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2168          * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2169          * methods can be used to retrieve the {@code classData}.
2170          *
2171          * @apiNote
2172          * A framework can create a hidden class with class data with one or more
2173          * objects and load the class data as dynamically-computed constant(s)
2174          * via a bootstrap method.  {@link MethodHandles#classData(Lookup, String, Class)
2175          * Class data} is accessible only to the lookup object created by the newly
2176          * defined hidden class but inaccessible to other members in the same nest
2177          * (unlike private static fields that are accessible to nestmates).
2178          * Care should be taken w.r.t. mutability for example when passing
2179          * an array or other mutable structure through the class data.
2180          * Changing any value stored in the class data at runtime may lead to
2181          * unpredictable behavior.
2182          * If the class data is a {@code List}, it is good practice to make it
2183          * unmodifiable for example via {@link List#of List::of}.
2184          *
2185          * @param bytes     the class bytes
2186          * @param classData pre-initialized class data
2187          * @param initialize if {@code true} the class will be initialized.
2188          * @param options   {@linkplain ClassOption class options}
2189          * @return the {@code Lookup} object on the hidden class,
2190          * with {@linkplain #ORIGINAL original} and
2191          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2192          *
2193          * @throws IllegalAccessException if this {@code Lookup} does not have
2194          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2195          * @throws SecurityException if a security manager is present and it
2196          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2197          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2198          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2199          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2200          * than the lookup class or {@code bytes} is not a class or interface
2201          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2202          * @throws IncompatibleClassChangeError if the class or interface named as
2203          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2204          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2205          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2206          * {@code C} is {@code C} itself
2207          * @throws VerifyError if the newly created class cannot be verified
2208          * @throws LinkageError if the newly created class cannot be linked for any other reason
2209          * @throws NullPointerException if any parameter is {@code null}
2210          *
2211          * @since 16
2212          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2213          * @see Class#isHidden()
2214          * @see MethodHandles#classData(Lookup, String, Class)
2215          * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2216          * @jvms 4.2.1 Binary Class and Interface Names
2217          * @jvms 4.2.2 Unqualified Names
2218          * @jvms 4.7.28 The {@code NestHost} Attribute
2219          * @jvms 4.7.29 The {@code NestMembers} Attribute
2220          * @jvms 5.4.3.1 Class and Interface Resolution
2221          * @jvms 5.4.4 Access Control
2222          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2223          * @jvms 5.4 Linking
2224          * @jvms 5.5 Initialization
2225          * @jls 12.7 Unloading of Classes and Interface
2226          */
2227         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2228                 throws IllegalAccessException
2229         {
2230             Objects.requireNonNull(bytes);
2231             Objects.requireNonNull(classData);
2232             Objects.requireNonNull(options);
2233 
2234             ensureDefineClassPermission();
2235             if (!hasFullPrivilegeAccess()) {
2236                 throw new IllegalAccessException(this + " does not have full privilege access");
2237             }
2238 
2239             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2240                        .defineClassAsLookup(initialize, classData);
2241         }
2242 
2243         // A default dumper for writing class files passed to Lookup::defineClass
2244         // and Lookup::defineHiddenClass to disk for debugging purposes.  To enable,
2245         // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or
2246         //     -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true
2247         //
2248         // This default dumper does not dump hidden classes defined by LambdaMetafactory
2249         // and LambdaForms and method handle internals.  They are dumped via
2250         // different ClassFileDumpers.
2251         private static ClassFileDumper defaultDumper() {
2252             return DEFAULT_DUMPER;
2253         }
2254 
2255         private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance(
2256                 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES");
2257 
2258         static class ClassFile {
2259             final String name;  // internal name
2260             final int accessFlags;
2261             final byte[] bytes;
2262             ClassFile(String name, int accessFlags, byte[] bytes) {
2263                 this.name = name;
2264                 this.accessFlags = accessFlags;
2265                 this.bytes = bytes;
2266             }
2267 
2268             static ClassFile newInstanceNoCheck(String name, byte[] bytes) {
2269                 return new ClassFile(name, 0, bytes);
2270             }
2271 
2272             /**
2273              * This method checks the class file version and the structure of `this_class`.
2274              * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2275              * that is in the named package.
2276              *
2277              * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2278              * or the class is not in the given package name.
2279              */
2280             static ClassFile newInstance(byte[] bytes, String pkgName) {
2281                 var cf = readClassFile(bytes);
2282 
2283                 // check if it's in the named package
2284                 int index = cf.name.lastIndexOf('/');
2285                 String pn = (index == -1) ? "" : cf.name.substring(0, index).replace('/', '.');
2286                 if (!pn.equals(pkgName)) {
2287                     throw newIllegalArgumentException(cf.name + " not in same package as lookup class");
2288                 }
2289                 return cf;
2290             }
2291 
2292             private static ClassFile readClassFile(byte[] bytes) {
2293                 int magic = readInt(bytes, 0);
2294                 if (magic != 0xCAFEBABE) {
2295                     throw new ClassFormatError("Incompatible magic value: " + magic);
2296                 }
2297                 int minor = readUnsignedShort(bytes, 4);
2298                 int major = readUnsignedShort(bytes, 6);
2299                 if (!VM.isSupportedClassFileVersion(major, minor)) {
2300                     throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2301                 }
2302 
2303                 String name;
2304                 int accessFlags;
2305                 try {
2306                     ClassReader reader = new ClassReader(bytes);
2307                     // ClassReader does not check if `this_class` is CONSTANT_Class_info
2308                     // workaround to read `this_class` using readConst and validate the value
2309                     int thisClass = reader.readUnsignedShort(reader.header + 2);
2310                     Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]);
2311                     if (!(constant instanceof Type type)) {
2312                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2313                     }
2314                     if (!type.getDescriptor().startsWith("L")) {
2315                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2316                     }
2317                     name = type.getInternalName();
2318                     accessFlags = reader.readUnsignedShort(reader.header);
2319                 } catch (RuntimeException e) {
2320                     // ASM exceptions are poorly specified
2321                     ClassFormatError cfe = new ClassFormatError();
2322                     cfe.initCause(e);
2323                     throw cfe;
2324                 }
2325                 // must be a class or interface
2326                 if ((accessFlags & Opcodes.ACC_MODULE) != 0) {
2327                     throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2328                 }
2329                 return new ClassFile(name, accessFlags, bytes);
2330             }
2331 
2332             private static int readInt(byte[] bytes, int offset) {
2333                 if ((offset+4) > bytes.length) {
2334                     throw new ClassFormatError("Invalid ClassFile structure");
2335                 }
2336                 return ((bytes[offset] & 0xFF) << 24)
2337                         | ((bytes[offset + 1] & 0xFF) << 16)
2338                         | ((bytes[offset + 2] & 0xFF) << 8)
2339                         | (bytes[offset + 3] & 0xFF);
2340             }
2341 
2342             private static int readUnsignedShort(byte[] bytes, int offset) {
2343                 if ((offset+2) > bytes.length) {
2344                     throw new ClassFormatError("Invalid ClassFile structure");
2345                 }
2346                 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2347             }
2348         }
2349 
2350         /*
2351          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2352          * from the given bytes.
2353          *
2354          * Caller should make a defensive copy of the arguments if needed
2355          * before calling this factory method.
2356          *
2357          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2358          * {@code bytes} denotes a class in a different package than the lookup class
2359          */
2360         private ClassDefiner makeClassDefiner(byte[] bytes) {
2361             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2362             return new ClassDefiner(this, cf, STRONG_LOADER_LINK, defaultDumper());
2363         }
2364 
2365         /**
2366          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2367          * from the given bytes.  No package name check on the given bytes.
2368          *
2369          * @param name    internal name
2370          * @param bytes   class bytes
2371          * @param dumper  dumper to write the given bytes to the dumper's output directory
2372          * @return ClassDefiner that defines a normal class of the given bytes.
2373          */
2374         ClassDefiner makeClassDefiner(String name, byte[] bytes, ClassFileDumper dumper) {
2375             // skip package name validation
2376             ClassFile cf = ClassFile.newInstanceNoCheck(name, bytes);
2377             return new ClassDefiner(this, cf, STRONG_LOADER_LINK, dumper);
2378         }
2379 
2380         /**
2381          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2382          * from the given bytes.  The name must be in the same package as the lookup class.
2383          *
2384          * Caller should make a defensive copy of the arguments if needed
2385          * before calling this factory method.
2386          *
2387          * @param bytes   class bytes
2388          * @param dumper dumper to write the given bytes to the dumper's output directory
2389          * @return ClassDefiner that defines a hidden class of the given bytes.
2390          *
2391          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2392          * {@code bytes} denotes a class in a different package than the lookup class
2393          */
2394         ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) {
2395             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2396             return makeHiddenClassDefiner(cf, Set.of(), false, dumper);
2397         }
2398 
2399         /**
2400          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2401          * from the given bytes and options.
2402          * The name must be in the same package as the lookup class.
2403          *
2404          * Caller should make a defensive copy of the arguments if needed
2405          * before calling this factory method.
2406          *
2407          * @param bytes   class bytes
2408          * @param options class options
2409          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2410          * @return ClassDefiner that defines a hidden class of the given bytes and options
2411          *
2412          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2413          * {@code bytes} denotes a class in a different package than the lookup class
2414          */
2415         private ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2416                                                     Set<ClassOption> options,
2417                                                     boolean accessVmAnnotations) {
2418             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2419             return makeHiddenClassDefiner(cf, options, accessVmAnnotations, defaultDumper());
2420         }
2421 
2422         /**
2423          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2424          * from the given bytes and the given options.  No package name check on the given bytes.
2425          *
2426          * @param name    internal name that specifies the prefix of the hidden class
2427          * @param bytes   class bytes
2428          * @param options class options
2429          * @param dumper  dumper to write the given bytes to the dumper's output directory
2430          * @return ClassDefiner that defines a hidden class of the given bytes and options.
2431          */
2432         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options, ClassFileDumper dumper) {
2433             Objects.requireNonNull(dumper);
2434             // skip name and access flags validation
2435             return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false, dumper);
2436         }
2437 
2438         /**
2439          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2440          * from the given class file and options.
2441          *
2442          * @param cf ClassFile
2443          * @param options class options
2444          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2445          * @param dumper dumper to write the given bytes to the dumper's output directory
2446          */
2447         private ClassDefiner makeHiddenClassDefiner(ClassFile cf,
2448                                                     Set<ClassOption> options,
2449                                                     boolean accessVmAnnotations,
2450                                                     ClassFileDumper dumper) {
2451             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2452             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2453                 // jdk.internal.vm.annotations are permitted for classes
2454                 // defined to boot loader and platform loader
2455                 flags |= ACCESS_VM_ANNOTATIONS;
2456             }
2457 
2458             return new ClassDefiner(this, cf, flags, dumper);
2459         }
2460 
2461         static class ClassDefiner {
2462             private final Lookup lookup;
2463             private final String name;  // internal name
2464             private final byte[] bytes;
2465             private final int classFlags;
2466             private final ClassFileDumper dumper;
2467 
2468             private ClassDefiner(Lookup lookup, ClassFile cf, int flags, ClassFileDumper dumper) {
2469                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2470                 this.lookup = lookup;
2471                 this.bytes = cf.bytes;
2472                 this.name = cf.name;
2473                 this.classFlags = flags;
2474                 this.dumper = dumper;
2475             }
2476 
2477             String internalName() {
2478                 return name;
2479             }
2480 
2481             Class<?> defineClass(boolean initialize) {
2482                 return defineClass(initialize, null);
2483             }
2484 
2485             Lookup defineClassAsLookup(boolean initialize) {
2486                 Class<?> c = defineClass(initialize, null);
2487                 return new Lookup(c, null, FULL_POWER_MODES);
2488             }
2489 
2490             /**
2491              * Defines the class of the given bytes and the given classData.
2492              * If {@code initialize} parameter is true, then the class will be initialized.
2493              *
2494              * @param initialize true if the class to be initialized
2495              * @param classData classData or null
2496              * @return the class
2497              *
2498              * @throws LinkageError linkage error
2499              */
2500             Class<?> defineClass(boolean initialize, Object classData) {
2501                 Class<?> lookupClass = lookup.lookupClass();
2502                 ClassLoader loader = lookupClass.getClassLoader();
2503                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2504                 Class<?> c = null;
2505                 try {
2506                     c = SharedSecrets.getJavaLangAccess()
2507                             .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2508                     assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2509                     return c;
2510                 } finally {
2511                     // dump the classfile for debugging
2512                     if (dumper.isEnabled()) {
2513                         String name = internalName();
2514                         if (c != null) {
2515                             dumper.dumpClass(name, c, bytes);
2516                         } else {
2517                             dumper.dumpFailedClass(name, bytes);
2518                         }
2519                     }
2520                 }
2521             }
2522 
2523             /**
2524              * Defines the class of the given bytes and the given classData.
2525              * If {@code initialize} parameter is true, then the class will be initialized.
2526              *
2527              * @param initialize true if the class to be initialized
2528              * @param classData classData or null
2529              * @return a Lookup for the defined class
2530              *
2531              * @throws LinkageError linkage error
2532              */
2533             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2534                 Class<?> c = defineClass(initialize, classData);
2535                 return new Lookup(c, null, FULL_POWER_MODES);
2536             }
2537 
2538             private boolean isNestmate() {
2539                 return (classFlags & NESTMATE_CLASS) != 0;
2540             }
2541         }
2542 
2543         private ProtectionDomain lookupClassProtectionDomain() {
2544             ProtectionDomain pd = cachedProtectionDomain;
2545             if (pd == null) {
2546                 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2547             }
2548             return pd;
2549         }
2550 
2551         // cached protection domain
2552         private volatile ProtectionDomain cachedProtectionDomain;
2553 
2554         // Make sure outer class is initialized first.
2555         static { IMPL_NAMES.getClass(); }
2556 
2557         /** Package-private version of lookup which is trusted. */
2558         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2559 
2560         /** Version of lookup which is trusted minimally.
2561          *  It can only be used to create method handles to publicly accessible
2562          *  members in packages that are exported unconditionally.
2563          */
2564         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2565 
2566         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2567             String name = lookupClass.getName();
2568             if (name.startsWith("java.lang.invoke."))
2569                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2570         }
2571 
2572         /**
2573          * Displays the name of the class from which lookups are to be made,
2574          * followed by "/" and the name of the {@linkplain #previousLookupClass()
2575          * previous lookup class} if present.
2576          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2577          * If there are restrictions on the access permitted to this lookup,
2578          * this is indicated by adding a suffix to the class name, consisting
2579          * of a slash and a keyword.  The keyword represents the strongest
2580          * allowed access, and is chosen as follows:
2581          * <ul>
2582          * <li>If no access is allowed, the suffix is "/noaccess".
2583          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2584          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2585          * <li>If only public and module access are allowed, the suffix is "/module".
2586          * <li>If public and package access are allowed, the suffix is "/package".
2587          * <li>If public, package, and private access are allowed, the suffix is "/private".
2588          * </ul>
2589          * If none of the above cases apply, it is the case that
2590          * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2591          * (public, module, package, private, and protected) is allowed.
2592          * In this case, no suffix is added.
2593          * This is true only of an object obtained originally from
2594          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2595          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2596          * always have restricted access, and will display a suffix.
2597          * <p>
2598          * (It may seem strange that protected access should be
2599          * stronger than private access.  Viewed independently from
2600          * package access, protected access is the first to be lost,
2601          * because it requires a direct subclass relationship between
2602          * caller and callee.)
2603          * @see #in
2604          *
2605          * @revised 9
2606          */
2607         @Override
2608         public String toString() {
2609             String cname = lookupClass.getName();
2610             if (prevLookupClass != null)
2611                 cname += "/" + prevLookupClass.getName();
2612             switch (allowedModes) {
2613             case 0:  // no privileges
2614                 return cname + "/noaccess";
2615             case UNCONDITIONAL:
2616                 return cname + "/publicLookup";
2617             case PUBLIC:
2618                 return cname + "/public";
2619             case PUBLIC|MODULE:
2620                 return cname + "/module";
2621             case PUBLIC|PACKAGE:
2622             case PUBLIC|MODULE|PACKAGE:
2623                 return cname + "/package";
2624             case PUBLIC|PACKAGE|PRIVATE:
2625             case PUBLIC|MODULE|PACKAGE|PRIVATE:
2626                     return cname + "/private";
2627             case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2628             case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2629             case FULL_POWER_MODES:
2630                     return cname;
2631             case TRUSTED:
2632                 return "/trusted";  // internal only; not exported
2633             default:  // Should not happen, but it's a bitfield...
2634                 cname = cname + "/" + Integer.toHexString(allowedModes);
2635                 assert(false) : cname;
2636                 return cname;
2637             }
2638         }
2639 
2640         /**
2641          * Produces a method handle for a static method.
2642          * The type of the method handle will be that of the method.
2643          * (Since static methods do not take receivers, there is no
2644          * additional receiver argument inserted into the method handle type,
2645          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2646          * The method and all its argument types must be accessible to the lookup object.
2647          * <p>
2648          * The returned method handle will have
2649          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2650          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2651          * <p>
2652          * If the returned method handle is invoked, the method's class will
2653          * be initialized, if it has not already been initialized.
2654          * <p><b>Example:</b>
2655          * {@snippet lang="java" :
2656 import static java.lang.invoke.MethodHandles.*;
2657 import static java.lang.invoke.MethodType.*;
2658 ...
2659 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2660   "asList", methodType(List.class, Object[].class));
2661 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2662          * }
2663          * @param refc the class from which the method is accessed
2664          * @param name the name of the method
2665          * @param type the type of the method
2666          * @return the desired method handle
2667          * @throws NoSuchMethodException if the method does not exist
2668          * @throws IllegalAccessException if access checking fails,
2669          *                                or if the method is not {@code static},
2670          *                                or if the method's variable arity modifier bit
2671          *                                is set and {@code asVarargsCollector} fails
2672          * @throws    SecurityException if a security manager is present and it
2673          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2674          * @throws NullPointerException if any argument is null
2675          */
2676         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2677             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2678             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2679         }
2680 
2681         /**
2682          * Produces a method handle for a virtual method.
2683          * The type of the method handle will be that of the method,
2684          * with the receiver type (usually {@code refc}) prepended.
2685          * The method and all its argument types must be accessible to the lookup object.
2686          * <p>
2687          * When called, the handle will treat the first argument as a receiver
2688          * and, for non-private methods, dispatch on the receiver's type to determine which method
2689          * implementation to enter.
2690          * For private methods the named method in {@code refc} will be invoked on the receiver.
2691          * (The dispatching action is identical with that performed by an
2692          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2693          * <p>
2694          * The first argument will be of type {@code refc} if the lookup
2695          * class has full privileges to access the member.  Otherwise
2696          * the member must be {@code protected} and the first argument
2697          * will be restricted in type to the lookup class.
2698          * <p>
2699          * The returned method handle will have
2700          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2701          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2702          * <p>
2703          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2704          * instructions and method handles produced by {@code findVirtual},
2705          * if the class is {@code MethodHandle} and the name string is
2706          * {@code invokeExact} or {@code invoke}, the resulting
2707          * method handle is equivalent to one produced by
2708          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2709          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2710          * with the same {@code type} argument.
2711          * <p>
2712          * If the class is {@code VarHandle} and the name string corresponds to
2713          * the name of a signature-polymorphic access mode method, the resulting
2714          * method handle is equivalent to one produced by
2715          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2716          * the access mode corresponding to the name string and with the same
2717          * {@code type} arguments.
2718          * <p>
2719          * <b>Example:</b>
2720          * {@snippet lang="java" :
2721 import static java.lang.invoke.MethodHandles.*;
2722 import static java.lang.invoke.MethodType.*;
2723 ...
2724 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2725   "concat", methodType(String.class, String.class));
2726 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2727   "hashCode", methodType(int.class));
2728 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2729   "hashCode", methodType(int.class));
2730 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2731 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2732 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2733 // interface method:
2734 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2735   "subSequence", methodType(CharSequence.class, int.class, int.class));
2736 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2737 // constructor "internal method" must be accessed differently:
2738 MethodType MT_newString = methodType(void.class); //()V for new String()
2739 try { assertEquals("impossible", lookup()
2740         .findVirtual(String.class, "<init>", MT_newString));
2741  } catch (NoSuchMethodException ex) { } // OK
2742 MethodHandle MH_newString = publicLookup()
2743   .findConstructor(String.class, MT_newString);
2744 assertEquals("", (String) MH_newString.invokeExact());
2745          * }
2746          *
2747          * @param refc the class or interface from which the method is accessed
2748          * @param name the name of the method
2749          * @param type the type of the method, with the receiver argument omitted
2750          * @return the desired method handle
2751          * @throws NoSuchMethodException if the method does not exist
2752          * @throws IllegalAccessException if access checking fails,
2753          *                                or if the method is {@code static},
2754          *                                or if the method's variable arity modifier bit
2755          *                                is set and {@code asVarargsCollector} fails
2756          * @throws    SecurityException if a security manager is present and it
2757          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2758          * @throws NullPointerException if any argument is null
2759          */
2760         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2761             if (refc == MethodHandle.class) {
2762                 MethodHandle mh = findVirtualForMH(name, type);
2763                 if (mh != null)  return mh;
2764             } else if (refc == VarHandle.class) {
2765                 MethodHandle mh = findVirtualForVH(name, type);
2766                 if (mh != null)  return mh;
2767             }
2768             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2769             MemberName method = resolveOrFail(refKind, refc, name, type);
2770             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2771         }
2772         private MethodHandle findVirtualForMH(String name, MethodType type) {
2773             // these names require special lookups because of the implicit MethodType argument
2774             if ("invoke".equals(name))
2775                 return invoker(type);
2776             if ("invokeExact".equals(name))
2777                 return exactInvoker(type);
2778             assert(!MemberName.isMethodHandleInvokeName(name));
2779             return null;
2780         }
2781         private MethodHandle findVirtualForVH(String name, MethodType type) {
2782             try {
2783                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2784             } catch (IllegalArgumentException e) {
2785                 return null;
2786             }
2787         }
2788 
2789         /**
2790          * Produces a method handle which creates an object and initializes it, using
2791          * the constructor of the specified type.
2792          * The parameter types of the method handle will be those of the constructor,
2793          * while the return type will be a reference to the constructor's class.
2794          * The constructor and all its argument types must be accessible to the lookup object.
2795          * <p>
2796          * The requested type must have a return type of {@code void}.
2797          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2798          * <p>
2799          * The returned method handle will have
2800          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2801          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2802          * <p>
2803          * If the returned method handle is invoked, the constructor's class will
2804          * be initialized, if it has not already been initialized.
2805          * <p><b>Example:</b>
2806          * {@snippet lang="java" :
2807 import static java.lang.invoke.MethodHandles.*;
2808 import static java.lang.invoke.MethodType.*;
2809 ...
2810 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2811   ArrayList.class, methodType(void.class, Collection.class));
2812 Collection orig = Arrays.asList("x", "y");
2813 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2814 assert(orig != copy);
2815 assertEquals(orig, copy);
2816 // a variable-arity constructor:
2817 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2818   ProcessBuilder.class, methodType(void.class, String[].class));
2819 ProcessBuilder pb = (ProcessBuilder)
2820   MH_newProcessBuilder.invoke("x", "y", "z");
2821 assertEquals("[x, y, z]", pb.command().toString());
2822          * }
2823          *
2824          *
2825          * @param refc the class or interface from which the method is accessed
2826          * @param type the type of the method, with the receiver argument omitted, and a void return type
2827          * @return the desired method handle
2828          * @throws NoSuchMethodException if the constructor does not exist
2829          * @throws IllegalAccessException if access checking fails
2830          *                                or if the method's variable arity modifier bit
2831          *                                is set and {@code asVarargsCollector} fails
2832          * @throws    SecurityException if a security manager is present and it
2833          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2834          * @throws NullPointerException if any argument is null
2835          */
2836         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2837             if (refc.isArray()) {
2838                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2839             }
2840             if (type.returnType() != void.class) {
2841                 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName());
2842             }
2843             String name = ConstantDescs.INIT_NAME;
2844             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2845             return getDirectConstructor(refc, ctor);
2846         }
2847 
2848         /**
2849          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2850          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2851          * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2852          * and then determines whether the class is accessible to this lookup object.
2853          * <p>
2854          * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}.
2855          * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences
2856          * of {@code '['} and followed by the element type as encoded in the
2857          * {@linkplain Class##nameFormat table} specified in {@link Class#getName}.
2858          * <p>
2859          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2860          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2861          *
2862          * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class
2863          *                   or the string representing an array class
2864          * @return the requested class.
2865          * @throws SecurityException if a security manager is present and it
2866          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2867          * @throws LinkageError if the linkage fails
2868          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2869          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2870          * modes.
2871          * @throws NullPointerException if {@code targetName} is null
2872          * @since 9
2873          * @jvms 5.4.3.1 Class and Interface Resolution
2874          */
2875         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2876             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2877             return accessClass(targetClass);
2878         }
2879 
2880         /**
2881          * Ensures that {@code targetClass} has been initialized. The class
2882          * to be initialized must be {@linkplain #accessClass accessible}
2883          * to this {@code Lookup} object.  This method causes {@code targetClass}
2884          * to be initialized if it has not been already initialized,
2885          * as specified in JVMS {@jvms 5.5}.
2886          *
2887          * <p>
2888          * This method returns when {@code targetClass} is fully initialized, or
2889          * when {@code targetClass} is being initialized by the current thread.
2890          *
2891          * @param <T> the type of the class to be initialized
2892          * @param targetClass the class to be initialized
2893          * @return {@code targetClass} that has been initialized, or that is being
2894          *         initialized by the current thread.
2895          *
2896          * @throws  IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2897          *          or array class
2898          * @throws  IllegalAccessException if {@code targetClass} is not
2899          *          {@linkplain #accessClass accessible} to this lookup
2900          * @throws  ExceptionInInitializerError if the class initialization provoked
2901          *          by this method fails
2902          * @throws  SecurityException if a security manager is present and it
2903          *          <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2904          * @since 15
2905          * @jvms 5.5 Initialization
2906          */
2907         public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException {
2908             if (targetClass.isPrimitive())
2909                 throw new IllegalArgumentException(targetClass + " is a primitive class");
2910             if (targetClass.isArray())
2911                 throw new IllegalArgumentException(targetClass + " is an array class");
2912 
2913             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2914                 throw makeAccessException(targetClass);
2915             }
2916             checkSecurityManager(targetClass);
2917 
2918             // ensure class initialization
2919             Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2920             return targetClass;
2921         }
2922 
2923         /*
2924          * Returns IllegalAccessException due to access violation to the given targetClass.
2925          *
2926          * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2927          * which verifies access to a class rather a member.
2928          */
2929         private IllegalAccessException makeAccessException(Class<?> targetClass) {
2930             String message = "access violation: "+ targetClass;
2931             if (this == MethodHandles.publicLookup()) {
2932                 message += ", from public Lookup";
2933             } else {
2934                 Module m = lookupClass().getModule();
2935                 message += ", from " + lookupClass() + " (" + m + ")";
2936                 if (prevLookupClass != null) {
2937                     message += ", previous lookup " +
2938                             prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2939                 }
2940             }
2941             return new IllegalAccessException(message);
2942         }
2943 
2944         /**
2945          * Determines if a class can be accessed from the lookup context defined by
2946          * this {@code Lookup} object. The static initializer of the class is not run.
2947          * If {@code targetClass} is an array class, {@code targetClass} is accessible
2948          * if the element type of the array class is accessible.  Otherwise,
2949          * {@code targetClass} is determined as accessible as follows.
2950          *
2951          * <p>
2952          * If {@code targetClass} is in the same module as the lookup class,
2953          * the lookup class is {@code LC} in module {@code M1} and
2954          * the previous lookup class is in module {@code M0} or
2955          * {@code null} if not present,
2956          * {@code targetClass} is accessible if and only if one of the following is true:
2957          * <ul>
2958          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2959          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2960          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2961          *     in the same runtime package of {@code LC}.</li>
2962          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2963          *     a public type in {@code M1}.</li>
2964          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2965          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2966          *     if the previous lookup class is present; otherwise, {@code targetClass}
2967          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2968          * </ul>
2969          *
2970          * <p>
2971          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2972          * can access public types in all modules when the type is in a package
2973          * that is exported unconditionally.
2974          * <p>
2975          * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2976          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2977          * is inaccessible.
2978          * <p>
2979          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2980          * {@code M1} is the module containing {@code lookupClass} and
2981          * {@code M2} is the module containing {@code targetClass},
2982          * then {@code targetClass} is accessible if and only if
2983          * <ul>
2984          * <li>{@code M1} reads {@code M2}, and
2985          * <li>{@code targetClass} is public and in a package exported by
2986          *     {@code M2} at least to {@code M1}.
2987          * </ul>
2988          * <p>
2989          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2990          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2991          * containing the previous lookup class, then {@code targetClass} is accessible
2992          * if and only if one of the following is true:
2993          * <ul>
2994          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2995          *     {@linkplain Module#reads reads} {@code M0} and the type is
2996          *     in a package that is exported to at least {@code M1}.
2997          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2998          *     {@linkplain Module#reads reads} {@code M1} and the type is
2999          *     in a package that is exported to at least {@code M0}.
3000          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
3001          *     and {@code M1} reads {@code M2} and the type is in a package
3002          *     that is exported to at least both {@code M0} and {@code M2}.
3003          * </ul>
3004          * <p>
3005          * Otherwise, {@code targetClass} is not accessible.
3006          *
3007          * @param <T> the type of the class to be access-checked
3008          * @param targetClass the class to be access-checked
3009          * @return {@code targetClass} that has been access-checked
3010          * @throws IllegalAccessException if the class is not accessible from the lookup class
3011          * and previous lookup class, if present, using the allowed access modes.
3012          * @throws SecurityException if a security manager is present and it
3013          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3014          * @throws NullPointerException if {@code targetClass} is {@code null}
3015          * @since 9
3016          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
3017          */
3018         public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException {
3019             if (!isClassAccessible(targetClass)) {
3020                 throw makeAccessException(targetClass);
3021             }
3022             checkSecurityManager(targetClass);
3023             return targetClass;
3024         }
3025 
3026         /**
3027          * Produces an early-bound method handle for a virtual method.
3028          * It will bypass checks for overriding methods on the receiver,
3029          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3030          * instruction from within the explicitly specified {@code specialCaller}.
3031          * The type of the method handle will be that of the method,
3032          * with a suitably restricted receiver type prepended.
3033          * (The receiver type will be {@code specialCaller} or a subtype.)
3034          * The method and all its argument types must be accessible
3035          * to the lookup object.
3036          * <p>
3037          * Before method resolution,
3038          * if the explicitly specified caller class is not identical with the
3039          * lookup class, or if this lookup object does not have
3040          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3041          * privileges, the access fails.
3042          * <p>
3043          * The returned method handle will have
3044          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3045          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3046          * <p style="font-size:smaller;">
3047          * <em>(Note:  JVM internal methods named {@value ConstantDescs#INIT_NAME}
3048          * are not visible to this API,
3049          * even though the {@code invokespecial} instruction can refer to them
3050          * in special circumstances.  Use {@link #findConstructor findConstructor}
3051          * to access instance initialization methods in a safe manner.)</em>
3052          * <p><b>Example:</b>
3053          * {@snippet lang="java" :
3054 import static java.lang.invoke.MethodHandles.*;
3055 import static java.lang.invoke.MethodType.*;
3056 ...
3057 static class Listie extends ArrayList {
3058   public String toString() { return "[wee Listie]"; }
3059   static Lookup lookup() { return MethodHandles.lookup(); }
3060 }
3061 ...
3062 // no access to constructor via invokeSpecial:
3063 MethodHandle MH_newListie = Listie.lookup()
3064   .findConstructor(Listie.class, methodType(void.class));
3065 Listie l = (Listie) MH_newListie.invokeExact();
3066 try { assertEquals("impossible", Listie.lookup().findSpecial(
3067         Listie.class, "<init>", methodType(void.class), Listie.class));
3068  } catch (NoSuchMethodException ex) { } // OK
3069 // access to super and self methods via invokeSpecial:
3070 MethodHandle MH_super = Listie.lookup().findSpecial(
3071   ArrayList.class, "toString" , methodType(String.class), Listie.class);
3072 MethodHandle MH_this = Listie.lookup().findSpecial(
3073   Listie.class, "toString" , methodType(String.class), Listie.class);
3074 MethodHandle MH_duper = Listie.lookup().findSpecial(
3075   Object.class, "toString" , methodType(String.class), Listie.class);
3076 assertEquals("[]", (String) MH_super.invokeExact(l));
3077 assertEquals(""+l, (String) MH_this.invokeExact(l));
3078 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
3079 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
3080         String.class, "toString", methodType(String.class), Listie.class));
3081  } catch (IllegalAccessException ex) { } // OK
3082 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
3083 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
3084          * }
3085          *
3086          * @param refc the class or interface from which the method is accessed
3087          * @param name the name of the method (which must not be "&lt;init&gt;")
3088          * @param type the type of the method, with the receiver argument omitted
3089          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
3090          * @return the desired method handle
3091          * @throws NoSuchMethodException if the method does not exist
3092          * @throws IllegalAccessException if access checking fails,
3093          *                                or if the method is {@code static},
3094          *                                or if the method's variable arity modifier bit
3095          *                                is set and {@code asVarargsCollector} fails
3096          * @throws    SecurityException if a security manager is present and it
3097          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3098          * @throws NullPointerException if any argument is null
3099          */
3100         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
3101                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
3102             checkSpecialCaller(specialCaller, refc);
3103             Lookup specialLookup = this.in(specialCaller);
3104             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
3105             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
3106         }
3107 
3108         /**
3109          * Produces a method handle giving read access to a non-static field.
3110          * The type of the method handle will have a return type of the field's
3111          * value type.
3112          * The method handle's single argument will be the instance containing
3113          * the field.
3114          * Access checking is performed immediately on behalf of the lookup class.
3115          * @param refc the class or interface from which the method is accessed
3116          * @param name the field's name
3117          * @param type the field's type
3118          * @return a method handle which can load values from the field
3119          * @throws NoSuchFieldException if the field does not exist
3120          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3121          * @throws    SecurityException if a security manager is present and it
3122          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3123          * @throws NullPointerException if any argument is null
3124          * @see #findVarHandle(Class, String, Class)
3125          */
3126         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3127             MemberName field = resolveOrFail(REF_getField, refc, name, type);
3128             return getDirectField(REF_getField, refc, field);
3129         }
3130 
3131         /**
3132          * Produces a method handle giving write access to a non-static field.
3133          * The type of the method handle will have a void return type.
3134          * The method handle will take two arguments, the instance containing
3135          * the field, and the value to be stored.
3136          * The second argument will be of the field's value type.
3137          * Access checking is performed immediately on behalf of the lookup class.
3138          * @param refc the class or interface from which the method is accessed
3139          * @param name the field's name
3140          * @param type the field's type
3141          * @return a method handle which can store values into the field
3142          * @throws NoSuchFieldException if the field does not exist
3143          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3144          *                                or {@code final}
3145          * @throws    SecurityException if a security manager is present and it
3146          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3147          * @throws NullPointerException if any argument is null
3148          * @see #findVarHandle(Class, String, Class)
3149          */
3150         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3151             MemberName field = resolveOrFail(REF_putField, refc, name, type);
3152             return getDirectField(REF_putField, refc, field);
3153         }
3154 
3155         /**
3156          * Produces a VarHandle giving access to a non-static field {@code name}
3157          * of type {@code type} declared in a class of type {@code recv}.
3158          * The VarHandle's variable type is {@code type} and it has one
3159          * coordinate type, {@code recv}.
3160          * <p>
3161          * Access checking is performed immediately on behalf of the lookup
3162          * class.
3163          * <p>
3164          * Certain access modes of the returned VarHandle are unsupported under
3165          * the following conditions:
3166          * <ul>
3167          * <li>if the field is declared {@code final}, then the write, atomic
3168          *     update, numeric atomic update, and bitwise atomic update access
3169          *     modes are unsupported.
3170          * <li>if the field type is anything other than {@code byte},
3171          *     {@code short}, {@code char}, {@code int}, {@code long},
3172          *     {@code float}, or {@code double} then numeric atomic update
3173          *     access modes are unsupported.
3174          * <li>if the field type is anything other than {@code boolean},
3175          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3176          *     {@code long} then bitwise atomic update access modes are
3177          *     unsupported.
3178          * </ul>
3179          * <p>
3180          * If the field is declared {@code volatile} then the returned VarHandle
3181          * will override access to the field (effectively ignore the
3182          * {@code volatile} declaration) in accordance to its specified
3183          * access modes.
3184          * <p>
3185          * If the field type is {@code float} or {@code double} then numeric
3186          * and atomic update access modes compare values using their bitwise
3187          * representation (see {@link Float#floatToRawIntBits} and
3188          * {@link Double#doubleToRawLongBits}, respectively).
3189          * @apiNote
3190          * Bitwise comparison of {@code float} values or {@code double} values,
3191          * as performed by the numeric and atomic update access modes, differ
3192          * from the primitive {@code ==} operator and the {@link Float#equals}
3193          * and {@link Double#equals} methods, specifically with respect to
3194          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3195          * Care should be taken when performing a compare and set or a compare
3196          * and exchange operation with such values since the operation may
3197          * unexpectedly fail.
3198          * There are many possible NaN values that are considered to be
3199          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3200          * provided by Java can distinguish between them.  Operation failure can
3201          * occur if the expected or witness value is a NaN value and it is
3202          * transformed (perhaps in a platform specific manner) into another NaN
3203          * value, and thus has a different bitwise representation (see
3204          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3205          * details).
3206          * The values {@code -0.0} and {@code +0.0} have different bitwise
3207          * representations but are considered equal when using the primitive
3208          * {@code ==} operator.  Operation failure can occur if, for example, a
3209          * numeric algorithm computes an expected value to be say {@code -0.0}
3210          * and previously computed the witness value to be say {@code +0.0}.
3211          * @param recv the receiver class, of type {@code R}, that declares the
3212          * non-static field
3213          * @param name the field's name
3214          * @param type the field's type, of type {@code T}
3215          * @return a VarHandle giving access to non-static fields.
3216          * @throws NoSuchFieldException if the field does not exist
3217          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3218          * @throws    SecurityException if a security manager is present and it
3219          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3220          * @throws NullPointerException if any argument is null
3221          * @since 9
3222          */
3223         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3224             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3225             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3226             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3227         }
3228 
3229         /**
3230          * Produces a method handle giving read access to a static field.
3231          * The type of the method handle will have a return type of the field's
3232          * value type.
3233          * The method handle will take no arguments.
3234          * Access checking is performed immediately on behalf of the lookup class.
3235          * <p>
3236          * If the returned method handle is invoked, the field's class will
3237          * be initialized, if it has not already been initialized.
3238          * @param refc the class or interface from which the method is accessed
3239          * @param name the field's name
3240          * @param type the field's type
3241          * @return a method handle which can load values from the field
3242          * @throws NoSuchFieldException if the field does not exist
3243          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3244          * @throws    SecurityException if a security manager is present and it
3245          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3246          * @throws NullPointerException if any argument is null
3247          */
3248         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3249             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3250             return getDirectField(REF_getStatic, refc, field);
3251         }
3252 
3253         /**
3254          * Produces a method handle giving write access to a static field.
3255          * The type of the method handle will have a void return type.
3256          * The method handle will take a single
3257          * argument, of the field's value type, the value to be stored.
3258          * Access checking is performed immediately on behalf of the lookup class.
3259          * <p>
3260          * If the returned method handle is invoked, the field's class will
3261          * be initialized, if it has not already been initialized.
3262          * @param refc the class or interface from which the method is accessed
3263          * @param name the field's name
3264          * @param type the field's type
3265          * @return a method handle which can store values into the field
3266          * @throws NoSuchFieldException if the field does not exist
3267          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3268          *                                or is {@code final}
3269          * @throws    SecurityException if a security manager is present and it
3270          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3271          * @throws NullPointerException if any argument is null
3272          */
3273         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3274             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3275             return getDirectField(REF_putStatic, refc, field);
3276         }
3277 
3278         /**
3279          * Produces a VarHandle giving access to a static field {@code name} of
3280          * type {@code type} declared in a class of type {@code decl}.
3281          * The VarHandle's variable type is {@code type} and it has no
3282          * coordinate types.
3283          * <p>
3284          * Access checking is performed immediately on behalf of the lookup
3285          * class.
3286          * <p>
3287          * If the returned VarHandle is operated on, the declaring class will be
3288          * initialized, if it has not already been initialized.
3289          * <p>
3290          * Certain access modes of the returned VarHandle are unsupported under
3291          * the following conditions:
3292          * <ul>
3293          * <li>if the field is declared {@code final}, then the write, atomic
3294          *     update, numeric atomic update, and bitwise atomic update access
3295          *     modes are unsupported.
3296          * <li>if the field type is anything other than {@code byte},
3297          *     {@code short}, {@code char}, {@code int}, {@code long},
3298          *     {@code float}, or {@code double}, then numeric atomic update
3299          *     access modes are unsupported.
3300          * <li>if the field type is anything other than {@code boolean},
3301          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3302          *     {@code long} then bitwise atomic update access modes are
3303          *     unsupported.
3304          * </ul>
3305          * <p>
3306          * If the field is declared {@code volatile} then the returned VarHandle
3307          * will override access to the field (effectively ignore the
3308          * {@code volatile} declaration) in accordance to its specified
3309          * access modes.
3310          * <p>
3311          * If the field type is {@code float} or {@code double} then numeric
3312          * and atomic update access modes compare values using their bitwise
3313          * representation (see {@link Float#floatToRawIntBits} and
3314          * {@link Double#doubleToRawLongBits}, respectively).
3315          * @apiNote
3316          * Bitwise comparison of {@code float} values or {@code double} values,
3317          * as performed by the numeric and atomic update access modes, differ
3318          * from the primitive {@code ==} operator and the {@link Float#equals}
3319          * and {@link Double#equals} methods, specifically with respect to
3320          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3321          * Care should be taken when performing a compare and set or a compare
3322          * and exchange operation with such values since the operation may
3323          * unexpectedly fail.
3324          * There are many possible NaN values that are considered to be
3325          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3326          * provided by Java can distinguish between them.  Operation failure can
3327          * occur if the expected or witness value is a NaN value and it is
3328          * transformed (perhaps in a platform specific manner) into another NaN
3329          * value, and thus has a different bitwise representation (see
3330          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3331          * details).
3332          * The values {@code -0.0} and {@code +0.0} have different bitwise
3333          * representations but are considered equal when using the primitive
3334          * {@code ==} operator.  Operation failure can occur if, for example, a
3335          * numeric algorithm computes an expected value to be say {@code -0.0}
3336          * and previously computed the witness value to be say {@code +0.0}.
3337          * @param decl the class that declares the static field
3338          * @param name the field's name
3339          * @param type the field's type, of type {@code T}
3340          * @return a VarHandle giving access to a static field
3341          * @throws NoSuchFieldException if the field does not exist
3342          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3343          * @throws    SecurityException if a security manager is present and it
3344          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3345          * @throws NullPointerException if any argument is null
3346          * @since 9
3347          */
3348         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3349             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3350             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3351             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3352         }
3353 
3354         /**
3355          * Produces an early-bound method handle for a non-static method.
3356          * The receiver must have a supertype {@code defc} in which a method
3357          * of the given name and type is accessible to the lookup class.
3358          * The method and all its argument types must be accessible to the lookup object.
3359          * The type of the method handle will be that of the method,
3360          * without any insertion of an additional receiver parameter.
3361          * The given receiver will be bound into the method handle,
3362          * so that every call to the method handle will invoke the
3363          * requested method on the given receiver.
3364          * <p>
3365          * The returned method handle will have
3366          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3367          * the method's variable arity modifier bit ({@code 0x0080}) is set
3368          * <em>and</em> the trailing array argument is not the only argument.
3369          * (If the trailing array argument is the only argument,
3370          * the given receiver value will be bound to it.)
3371          * <p>
3372          * This is almost equivalent to the following code, with some differences noted below:
3373          * {@snippet lang="java" :
3374 import static java.lang.invoke.MethodHandles.*;
3375 import static java.lang.invoke.MethodType.*;
3376 ...
3377 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3378 MethodHandle mh1 = mh0.bindTo(receiver);
3379 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3380 return mh1;
3381          * }
3382          * where {@code defc} is either {@code receiver.getClass()} or a super
3383          * type of that class, in which the requested method is accessible
3384          * to the lookup class.
3385          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3386          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3387          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3388          * the receiver is restricted by {@code findVirtual} to the lookup class.)
3389          * @param receiver the object from which the method is accessed
3390          * @param name the name of the method
3391          * @param type the type of the method, with the receiver argument omitted
3392          * @return the desired method handle
3393          * @throws NoSuchMethodException if the method does not exist
3394          * @throws IllegalAccessException if access checking fails
3395          *                                or if the method's variable arity modifier bit
3396          *                                is set and {@code asVarargsCollector} fails
3397          * @throws    SecurityException if a security manager is present and it
3398          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3399          * @throws NullPointerException if any argument is null
3400          * @see MethodHandle#bindTo
3401          * @see #findVirtual
3402          */
3403         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3404             Class<? extends Object> refc = receiver.getClass(); // may get NPE
3405             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3406             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3407             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3408                 throw new IllegalAccessException("The restricted defining class " +
3409                                                  mh.type().leadingReferenceParameter().getName() +
3410                                                  " is not assignable from receiver class " +
3411                                                  receiver.getClass().getName());
3412             }
3413             return mh.bindArgumentL(0, receiver).setVarargs(method);
3414         }
3415 
3416         /**
3417          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3418          * to <i>m</i>, if the lookup class has permission.
3419          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3420          * If <i>m</i> is virtual, overriding is respected on every call.
3421          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3422          * The type of the method handle will be that of the method,
3423          * with the receiver type prepended (but only if it is non-static).
3424          * If the method's {@code accessible} flag is not set,
3425          * access checking is performed immediately on behalf of the lookup class.
3426          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3427          * <p>
3428          * The returned method handle will have
3429          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3430          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3431          * <p>
3432          * If <i>m</i> is static, and
3433          * if the returned method handle is invoked, the method's class will
3434          * be initialized, if it has not already been initialized.
3435          * @param m the reflected method
3436          * @return a method handle which can invoke the reflected method
3437          * @throws IllegalAccessException if access checking fails
3438          *                                or if the method's variable arity modifier bit
3439          *                                is set and {@code asVarargsCollector} fails
3440          * @throws NullPointerException if the argument is null
3441          */
3442         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3443             if (m.getDeclaringClass() == MethodHandle.class) {
3444                 MethodHandle mh = unreflectForMH(m);
3445                 if (mh != null)  return mh;
3446             }
3447             if (m.getDeclaringClass() == VarHandle.class) {
3448                 MethodHandle mh = unreflectForVH(m);
3449                 if (mh != null)  return mh;
3450             }
3451             MemberName method = new MemberName(m);
3452             byte refKind = method.getReferenceKind();
3453             if (refKind == REF_invokeSpecial)
3454                 refKind = REF_invokeVirtual;
3455             assert(method.isMethod());
3456             @SuppressWarnings("deprecation")
3457             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3458             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3459         }
3460         private MethodHandle unreflectForMH(Method m) {
3461             // these names require special lookups because they throw UnsupportedOperationException
3462             if (MemberName.isMethodHandleInvokeName(m.getName()))
3463                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3464             return null;
3465         }
3466         private MethodHandle unreflectForVH(Method m) {
3467             // these names require special lookups because they throw UnsupportedOperationException
3468             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3469                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3470             return null;
3471         }
3472 
3473         /**
3474          * Produces a method handle for a reflected method.
3475          * It will bypass checks for overriding methods on the receiver,
3476          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3477          * instruction from within the explicitly specified {@code specialCaller}.
3478          * The type of the method handle will be that of the method,
3479          * with a suitably restricted receiver type prepended.
3480          * (The receiver type will be {@code specialCaller} or a subtype.)
3481          * If the method's {@code accessible} flag is not set,
3482          * access checking is performed immediately on behalf of the lookup class,
3483          * as if {@code invokespecial} instruction were being linked.
3484          * <p>
3485          * Before method resolution,
3486          * if the explicitly specified caller class is not identical with the
3487          * lookup class, or if this lookup object does not have
3488          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3489          * privileges, the access fails.
3490          * <p>
3491          * The returned method handle will have
3492          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3493          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3494          * @param m the reflected method
3495          * @param specialCaller the class nominally calling the method
3496          * @return a method handle which can invoke the reflected method
3497          * @throws IllegalAccessException if access checking fails,
3498          *                                or if the method is {@code static},
3499          *                                or if the method's variable arity modifier bit
3500          *                                is set and {@code asVarargsCollector} fails
3501          * @throws NullPointerException if any argument is null
3502          */
3503         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3504             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3505             Lookup specialLookup = this.in(specialCaller);
3506             MemberName method = new MemberName(m, true);
3507             assert(method.isMethod());
3508             // ignore m.isAccessible:  this is a new kind of access
3509             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3510         }
3511 
3512         /**
3513          * Produces a method handle for a reflected constructor.
3514          * The type of the method handle will be that of the constructor,
3515          * with the return type changed to the declaring class.
3516          * The method handle will perform a {@code newInstance} operation,
3517          * creating a new instance of the constructor's class on the
3518          * arguments passed to the method handle.
3519          * <p>
3520          * If the constructor's {@code accessible} flag is not set,
3521          * access checking is performed immediately on behalf of the lookup class.
3522          * <p>
3523          * The returned method handle will have
3524          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3525          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3526          * <p>
3527          * If the returned method handle is invoked, the constructor's class will
3528          * be initialized, if it has not already been initialized.
3529          * @param c the reflected constructor
3530          * @return a method handle which can invoke the reflected constructor
3531          * @throws IllegalAccessException if access checking fails
3532          *                                or if the method's variable arity modifier bit
3533          *                                is set and {@code asVarargsCollector} fails
3534          * @throws NullPointerException if the argument is null
3535          */
3536         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3537             MemberName ctor = new MemberName(c);
3538             assert(ctor.isObjectConstructor() || ctor.isStaticValueFactoryMethod());
3539             @SuppressWarnings("deprecation")
3540             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3541             Class<?> defc = c.getDeclaringClass();
3542             if (ctor.isObjectConstructor()) {
3543                 assert(ctor.getMethodType().returnType() == void.class);
3544                 return lookup.getDirectConstructorNoSecurityManager(defc, ctor);
3545             } else {
3546                 // static init factory is a static method
3547                 assert(ctor.isMethod() && ctor.getMethodType().returnType() == defc && ctor.getReferenceKind() == REF_invokeStatic) : ctor.toString();
3548                 assert(!MethodHandleNatives.isCallerSensitive(ctor));  // must not be caller-sensitive
3549                 return lookup.getDirectMethodNoSecurityManager(ctor.getReferenceKind(), defc, ctor, lookup);
3550             }
3551         }
3552 
3553         /**
3554          * Produces a method handle giving read access to a reflected field.
3555          * The type of the method handle will have a return type of the field's
3556          * value type.
3557          * If the field is {@code static}, the method handle will take no arguments.
3558          * Otherwise, its single argument will be the instance containing
3559          * the field.
3560          * If the {@code Field} object's {@code accessible} flag is not set,
3561          * access checking is performed immediately on behalf of the lookup class.
3562          * <p>
3563          * If the field is static, and
3564          * if the returned method handle is invoked, the field's class will
3565          * be initialized, if it has not already been initialized.
3566          * @param f the reflected field
3567          * @return a method handle which can load values from the reflected field
3568          * @throws IllegalAccessException if access checking fails
3569          * @throws NullPointerException if the argument is null
3570          */
3571         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3572             return unreflectField(f, false);
3573         }
3574 
3575         /**
3576          * Produces a method handle giving write access to a reflected field.
3577          * The type of the method handle will have a void return type.
3578          * If the field is {@code static}, the method handle will take a single
3579          * argument, of the field's value type, the value to be stored.
3580          * Otherwise, the two arguments will be the instance containing
3581          * the field, and the value to be stored.
3582          * If the {@code Field} object's {@code accessible} flag is not set,
3583          * access checking is performed immediately on behalf of the lookup class.
3584          * <p>
3585          * If the field is {@code final}, write access will not be
3586          * allowed and access checking will fail, except under certain
3587          * narrow circumstances documented for {@link Field#set Field.set}.
3588          * A method handle is returned only if a corresponding call to
3589          * the {@code Field} object's {@code set} method could return
3590          * normally.  In particular, fields which are both {@code static}
3591          * and {@code final} may never be set.
3592          * <p>
3593          * If the field is {@code static}, and
3594          * if the returned method handle is invoked, the field's class will
3595          * be initialized, if it has not already been initialized.
3596          * @param f the reflected field
3597          * @return a method handle which can store values into the reflected field
3598          * @throws IllegalAccessException if access checking fails,
3599          *         or if the field is {@code final} and write access
3600          *         is not enabled on the {@code Field} object
3601          * @throws NullPointerException if the argument is null
3602          */
3603         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3604             return unreflectField(f, true);
3605         }
3606 
3607         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3608             MemberName field = new MemberName(f, isSetter);
3609             if (isSetter && field.isFinal()) {
3610                 if (field.isTrustedFinalField()) {
3611                     String msg = field.isStatic() ? "static final field has no write access"
3612                                                   : "final field has no write access";
3613                     throw field.makeAccessException(msg, this);
3614                 }
3615             }
3616             assert(isSetter
3617                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3618                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3619             @SuppressWarnings("deprecation")
3620             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3621             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3622         }
3623 
3624         /**
3625          * Produces a VarHandle giving access to a reflected field {@code f}
3626          * of type {@code T} declared in a class of type {@code R}.
3627          * The VarHandle's variable type is {@code T}.
3628          * If the field is non-static the VarHandle has one coordinate type,
3629          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3630          * coordinate types.
3631          * <p>
3632          * Access checking is performed immediately on behalf of the lookup
3633          * class, regardless of the value of the field's {@code accessible}
3634          * flag.
3635          * <p>
3636          * If the field is static, and if the returned VarHandle is operated
3637          * on, the field's declaring class will be initialized, if it has not
3638          * already been initialized.
3639          * <p>
3640          * Certain access modes of the returned VarHandle are unsupported under
3641          * the following conditions:
3642          * <ul>
3643          * <li>if the field is declared {@code final}, then the write, atomic
3644          *     update, numeric atomic update, and bitwise atomic update access
3645          *     modes are unsupported.
3646          * <li>if the field type is anything other than {@code byte},
3647          *     {@code short}, {@code char}, {@code int}, {@code long},
3648          *     {@code float}, or {@code double} then numeric atomic update
3649          *     access modes are unsupported.
3650          * <li>if the field type is anything other than {@code boolean},
3651          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3652          *     {@code long} then bitwise atomic update access modes are
3653          *     unsupported.
3654          * </ul>
3655          * <p>
3656          * If the field is declared {@code volatile} then the returned VarHandle
3657          * will override access to the field (effectively ignore the
3658          * {@code volatile} declaration) in accordance to its specified
3659          * access modes.
3660          * <p>
3661          * If the field type is {@code float} or {@code double} then numeric
3662          * and atomic update access modes compare values using their bitwise
3663          * representation (see {@link Float#floatToRawIntBits} and
3664          * {@link Double#doubleToRawLongBits}, respectively).
3665          * @apiNote
3666          * Bitwise comparison of {@code float} values or {@code double} values,
3667          * as performed by the numeric and atomic update access modes, differ
3668          * from the primitive {@code ==} operator and the {@link Float#equals}
3669          * and {@link Double#equals} methods, specifically with respect to
3670          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3671          * Care should be taken when performing a compare and set or a compare
3672          * and exchange operation with such values since the operation may
3673          * unexpectedly fail.
3674          * There are many possible NaN values that are considered to be
3675          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3676          * provided by Java can distinguish between them.  Operation failure can
3677          * occur if the expected or witness value is a NaN value and it is
3678          * transformed (perhaps in a platform specific manner) into another NaN
3679          * value, and thus has a different bitwise representation (see
3680          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3681          * details).
3682          * The values {@code -0.0} and {@code +0.0} have different bitwise
3683          * representations but are considered equal when using the primitive
3684          * {@code ==} operator.  Operation failure can occur if, for example, a
3685          * numeric algorithm computes an expected value to be say {@code -0.0}
3686          * and previously computed the witness value to be say {@code +0.0}.
3687          * @param f the reflected field, with a field of type {@code T}, and
3688          * a declaring class of type {@code R}
3689          * @return a VarHandle giving access to non-static fields or a static
3690          * field
3691          * @throws IllegalAccessException if access checking fails
3692          * @throws NullPointerException if the argument is null
3693          * @since 9
3694          */
3695         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3696             MemberName getField = new MemberName(f, false);
3697             MemberName putField = new MemberName(f, true);
3698             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
3699                                                       f.getDeclaringClass(), getField, putField);
3700         }
3701 
3702         /**
3703          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3704          * created by this lookup object or a similar one.
3705          * Security and access checks are performed to ensure that this lookup object
3706          * is capable of reproducing the target method handle.
3707          * This means that the cracking may fail if target is a direct method handle
3708          * but was created by an unrelated lookup object.
3709          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3710          * and was created by a lookup object for a different class.
3711          * @param target a direct method handle to crack into symbolic reference components
3712          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3713          * @throws    SecurityException if a security manager is present and it
3714          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3715          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3716          * @throws    NullPointerException if the target is {@code null}
3717          * @see MethodHandleInfo
3718          * @since 1.8
3719          */
3720         public MethodHandleInfo revealDirect(MethodHandle target) {
3721             if (!target.isCrackable()) {
3722                 throw newIllegalArgumentException("not a direct method handle");
3723             }
3724             MemberName member = target.internalMemberName();
3725             Class<?> defc = member.getDeclaringClass();
3726             byte refKind = member.getReferenceKind();
3727             assert(MethodHandleNatives.refKindIsValid(refKind));
3728             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3729                 // Devirtualized method invocation is usually formally virtual.
3730                 // To avoid creating extra MemberName objects for this common case,
3731                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3732                 refKind = REF_invokeVirtual;
3733             if (refKind == REF_invokeVirtual && defc.isInterface())
3734                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3735                 refKind = REF_invokeInterface;
3736             // Check SM permissions and member access before cracking.
3737             try {
3738                 checkAccess(refKind, defc, member);
3739                 checkSecurityManager(defc, member);
3740             } catch (IllegalAccessException ex) {
3741                 throw new IllegalArgumentException(ex);
3742             }
3743             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3744                 Class<?> callerClass = target.internalCallerClass();
3745                 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3746                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3747             }
3748             // Produce the handle to the results.
3749             return new InfoFromMemberName(this, member, refKind);
3750         }
3751 
3752         /// Helper methods, all package-private.
3753 
3754         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3755             checkSymbolicClass(refc);  // do this before attempting to resolve
3756             Objects.requireNonNull(name);
3757             Objects.requireNonNull(type);
3758             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3759                                             NoSuchFieldException.class);
3760         }
3761 
3762         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3763             checkSymbolicClass(refc);  // do this before attempting to resolve
3764             Objects.requireNonNull(type);
3765             checkMethodName(refKind, name);  // implicit null-check of name
3766             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3767                                             NoSuchMethodException.class);
3768         }
3769 
3770         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3771             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3772             Objects.requireNonNull(member.getName());
3773             Objects.requireNonNull(member.getType());
3774             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3775                                             ReflectiveOperationException.class);
3776         }
3777 
3778         MemberName resolveOrNull(byte refKind, MemberName member) {
3779             // do this before attempting to resolve
3780             if (!isClassAccessible(member.getDeclaringClass())) {
3781                 return null;
3782             }
3783             Objects.requireNonNull(member.getName());
3784             Objects.requireNonNull(member.getType());
3785             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3786         }
3787 
3788         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3789             // do this before attempting to resolve
3790             if (!isClassAccessible(refc)) {
3791                 return null;
3792             }
3793             Objects.requireNonNull(type);
3794             // implicit null-check of name
3795             if (isIllegalMethodName(refKind, name)) {
3796                 return null;
3797             }
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         /*
3819          * "<init>" can only be invoked via invokespecial
3820          * "<vnew>" factory can only invoked via invokestatic
3821          */
3822         boolean isIllegalMethodName(byte refKind, String name) {
3823             if (name.startsWith("<")) {
3824                 return MemberName.VALUE_FACTORY_NAME.equals(name) ? refKind != REF_invokeStatic
3825                                                                   : refKind != REF_newInvokeSpecial;
3826             }
3827             return false;
3828         }
3829 
3830         /** Check name for an illegal leading "&lt;" character. */
3831         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3832             if (isIllegalMethodName(refKind, name)) {
3833                 throw new NoSuchMethodException("illegal method name: " + name + " " + refKind);
3834             }
3835         }
3836 
3837         /**
3838          * Find my trustable caller class if m is a caller sensitive method.
3839          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3840          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3841          */
3842         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3843             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3844                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3845                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3846             }
3847             return this;
3848         }
3849 
3850         /**
3851          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3852          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3853          *
3854          * @deprecated This method was originally designed to test {@code PRIVATE} access
3855          * that implies full privilege access but {@code MODULE} access has since become
3856          * independent of {@code PRIVATE} access.  It is recommended to call
3857          * {@link #hasFullPrivilegeAccess()} instead.
3858          * @since 9
3859          */
3860         @Deprecated(since="14")
3861         public boolean hasPrivateAccess() {
3862             return hasFullPrivilegeAccess();
3863         }
3864 
3865         /**
3866          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3867          * i.e. {@code PRIVATE} and {@code MODULE} access.
3868          * A {@code Lookup} object must have full privilege access in order to
3869          * access all members that are allowed to the
3870          * {@linkplain #lookupClass() lookup class}.
3871          *
3872          * @return {@code true} if this lookup has full privilege access.
3873          * @since 14
3874          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3875          */
3876         public boolean hasFullPrivilegeAccess() {
3877             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3878         }
3879 
3880         /**
3881          * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a>
3882          * for ensureInitialized, findClass or accessClass.
3883          */
3884         void checkSecurityManager(Class<?> refc) {
3885             if (allowedModes == TRUSTED)  return;
3886 
3887             @SuppressWarnings("removal")
3888             SecurityManager smgr = System.getSecurityManager();
3889             if (smgr == null)  return;
3890 
3891             // Step 1:
3892             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3893             if (!fullPrivilegeLookup ||
3894                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3895                 ReflectUtil.checkPackageAccess(refc);
3896             }
3897 
3898             // Step 2b:
3899             if (!fullPrivilegeLookup) {
3900                 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
3901             }
3902         }
3903 
3904         /**
3905          * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
3906          * Determines a trustable caller class to compare with refc, the symbolic reference class.
3907          * If this lookup object has full privilege access except original access,
3908          * then the caller class is the lookupClass.
3909          *
3910          * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)}
3911          * from the same module skips the security permission check.
3912          */
3913         void checkSecurityManager(Class<?> refc, MemberName m) {
3914             Objects.requireNonNull(refc);
3915             Objects.requireNonNull(m);
3916 
3917             if (allowedModes == TRUSTED)  return;
3918 
3919             @SuppressWarnings("removal")
3920             SecurityManager smgr = System.getSecurityManager();
3921             if (smgr == null)  return;
3922 
3923             // Step 1:
3924             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3925             if (!fullPrivilegeLookup ||
3926                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3927                 ReflectUtil.checkPackageAccess(refc);
3928             }
3929 
3930             // Step 2a:
3931             if (m.isPublic()) return;
3932             if (!fullPrivilegeLookup) {
3933                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3934             }
3935 
3936             // Step 3:
3937             Class<?> defc = m.getDeclaringClass();
3938             if (!fullPrivilegeLookup && PrimitiveClass.asPrimaryType(defc) != PrimitiveClass.asPrimaryType(refc)) {
3939                 ReflectUtil.checkPackageAccess(defc);
3940             }
3941         }
3942 
3943         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3944             boolean wantStatic = (refKind == REF_invokeStatic);
3945             String message;
3946             if (m.isObjectConstructor())
3947                 message = "expected a method, not a constructor";
3948             else if (!m.isMethod())
3949                 message = "expected a method";
3950             else if (wantStatic != m.isStatic())
3951                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3952             else
3953                 { checkAccess(refKind, refc, m); return; }
3954             throw m.makeAccessException(message, this);
3955         }
3956 
3957         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3958             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3959             String message;
3960             if (wantStatic != m.isStatic())
3961                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3962             else
3963                 { checkAccess(refKind, refc, m); return; }
3964             throw m.makeAccessException(message, this);
3965         }
3966 
3967         private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) {
3968             return Modifier.isProtected(m.getModifiers()) &&
3969                     refKind == REF_invokeVirtual &&
3970                     m.getDeclaringClass() == Object.class &&
3971                     m.getName().equals("clone") &&
3972                     refc.isArray();
3973         }
3974 
3975         /** Check public/protected/private bits on the symbolic reference class and its member. */
3976         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3977             assert(m.referenceKindIsConsistentWith(refKind) &&
3978                    MethodHandleNatives.refKindIsValid(refKind) &&
3979                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3980             int allowedModes = this.allowedModes;
3981             if (allowedModes == TRUSTED)  return;
3982             int mods = m.getModifiers();
3983             if (isArrayClone(refKind, refc, m)) {
3984                 // The JVM does this hack also.
3985                 // (See ClassVerifier::verify_invoke_instructions
3986                 // and LinkResolver::check_method_accessability.)
3987                 // Because the JVM does not allow separate methods on array types,
3988                 // there is no separate method for int[].clone.
3989                 // All arrays simply inherit Object.clone.
3990                 // But for access checking logic, we make Object.clone
3991                 // (normally protected) appear to be public.
3992                 // Later on, when the DirectMethodHandle is created,
3993                 // its leading argument will be restricted to the
3994                 // requested array type.
3995                 // N.B. The return type is not adjusted, because
3996                 // that is *not* the bytecode behavior.
3997                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3998             }
3999             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
4000                 // cannot "new" a protected ctor in a different package
4001                 mods ^= Modifier.PROTECTED;
4002             }
4003             if (Modifier.isFinal(mods) &&
4004                     MethodHandleNatives.refKindIsSetter(refKind))
4005                 throw m.makeAccessException("unexpected set of a final field", this);
4006             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
4007             if ((requestedModes & allowedModes) != 0) {
4008                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
4009                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
4010                     return;
4011             } else {
4012                 // Protected members can also be checked as if they were package-private.
4013                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
4014                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
4015                     return;
4016             }
4017             throw m.makeAccessException(accessFailedMessage(refc, m), this);
4018         }
4019 
4020         String accessFailedMessage(Class<?> refc, MemberName m) {
4021             Class<?> defc = m.getDeclaringClass();
4022             int mods = m.getModifiers();
4023             // check the class first:
4024             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
4025                                (PrimitiveClass.asPrimaryType(defc) == PrimitiveClass.asPrimaryType(refc) ||
4026                                 Modifier.isPublic(refc.getModifiers())));
4027             if (!classOK && (allowedModes & PACKAGE) != 0) {
4028                 // ignore previous lookup class to check if default package access
4029                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
4030                            (PrimitiveClass.asPrimaryType(defc) == PrimitiveClass.asPrimaryType(refc) ||
4031                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
4032             }
4033             if (!classOK)
4034                 return "class is not public";
4035             if (Modifier.isPublic(mods))
4036                 return "access to public member failed";  // (how?, module not readable?)
4037             if (Modifier.isPrivate(mods))
4038                 return "member is private";
4039             if (Modifier.isProtected(mods))
4040                 return "member is protected";
4041             return "member is private to package";
4042         }
4043 
4044         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
4045             int allowedModes = this.allowedModes;
4046             if (allowedModes == TRUSTED)  return;
4047             if ((lookupModes() & PRIVATE) == 0
4048                 || (specialCaller != lookupClass()
4049                        // ensure non-abstract methods in superinterfaces can be special-invoked
4050                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
4051                 throw new MemberName(specialCaller).
4052                     makeAccessException("no private access for invokespecial", this);
4053         }
4054 
4055         private boolean restrictProtectedReceiver(MemberName method) {
4056             // The accessing class only has the right to use a protected member
4057             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
4058             if (!method.isProtected() || method.isStatic()
4059                 || allowedModes == TRUSTED
4060                 || method.getDeclaringClass() == lookupClass()
4061                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
4062                 return false;
4063             return true;
4064         }
4065         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
4066             assert(!method.isStatic());
4067             // receiver type of mh is too wide; narrow to caller
4068             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
4069                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
4070             }
4071             MethodType rawType = mh.type();
4072             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
4073             MethodType narrowType = rawType.changeParameterType(0, caller);
4074             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
4075             assert(mh.viewAsTypeChecks(narrowType, true));
4076             return mh.copyWith(narrowType, mh.form);
4077         }
4078 
4079         /** Check access and get the requested method. */
4080         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4081             final boolean doRestrict    = true;
4082             final boolean checkSecurity = true;
4083             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4084         }
4085         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
4086         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4087             final boolean doRestrict    = false;
4088             final boolean checkSecurity = true;
4089             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
4090         }
4091         /** Check access and get the requested method, eliding security manager checks. */
4092         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4093             final boolean doRestrict    = true;
4094             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4095             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4096         }
4097         /** Common code for all methods; do not call directly except from immediately above. */
4098         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
4099                                                    boolean checkSecurity,
4100                                                    boolean doRestrict,
4101                                                    Lookup boundCaller) throws IllegalAccessException {
4102             checkMethod(refKind, refc, method);
4103             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4104             if (checkSecurity)
4105                 checkSecurityManager(refc, method);
4106             assert(!method.isMethodHandleInvoke());
4107             if (refKind == REF_invokeSpecial &&
4108                 refc != lookupClass() &&
4109                 !refc.isInterface() && !lookupClass().isInterface() &&
4110                 refc != lookupClass().getSuperclass() &&
4111                 refc.isAssignableFrom(lookupClass())) {
4112                 assert(!method.getName().equals(ConstantDescs.INIT_NAME));  // not this code path
4113 
4114                 // Per JVMS 6.5, desc. of invokespecial instruction:
4115                 // If the method is in a superclass of the LC,
4116                 // and if our original search was above LC.super,
4117                 // repeat the search (symbolic lookup) from LC.super
4118                 // and continue with the direct superclass of that class,
4119                 // and so forth, until a match is found or no further superclasses exist.
4120                 // FIXME: MemberName.resolve should handle this instead.
4121                 Class<?> refcAsSuper = lookupClass();
4122                 MemberName m2;
4123                 do {
4124                     refcAsSuper = refcAsSuper.getSuperclass();
4125                     m2 = new MemberName(refcAsSuper,
4126                                         method.getName(),
4127                                         method.getMethodType(),
4128                                         REF_invokeSpecial);
4129                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
4130                 } while (m2 == null &&         // no method is found yet
4131                          refc != refcAsSuper); // search up to refc
4132                 if (m2 == null)  throw new InternalError(method.toString());
4133                 method = m2;
4134                 refc = refcAsSuper;
4135                 // redo basic checks
4136                 checkMethod(refKind, refc, method);
4137             }
4138             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
4139             MethodHandle mh = dmh;
4140             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
4141             if ((doRestrict && refKind == REF_invokeSpecial) ||
4142                     (MethodHandleNatives.refKindHasReceiver(refKind) &&
4143                             restrictProtectedReceiver(method) &&
4144                             // All arrays simply inherit the protected Object.clone method.
4145                             // The leading argument is already restricted to the requested
4146                             // array type (not the lookup class).
4147                             !isArrayClone(refKind, refc, method))) {
4148                 mh = restrictReceiver(method, dmh, lookupClass());
4149             }
4150             mh = maybeBindCaller(method, mh, boundCaller);
4151             mh = mh.setVarargs(method);
4152             return mh;
4153         }
4154         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
4155                                              throws IllegalAccessException {
4156             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
4157                 return mh;
4158 
4159             // boundCaller must have full privilege access.
4160             // It should have been checked by findBoundCallerLookup. Safe to check this again.
4161             if ((boundCaller.lookupModes() & ORIGINAL) == 0)
4162                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
4163 
4164             assert boundCaller.hasFullPrivilegeAccess();
4165 
4166             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
4167             // Note: caller will apply varargs after this step happens.
4168             return cbmh;
4169         }
4170 
4171         /** Check access and get the requested field. */
4172         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4173             final boolean checkSecurity = true;
4174             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4175         }
4176         /** Check access and get the requested field, eliding security manager checks. */
4177         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4178             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4179             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4180         }
4181         /** Common code for all fields; do not call directly except from immediately above. */
4182         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
4183                                                   boolean checkSecurity) throws IllegalAccessException {
4184             checkField(refKind, refc, field);
4185             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4186             if (checkSecurity)
4187                 checkSecurityManager(refc, field);
4188             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
4189             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
4190                                     restrictProtectedReceiver(field));
4191             if (doRestrict)
4192                 return restrictReceiver(field, dmh, lookupClass());
4193             return dmh;
4194         }
4195         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
4196                                             Class<?> refc, MemberName getField, MemberName putField)
4197                 throws IllegalAccessException {
4198             final boolean checkSecurity = true;
4199             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4200         }
4201         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
4202                                                              Class<?> refc, MemberName getField, MemberName putField)
4203                 throws IllegalAccessException {
4204             final boolean checkSecurity = false;
4205             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4206         }
4207         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
4208                                                   Class<?> refc, MemberName getField, MemberName putField,
4209                                                   boolean checkSecurity) throws IllegalAccessException {
4210             assert getField.isStatic() == putField.isStatic();
4211             assert getField.isGetter() && putField.isSetter();
4212             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
4213             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
4214 
4215             checkField(getRefKind, refc, getField);
4216             if (checkSecurity)
4217                 checkSecurityManager(refc, getField);
4218 
4219             if (!putField.isFinal()) {
4220                 // A VarHandle does not support updates to final fields, any
4221                 // such VarHandle to a final field will be read-only and
4222                 // therefore the following write-based accessibility checks are
4223                 // only required for non-final fields
4224                 checkField(putRefKind, refc, putField);
4225                 if (checkSecurity)
4226                     checkSecurityManager(refc, putField);
4227             }
4228 
4229             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
4230                                   restrictProtectedReceiver(getField));
4231             if (doRestrict) {
4232                 assert !getField.isStatic();
4233                 // receiver type of VarHandle is too wide; narrow to caller
4234                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
4235                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4236                 }
4237                 refc = lookupClass();
4238             }
4239             return VarHandles.makeFieldHandle(getField, refc,
4240                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4241         }
4242         /** Check access and get the requested constructor. */
4243         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4244             final boolean checkSecurity = true;
4245             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4246         }
4247         /** Check access and get the requested constructor, eliding security manager checks. */
4248         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4249             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4250             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4251         }
4252         /** Common code for all constructors; do not call directly except from immediately above. */
4253         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4254                                                   boolean checkSecurity) throws IllegalAccessException {
4255             assert(ctor.isObjectConstructor());
4256             checkAccess(REF_newInvokeSpecial, refc, ctor);
4257             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4258             if (checkSecurity)
4259                 checkSecurityManager(refc, ctor);
4260             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4261             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4262         }
4263 
4264         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4265          */
4266         /*non-public*/
4267         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4268                 throws ReflectiveOperationException {
4269             if (!(type instanceof Class || type instanceof MethodType))
4270                 throw new InternalError("unresolved MemberName");
4271             MemberName member = new MemberName(refKind, defc, name, type);
4272             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4273             if (mh != null) {
4274                 checkSymbolicClass(defc);
4275                 return mh;
4276             }
4277             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
4278                 // Treat MethodHandle.invoke and invokeExact specially.
4279                 mh = findVirtualForMH(member.getName(), member.getMethodType());
4280                 if (mh != null) {
4281                     return mh;
4282                 }
4283             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4284                 // Treat signature-polymorphic methods on VarHandle specially.
4285                 mh = findVirtualForVH(member.getName(), member.getMethodType());
4286                 if (mh != null) {
4287                     return mh;
4288                 }
4289             }
4290             MemberName resolved = resolveOrFail(refKind, member);
4291             mh = getDirectMethodForConstant(refKind, defc, resolved);
4292             if (mh instanceof DirectMethodHandle dmh
4293                     && canBeCached(refKind, defc, resolved)) {
4294                 MemberName key = mh.internalMemberName();
4295                 if (key != null) {
4296                     key = key.asNormalOriginal();
4297                 }
4298                 if (member.equals(key)) {  // better safe than sorry
4299                     LOOKASIDE_TABLE.put(key, dmh);
4300                 }
4301             }
4302             return mh;
4303         }
4304         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4305             if (refKind == REF_invokeSpecial) {
4306                 return false;
4307             }
4308             if (!Modifier.isPublic(defc.getModifiers()) ||
4309                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4310                     !member.isPublic() ||
4311                     member.isCallerSensitive()) {
4312                 return false;
4313             }
4314             ClassLoader loader = defc.getClassLoader();
4315             if (loader != null) {
4316                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4317                 boolean found = false;
4318                 while (sysl != null) {
4319                     if (loader == sysl) { found = true; break; }
4320                     sysl = sysl.getParent();
4321                 }
4322                 if (!found) {
4323                     return false;
4324                 }
4325             }
4326             try {
4327                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4328                     new MemberName(refKind, defc, member.getName(), member.getType()));
4329                 if (resolved2 == null) {
4330                     return false;
4331                 }
4332                 checkSecurityManager(defc, resolved2);
4333             } catch (SecurityException ex) {
4334                 return false;
4335             }
4336             return true;
4337         }
4338         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4339                 throws ReflectiveOperationException {
4340             if (MethodHandleNatives.refKindIsField(refKind)) {
4341                 return getDirectFieldNoSecurityManager(refKind, defc, member);
4342             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4343                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
4344             } else if (refKind == REF_newInvokeSpecial) {
4345                 return getDirectConstructorNoSecurityManager(defc, member);
4346             }
4347             // oops
4348             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4349         }
4350 
4351         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4352     }
4353 
4354     /**
4355      * Produces a method handle constructing arrays of a desired type,
4356      * as if by the {@code anewarray} bytecode.
4357      * The return type of the method handle will be the array type.
4358      * The type of its sole argument will be {@code int}, which specifies the size of the array.
4359      *
4360      * <p> If the returned method handle is invoked with a negative
4361      * array size, a {@code NegativeArraySizeException} will be thrown.
4362      *
4363      * @param arrayClass an array type
4364      * @return a method handle which can create arrays of the given type
4365      * @throws NullPointerException if the argument is {@code null}
4366      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4367      * @see java.lang.reflect.Array#newInstance(Class, int)
4368      * @jvms 6.5 {@code anewarray} Instruction
4369      * @since 9
4370      */
4371     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4372         if (!arrayClass.isArray()) {
4373             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4374         }
4375         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4376                 bindTo(arrayClass.getComponentType());
4377         return ani.asType(ani.type().changeReturnType(arrayClass));
4378     }
4379 
4380     /**
4381      * Produces a method handle returning the length of an array,
4382      * as if by the {@code arraylength} bytecode.
4383      * The type of the method handle will have {@code int} as return type,
4384      * and its sole argument will be the array type.
4385      *
4386      * <p> If the returned method handle is invoked with a {@code null}
4387      * array reference, a {@code NullPointerException} will be thrown.
4388      *
4389      * @param arrayClass an array type
4390      * @return a method handle which can retrieve the length of an array of the given array type
4391      * @throws NullPointerException if the argument is {@code null}
4392      * @throws IllegalArgumentException if arrayClass is not an array type
4393      * @jvms 6.5 {@code arraylength} Instruction
4394      * @since 9
4395      */
4396     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4397         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4398     }
4399 
4400     /**
4401      * Produces a method handle giving read access to elements of an array,
4402      * as if by the {@code aaload} bytecode.
4403      * The type of the method handle will have a return type of the array's
4404      * element type.  Its first argument will be the array type,
4405      * and the second will be {@code int}.
4406      *
4407      * <p> When the returned method handle is invoked,
4408      * the array reference and array index are checked.
4409      * A {@code NullPointerException} will be thrown if the array reference
4410      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4411      * thrown if the index is negative or if it is greater than or equal to
4412      * the length of the array.
4413      *
4414      * @param arrayClass an array type
4415      * @return a method handle which can load values from the given array type
4416      * @throws NullPointerException if the argument is null
4417      * @throws  IllegalArgumentException if arrayClass is not an array type
4418      * @jvms 6.5 {@code aaload} Instruction
4419      */
4420     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4421         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4422     }
4423 
4424     /**
4425      * Produces a method handle giving write access to elements of an array,
4426      * as if by the {@code astore} bytecode.
4427      * The type of the method handle will have a void return type.
4428      * Its last argument will be the array's element type.
4429      * The first and second arguments will be the array type and int.
4430      *
4431      * <p> When the returned method handle is invoked,
4432      * the array reference and array index are checked.
4433      * A {@code NullPointerException} will be thrown if the array reference
4434      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4435      * thrown if the index is negative or if it is greater than or equal to
4436      * the length of the array.
4437      *
4438      * @param arrayClass the class of an array
4439      * @return a method handle which can store values into the array type
4440      * @throws NullPointerException if the argument is null
4441      * @throws IllegalArgumentException if arrayClass is not an array type
4442      * @jvms 6.5 {@code aastore} Instruction
4443      */
4444     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4445         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4446     }
4447 
4448     /**
4449      * Produces a VarHandle giving access to elements of an array of type
4450      * {@code arrayClass}.  The VarHandle's variable type is the component type
4451      * of {@code arrayClass} and the list of coordinate types is
4452      * {@code (arrayClass, int)}, where the {@code int} coordinate type
4453      * corresponds to an argument that is an index into an array.
4454      * <p>
4455      * Certain access modes of the returned VarHandle are unsupported under
4456      * the following conditions:
4457      * <ul>
4458      * <li>if the component type is anything other than {@code byte},
4459      *     {@code short}, {@code char}, {@code int}, {@code long},
4460      *     {@code float}, or {@code double} then numeric atomic update access
4461      *     modes are unsupported.
4462      * <li>if the component type is anything other than {@code boolean},
4463      *     {@code byte}, {@code short}, {@code char}, {@code int} or
4464      *     {@code long} then bitwise atomic update access modes are
4465      *     unsupported.
4466      * </ul>
4467      * <p>
4468      * If the component type is {@code float} or {@code double} then numeric
4469      * and atomic update access modes compare values using their bitwise
4470      * representation (see {@link Float#floatToRawIntBits} and
4471      * {@link Double#doubleToRawLongBits}, respectively).
4472      *
4473      * <p> When the returned {@code VarHandle} is invoked,
4474      * the array reference and array index are checked.
4475      * A {@code NullPointerException} will be thrown if the array reference
4476      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4477      * thrown if the index is negative or if it is greater than or equal to
4478      * the length of the array.
4479      *
4480      * @apiNote
4481      * Bitwise comparison of {@code float} values or {@code double} values,
4482      * as performed by the numeric and atomic update access modes, differ
4483      * from the primitive {@code ==} operator and the {@link Float#equals}
4484      * and {@link Double#equals} methods, specifically with respect to
4485      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4486      * Care should be taken when performing a compare and set or a compare
4487      * and exchange operation with such values since the operation may
4488      * unexpectedly fail.
4489      * There are many possible NaN values that are considered to be
4490      * {@code NaN} in Java, although no IEEE 754 floating-point operation
4491      * provided by Java can distinguish between them.  Operation failure can
4492      * occur if the expected or witness value is a NaN value and it is
4493      * transformed (perhaps in a platform specific manner) into another NaN
4494      * value, and thus has a different bitwise representation (see
4495      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4496      * details).
4497      * The values {@code -0.0} and {@code +0.0} have different bitwise
4498      * representations but are considered equal when using the primitive
4499      * {@code ==} operator.  Operation failure can occur if, for example, a
4500      * numeric algorithm computes an expected value to be say {@code -0.0}
4501      * and previously computed the witness value to be say {@code +0.0}.
4502      * @param arrayClass the class of an array, of type {@code T[]}
4503      * @return a VarHandle giving access to elements of an array
4504      * @throws NullPointerException if the arrayClass is null
4505      * @throws IllegalArgumentException if arrayClass is not an array type
4506      * @since 9
4507      */
4508     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4509         return VarHandles.makeArrayElementHandle(arrayClass);
4510     }
4511 
4512     /**
4513      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4514      * viewed as if it were a different primitive array type, such as
4515      * {@code int[]} or {@code long[]}.
4516      * The VarHandle's variable type is the component type of
4517      * {@code viewArrayClass} and the list of coordinate types is
4518      * {@code (byte[], int)}, where the {@code int} coordinate type
4519      * corresponds to an argument that is an index into a {@code byte[]} array.
4520      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4521      * array, composing bytes to or from a value of the component type of
4522      * {@code viewArrayClass} according to the given endianness.
4523      * <p>
4524      * The supported component types (variables types) are {@code short},
4525      * {@code char}, {@code int}, {@code long}, {@code float} and
4526      * {@code double}.
4527      * <p>
4528      * Access of bytes at a given index will result in an
4529      * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4530      * or greater than the {@code byte[]} array length minus the size (in bytes)
4531      * of {@code T}.
4532      * <p>
4533      * Access of bytes at an index may be aligned or misaligned for {@code T},
4534      * with respect to the underlying memory address, {@code A} say, associated
4535      * with the array and index.
4536      * If access is misaligned then access for anything other than the
4537      * {@code get} and {@code set} access modes will result in an
4538      * {@code IllegalStateException}.  In such cases atomic access is only
4539      * guaranteed with respect to the largest power of two that divides the GCD
4540      * of {@code A} and the size (in bytes) of {@code T}.
4541      * If access is aligned then following access modes are supported and are
4542      * guaranteed to support atomic access:
4543      * <ul>
4544      * <li>read write access modes for all {@code T}, with the exception of
4545      *     access modes {@code get} and {@code set} for {@code long} and
4546      *     {@code double} on 32-bit platforms.
4547      * <li>atomic update access modes for {@code int}, {@code long},
4548      *     {@code float} or {@code double}.
4549      *     (Future major platform releases of the JDK may support additional
4550      *     types for certain currently unsupported access modes.)
4551      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4552      *     (Future major platform releases of the JDK may support additional
4553      *     numeric types for certain currently unsupported access modes.)
4554      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4555      *     (Future major platform releases of the JDK may support additional
4556      *     numeric types for certain currently unsupported access modes.)
4557      * </ul>
4558      * <p>
4559      * Misaligned access, and therefore atomicity guarantees, may be determined
4560      * for {@code byte[]} arrays without operating on a specific array.  Given
4561      * an {@code index}, {@code T} and its corresponding boxed type,
4562      * {@code T_BOX}, misalignment may be determined as follows:
4563      * <pre>{@code
4564      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4565      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
4566      *     alignmentOffset(0, sizeOfT);
4567      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
4568      * boolean isMisaligned = misalignedAtIndex != 0;
4569      * }</pre>
4570      * <p>
4571      * If the variable type is {@code float} or {@code double} then atomic
4572      * update access modes compare values using their bitwise representation
4573      * (see {@link Float#floatToRawIntBits} and
4574      * {@link Double#doubleToRawLongBits}, respectively).
4575      * @param viewArrayClass the view array class, with a component type of
4576      * type {@code T}
4577      * @param byteOrder the endianness of the view array elements, as
4578      * stored in the underlying {@code byte} array
4579      * @return a VarHandle giving access to elements of a {@code byte[]} array
4580      * viewed as if elements corresponding to the components type of the view
4581      * array class
4582      * @throws NullPointerException if viewArrayClass or byteOrder is null
4583      * @throws IllegalArgumentException if viewArrayClass is not an array type
4584      * @throws UnsupportedOperationException if the component type of
4585      * viewArrayClass is not supported as a variable type
4586      * @since 9
4587      */
4588     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4589                                      ByteOrder byteOrder) throws IllegalArgumentException {
4590         Objects.requireNonNull(byteOrder);
4591         return VarHandles.byteArrayViewHandle(viewArrayClass,
4592                                               byteOrder == ByteOrder.BIG_ENDIAN);
4593     }
4594 
4595     /**
4596      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4597      * viewed as if it were an array of elements of a different primitive
4598      * component type to that of {@code byte}, such as {@code int[]} or
4599      * {@code long[]}.
4600      * The VarHandle's variable type is the component type of
4601      * {@code viewArrayClass} and the list of coordinate types is
4602      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4603      * corresponds to an argument that is an index into a {@code byte[]} array.
4604      * The returned VarHandle accesses bytes at an index in a
4605      * {@code ByteBuffer}, composing bytes to or from a value of the component
4606      * type of {@code viewArrayClass} according to the given endianness.
4607      * <p>
4608      * The supported component types (variables types) are {@code short},
4609      * {@code char}, {@code int}, {@code long}, {@code float} and
4610      * {@code double}.
4611      * <p>
4612      * Access will result in a {@code ReadOnlyBufferException} for anything
4613      * other than the read access modes if the {@code ByteBuffer} is read-only.
4614      * <p>
4615      * Access of bytes at a given index will result in an
4616      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4617      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4618      * {@code T}.
4619      * <p>
4620      * Access of bytes at an index may be aligned or misaligned for {@code T},
4621      * with respect to the underlying memory address, {@code A} say, associated
4622      * with the {@code ByteBuffer} and index.
4623      * If access is misaligned then access for anything other than the
4624      * {@code get} and {@code set} access modes will result in an
4625      * {@code IllegalStateException}.  In such cases atomic access is only
4626      * guaranteed with respect to the largest power of two that divides the GCD
4627      * of {@code A} and the size (in bytes) of {@code T}.
4628      * If access is aligned then following access modes are supported and are
4629      * guaranteed to support atomic access:
4630      * <ul>
4631      * <li>read write access modes for all {@code T}, with the exception of
4632      *     access modes {@code get} and {@code set} for {@code long} and
4633      *     {@code double} on 32-bit platforms.
4634      * <li>atomic update access modes for {@code int}, {@code long},
4635      *     {@code float} or {@code double}.
4636      *     (Future major platform releases of the JDK may support additional
4637      *     types for certain currently unsupported access modes.)
4638      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4639      *     (Future major platform releases of the JDK may support additional
4640      *     numeric types for certain currently unsupported access modes.)
4641      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4642      *     (Future major platform releases of the JDK may support additional
4643      *     numeric types for certain currently unsupported access modes.)
4644      * </ul>
4645      * <p>
4646      * Misaligned access, and therefore atomicity guarantees, may be determined
4647      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4648      * {@code index}, {@code T} and its corresponding boxed type,
4649      * {@code T_BOX}, as follows:
4650      * <pre>{@code
4651      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4652      * ByteBuffer bb = ...
4653      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4654      * boolean isMisaligned = misalignedAtIndex != 0;
4655      * }</pre>
4656      * <p>
4657      * If the variable type is {@code float} or {@code double} then atomic
4658      * update access modes compare values using their bitwise representation
4659      * (see {@link Float#floatToRawIntBits} and
4660      * {@link Double#doubleToRawLongBits}, respectively).
4661      * @param viewArrayClass the view array class, with a component type of
4662      * type {@code T}
4663      * @param byteOrder the endianness of the view array elements, as
4664      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4665      * endianness of a {@code ByteBuffer})
4666      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4667      * viewed as if elements corresponding to the components type of the view
4668      * array class
4669      * @throws NullPointerException if viewArrayClass or byteOrder is null
4670      * @throws IllegalArgumentException if viewArrayClass is not an array type
4671      * @throws UnsupportedOperationException if the component type of
4672      * viewArrayClass is not supported as a variable type
4673      * @since 9
4674      */
4675     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4676                                       ByteOrder byteOrder) throws IllegalArgumentException {
4677         Objects.requireNonNull(byteOrder);
4678         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4679                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4680     }
4681 
4682 
4683     /// method handle invocation (reflective style)
4684 
4685     /**
4686      * Produces a method handle which will invoke any method handle of the
4687      * given {@code type}, with a given number of trailing arguments replaced by
4688      * a single trailing {@code Object[]} array.
4689      * The resulting invoker will be a method handle with the following
4690      * arguments:
4691      * <ul>
4692      * <li>a single {@code MethodHandle} target
4693      * <li>zero or more leading values (counted by {@code leadingArgCount})
4694      * <li>an {@code Object[]} array containing trailing arguments
4695      * </ul>
4696      * <p>
4697      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4698      * the indicated {@code type}.
4699      * That is, if the target is exactly of the given {@code type}, it will behave
4700      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4701      * is used to convert the target to the required {@code type}.
4702      * <p>
4703      * The type of the returned invoker will not be the given {@code type}, but rather
4704      * will have all parameters except the first {@code leadingArgCount}
4705      * replaced by a single array of type {@code Object[]}, which will be
4706      * the final parameter.
4707      * <p>
4708      * Before invoking its target, the invoker will spread the final array, apply
4709      * reference casts as necessary, and unbox and widen primitive arguments.
4710      * If, when the invoker is called, the supplied array argument does
4711      * not have the correct number of elements, the invoker will throw
4712      * an {@link IllegalArgumentException} instead of invoking the target.
4713      * <p>
4714      * This method is equivalent to the following code (though it may be more efficient):
4715      * {@snippet lang="java" :
4716 MethodHandle invoker = MethodHandles.invoker(type);
4717 int spreadArgCount = type.parameterCount() - leadingArgCount;
4718 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4719 return invoker;
4720      * }
4721      * This method throws no reflective or security exceptions.
4722      * @param type the desired target type
4723      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4724      * @return a method handle suitable for invoking any method handle of the given type
4725      * @throws NullPointerException if {@code type} is null
4726      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4727      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4728      *                  or if the resulting method handle's type would have
4729      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4730      */
4731     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4732         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4733             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4734         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4735         return type.invokers().spreadInvoker(leadingArgCount);
4736     }
4737 
4738     /**
4739      * Produces a special <em>invoker method handle</em> which can be used to
4740      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4741      * The resulting invoker will have a type which is
4742      * exactly equal to the desired type, except that it will accept
4743      * an additional leading argument of type {@code MethodHandle}.
4744      * <p>
4745      * This method is equivalent to the following code (though it may be more efficient):
4746      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4747      *
4748      * <p style="font-size:smaller;">
4749      * <em>Discussion:</em>
4750      * Invoker method handles can be useful when working with variable method handles
4751      * of unknown types.
4752      * For example, to emulate an {@code invokeExact} call to a variable method
4753      * handle {@code M}, extract its type {@code T},
4754      * look up the invoker method {@code X} for {@code T},
4755      * and call the invoker method, as {@code X.invoke(T, A...)}.
4756      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4757      * is unknown.)
4758      * If spreading, collecting, or other argument transformations are required,
4759      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4760      * method handle values, as long as they are compatible with the type of {@code X}.
4761      * <p style="font-size:smaller;">
4762      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4763      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4764      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4765      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4766      * <p>
4767      * This method throws no reflective or security exceptions.
4768      * @param type the desired target type
4769      * @return a method handle suitable for invoking any method handle of the given type
4770      * @throws IllegalArgumentException if the resulting method handle's type would have
4771      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4772      */
4773     public static MethodHandle exactInvoker(MethodType type) {
4774         return type.invokers().exactInvoker();
4775     }
4776 
4777     /**
4778      * Produces a special <em>invoker method handle</em> which can be used to
4779      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4780      * The resulting invoker will have a type which is
4781      * exactly equal to the desired type, except that it will accept
4782      * an additional leading argument of type {@code MethodHandle}.
4783      * <p>
4784      * Before invoking its target, if the target differs from the expected type,
4785      * the invoker will apply reference casts as
4786      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4787      * Similarly, the return value will be converted as necessary.
4788      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4789      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4790      * <p>
4791      * This method is equivalent to the following code (though it may be more efficient):
4792      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4793      * <p style="font-size:smaller;">
4794      * <em>Discussion:</em>
4795      * A {@linkplain MethodType#genericMethodType general method type} is one which
4796      * mentions only {@code Object} arguments and return values.
4797      * An invoker for such a type is capable of calling any method handle
4798      * of the same arity as the general type.
4799      * <p style="font-size:smaller;">
4800      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4801      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4802      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4803      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4804      * <p>
4805      * This method throws no reflective or security exceptions.
4806      * @param type the desired target type
4807      * @return a method handle suitable for invoking any method handle convertible to the given type
4808      * @throws IllegalArgumentException if the resulting method handle's type would have
4809      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4810      */
4811     public static MethodHandle invoker(MethodType type) {
4812         return type.invokers().genericInvoker();
4813     }
4814 
4815     /**
4816      * Produces a special <em>invoker method handle</em> which can be used to
4817      * invoke a signature-polymorphic access mode method on any VarHandle whose
4818      * associated access mode type is compatible with the given type.
4819      * The resulting invoker will have a type which is exactly equal to the
4820      * desired given type, except that it will accept an additional leading
4821      * argument of type {@code VarHandle}.
4822      *
4823      * @param accessMode the VarHandle access mode
4824      * @param type the desired target type
4825      * @return a method handle suitable for invoking an access mode method of
4826      *         any VarHandle whose access mode type is of the given type.
4827      * @since 9
4828      */
4829     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4830         return type.invokers().varHandleMethodExactInvoker(accessMode);
4831     }
4832 
4833     /**
4834      * Produces a special <em>invoker method handle</em> which can be used to
4835      * invoke a signature-polymorphic access mode method on any VarHandle whose
4836      * associated access mode type is compatible with the given type.
4837      * The resulting invoker will have a type which is exactly equal to the
4838      * desired given type, except that it will accept an additional leading
4839      * argument of type {@code VarHandle}.
4840      * <p>
4841      * Before invoking its target, if the access mode type differs from the
4842      * desired given type, the invoker will apply reference casts as necessary
4843      * and box, unbox, or widen primitive values, as if by
4844      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4845      * converted as necessary.
4846      * <p>
4847      * This method is equivalent to the following code (though it may be more
4848      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4849      *
4850      * @param accessMode the VarHandle access mode
4851      * @param type the desired target type
4852      * @return a method handle suitable for invoking an access mode method of
4853      *         any VarHandle whose access mode type is convertible to the given
4854      *         type.
4855      * @since 9
4856      */
4857     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4858         return type.invokers().varHandleMethodInvoker(accessMode);
4859     }
4860 
4861     /*non-public*/
4862     static MethodHandle basicInvoker(MethodType type) {
4863         return type.invokers().basicInvoker();
4864     }
4865 
4866      /// method handle modification (creation from other method handles)
4867 
4868     /**
4869      * Produces a method handle which adapts the type of the
4870      * given method handle to a new type by pairwise argument and return type conversion.
4871      * The original type and new type must have the same number of arguments.
4872      * The resulting method handle is guaranteed to report a type
4873      * which is equal to the desired new type.
4874      * <p>
4875      * If the original type and new type are equal, returns target.
4876      * <p>
4877      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4878      * and some additional conversions are also applied if those conversions fail.
4879      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4880      * if possible, before or instead of any conversions done by {@code asType}:
4881      * <ul>
4882      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4883      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4884      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4885      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4886      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4887      *     (This treatment follows the usage of the bytecode verifier.)
4888      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4889      *     <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}),
4890      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4891      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4892      *     then a Java casting conversion (JLS {@jls 5.5}) is applied.
4893      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4894      *     widening and/or narrowing.)
4895      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4896      *     conversion will be applied at runtime, possibly followed
4897      *     by a Java casting conversion (JLS {@jls 5.5}) on the primitive value,
4898      *     possibly followed by a conversion from byte to boolean by testing
4899      *     the low-order bit.
4900      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4901      *     and if the reference is null at runtime, a zero value is introduced.
4902      * </ul>
4903      * @param target the method handle to invoke after arguments are retyped
4904      * @param newType the expected type of the new method handle
4905      * @return a method handle which delegates to the target after performing
4906      *           any necessary argument conversions, and arranges for any
4907      *           necessary return value conversions
4908      * @throws NullPointerException if either argument is null
4909      * @throws WrongMethodTypeException if the conversion cannot be made
4910      * @see MethodHandle#asType
4911      */
4912     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4913         explicitCastArgumentsChecks(target, newType);
4914         // use the asTypeCache when possible:
4915         MethodType oldType = target.type();
4916         if (oldType == newType)  return target;
4917         if (oldType.explicitCastEquivalentToAsType(newType)) {
4918             return target.asFixedArity().asType(newType);
4919         }
4920         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4921     }
4922 
4923     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4924         if (target.type().parameterCount() != newType.parameterCount()) {
4925             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4926         }
4927     }
4928 
4929     /**
4930      * Produces a method handle which adapts the calling sequence of the
4931      * given method handle to a new type, by reordering the arguments.
4932      * The resulting method handle is guaranteed to report a type
4933      * which is equal to the desired new type.
4934      * <p>
4935      * The given array controls the reordering.
4936      * Call {@code #I} the number of incoming parameters (the value
4937      * {@code newType.parameterCount()}, and call {@code #O} the number
4938      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4939      * Then the length of the reordering array must be {@code #O},
4940      * and each element must be a non-negative number less than {@code #I}.
4941      * For every {@code N} less than {@code #O}, the {@code N}-th
4942      * outgoing argument will be taken from the {@code I}-th incoming
4943      * argument, where {@code I} is {@code reorder[N]}.
4944      * <p>
4945      * No argument or return value conversions are applied.
4946      * The type of each incoming argument, as determined by {@code newType},
4947      * must be identical to the type of the corresponding outgoing parameter
4948      * or parameters in the target method handle.
4949      * The return type of {@code newType} must be identical to the return
4950      * type of the original target.
4951      * <p>
4952      * The reordering array need not specify an actual permutation.
4953      * An incoming argument will be duplicated if its index appears
4954      * more than once in the array, and an incoming argument will be dropped
4955      * if its index does not appear in the array.
4956      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4957      * incoming arguments which are not mentioned in the reordering array
4958      * may be of any type, as determined only by {@code newType}.
4959      * {@snippet lang="java" :
4960 import static java.lang.invoke.MethodHandles.*;
4961 import static java.lang.invoke.MethodType.*;
4962 ...
4963 MethodType intfn1 = methodType(int.class, int.class);
4964 MethodType intfn2 = methodType(int.class, int.class, int.class);
4965 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4966 assert(sub.type().equals(intfn2));
4967 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4968 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4969 assert((int)rsub.invokeExact(1, 100) == 99);
4970 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4971 assert(add.type().equals(intfn2));
4972 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4973 assert(twice.type().equals(intfn1));
4974 assert((int)twice.invokeExact(21) == 42);
4975      * }
4976      * <p>
4977      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4978      * variable-arity method handle}, even if the original target method handle was.
4979      * @param target the method handle to invoke after arguments are reordered
4980      * @param newType the expected type of the new method handle
4981      * @param reorder an index array which controls the reordering
4982      * @return a method handle which delegates to the target after it
4983      *           drops unused arguments and moves and/or duplicates the other arguments
4984      * @throws NullPointerException if any argument is null
4985      * @throws IllegalArgumentException if the index array length is not equal to
4986      *                  the arity of the target, or if any index array element
4987      *                  not a valid index for a parameter of {@code newType},
4988      *                  or if two corresponding parameter types in
4989      *                  {@code target.type()} and {@code newType} are not identical,
4990      */
4991     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4992         reorder = reorder.clone();  // get a private copy
4993         MethodType oldType = target.type();
4994         permuteArgumentChecks(reorder, newType, oldType);
4995         // first detect dropped arguments and handle them separately
4996         int[] originalReorder = reorder;
4997         BoundMethodHandle result = target.rebind();
4998         LambdaForm form = result.form;
4999         int newArity = newType.parameterCount();
5000         // Normalize the reordering into a real permutation,
5001         // by removing duplicates and adding dropped elements.
5002         // This somewhat improves lambda form caching, as well
5003         // as simplifying the transform by breaking it up into steps.
5004         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
5005             if (ddIdx > 0) {
5006                 // We found a duplicated entry at reorder[ddIdx].
5007                 // Example:  (x,y,z)->asList(x,y,z)
5008                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
5009                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
5010                 // The starred element corresponds to the argument
5011                 // deleted by the dupArgumentForm transform.
5012                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
5013                 boolean killFirst = false;
5014                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
5015                     // Set killFirst if the dup is larger than an intervening position.
5016                     // This will remove at least one inversion from the permutation.
5017                     if (dupVal > val) killFirst = true;
5018                 }
5019                 if (!killFirst) {
5020                     srcPos = dstPos;
5021                     dstPos = ddIdx;
5022                 }
5023                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
5024                 assert (reorder[srcPos] == reorder[dstPos]);
5025                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
5026                 // contract the reordering by removing the element at dstPos
5027                 int tailPos = dstPos + 1;
5028                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
5029                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
5030             } else {
5031                 int dropVal = ~ddIdx, insPos = 0;
5032                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
5033                     // Find first element of reorder larger than dropVal.
5034                     // This is where we will insert the dropVal.
5035                     insPos += 1;
5036                 }
5037                 Class<?> ptype = newType.parameterType(dropVal);
5038                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
5039                 oldType = oldType.insertParameterTypes(insPos, ptype);
5040                 // expand the reordering by inserting an element at insPos
5041                 int tailPos = insPos + 1;
5042                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
5043                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
5044                 reorder[insPos] = dropVal;
5045             }
5046             assert (permuteArgumentChecks(reorder, newType, oldType));
5047         }
5048         assert (reorder.length == newArity);  // a perfect permutation
5049         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
5050         form = form.editor().permuteArgumentsForm(1, reorder);
5051         if (newType == result.type() && form == result.internalForm())
5052             return result;
5053         return result.copyWith(newType, form);
5054     }
5055 
5056     /**
5057      * Return an indication of any duplicate or omission in reorder.
5058      * If the reorder contains a duplicate entry, return the index of the second occurrence.
5059      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
5060      * Otherwise, return zero.
5061      * If an element not in [0..newArity-1] is encountered, return reorder.length.
5062      */
5063     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
5064         final int BIT_LIMIT = 63;  // max number of bits in bit mask
5065         if (newArity < BIT_LIMIT) {
5066             long mask = 0;
5067             for (int i = 0; i < reorder.length; i++) {
5068                 int arg = reorder[i];
5069                 if (arg >= newArity) {
5070                     return reorder.length;
5071                 }
5072                 long bit = 1L << arg;
5073                 if ((mask & bit) != 0) {
5074                     return i;  // >0 indicates a dup
5075                 }
5076                 mask |= bit;
5077             }
5078             if (mask == (1L << newArity) - 1) {
5079                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
5080                 return 0;
5081             }
5082             // find first zero
5083             long zeroBit = Long.lowestOneBit(~mask);
5084             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
5085             assert(zeroPos <= newArity);
5086             if (zeroPos == newArity) {
5087                 return 0;
5088             }
5089             return ~zeroPos;
5090         } else {
5091             // same algorithm, different bit set
5092             BitSet mask = new BitSet(newArity);
5093             for (int i = 0; i < reorder.length; i++) {
5094                 int arg = reorder[i];
5095                 if (arg >= newArity) {
5096                     return reorder.length;
5097                 }
5098                 if (mask.get(arg)) {
5099                     return i;  // >0 indicates a dup
5100                 }
5101                 mask.set(arg);
5102             }
5103             int zeroPos = mask.nextClearBit(0);
5104             assert(zeroPos <= newArity);
5105             if (zeroPos == newArity) {
5106                 return 0;
5107             }
5108             return ~zeroPos;
5109         }
5110     }
5111 
5112     static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
5113         if (newType.returnType() != oldType.returnType())
5114             throw newIllegalArgumentException("return types do not match",
5115                     oldType, newType);
5116         if (reorder.length != oldType.parameterCount())
5117             throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
5118                     oldType, Arrays.toString(reorder));
5119 
5120         int limit = newType.parameterCount();
5121         for (int j = 0; j < reorder.length; j++) {
5122             int i = reorder[j];
5123             if (i < 0 || i >= limit) {
5124                 throw newIllegalArgumentException("index is out of bounds for new type",
5125                         i, newType);
5126             }
5127             Class<?> src = newType.parameterType(i);
5128             Class<?> dst = oldType.parameterType(j);
5129             if (src != dst)
5130                 throw newIllegalArgumentException("parameter types do not match after reorder",
5131                         oldType, newType);
5132         }
5133         return true;
5134     }
5135 
5136     /**
5137      * Produces a method handle of the requested return type which returns the given
5138      * constant value every time it is invoked.
5139      * <p>
5140      * Before the method handle is returned, the passed-in value is converted to the requested type.
5141      * If the requested type is primitive, widening primitive conversions are attempted,
5142      * else reference conversions are attempted.
5143      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5144      * @param type the return type of the desired method handle
5145      * @param value the value to return
5146      * @return a method handle of the given return type and no arguments, which always returns the given value
5147      * @throws NullPointerException if the {@code type} argument is null
5148      * @throws ClassCastException if the value cannot be converted to the required return type
5149      * @throws IllegalArgumentException if the given type is {@code void.class}
5150      */
5151     public static MethodHandle constant(Class<?> type, Object value) {
5152         if (type.isPrimitive()) {
5153             if (type == void.class)
5154                 throw newIllegalArgumentException("void type");
5155             Wrapper w = Wrapper.forPrimitiveType(type);
5156             value = w.convert(value, type);
5157             if (w.zero().equals(value))
5158                 return zero(w, type);
5159             return insertArguments(identity(type), 0, value);
5160         } else {
5161             if (!PrimitiveClass.isPrimitiveValueType(type) && value == null)
5162                 return zero(Wrapper.OBJECT, type);
5163             return identity(type).bindTo(value);
5164         }
5165     }
5166 
5167     /**
5168      * Produces a method handle which returns its sole argument when invoked.
5169      * @param type the type of the sole parameter and return value of the desired method handle
5170      * @return a unary method handle which accepts and returns the given type
5171      * @throws NullPointerException if the argument is null
5172      * @throws IllegalArgumentException if the given type is {@code void.class}
5173      */
5174     public static MethodHandle identity(Class<?> type) {
5175         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5176         int pos = btw.ordinal();
5177         MethodHandle ident = IDENTITY_MHS[pos];
5178         if (ident == null) {
5179             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5180         }
5181         if (ident.type().returnType() == type)
5182             return ident;
5183         // something like identity(Foo.class); do not bother to intern these
5184         assert (btw == Wrapper.OBJECT);
5185         return makeIdentity(type);
5186     }
5187 
5188     /**
5189      * Produces a constant method handle of the requested return type which
5190      * returns the default value for that type every time it is invoked.
5191      * The resulting constant method handle will have no side effects.
5192      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5193      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5194      * since {@code explicitCastArguments} converts {@code null} to default values.
5195      * @param type the expected return type of the desired method handle
5196      * @return a constant method handle that takes no arguments
5197      *         and returns the default value of the given type (or void, if the type is void)
5198      * @throws NullPointerException if the argument is null
5199      * @see MethodHandles#constant
5200      * @see MethodHandles#empty
5201      * @see MethodHandles#explicitCastArguments
5202      * @since 9
5203      */
5204     public static MethodHandle zero(Class<?> type) {
5205         Objects.requireNonNull(type);
5206         if (type.isPrimitive()) {
5207             return zero(Wrapper.forPrimitiveType(type), type);
5208         } else if (PrimitiveClass.isPrimitiveValueType(type)) {
5209             // singleton default value
5210             Object value = UNSAFE.uninitializedDefaultValue(type);
5211             return identity(type).bindTo(value);
5212         } else {
5213             return zero(Wrapper.OBJECT, type);
5214         }
5215     }
5216 
5217     private static MethodHandle identityOrVoid(Class<?> type) {
5218         return type == void.class ? zero(type) : identity(type);
5219     }
5220 
5221     /**
5222      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5223      * and returns a suitable default depending on the return type.
5224      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
5225      * <p>The returned method handle is equivalent to
5226      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5227      *
5228      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5229      * {@code guardWithTest(pred, target, empty(target.type())}.
5230      * @param type the type of the desired method handle
5231      * @return a constant method handle of the given type, which returns a default value of the given return type
5232      * @throws NullPointerException if the argument is null
5233      * @see MethodHandles#zero
5234      * @see MethodHandles#constant
5235      * @since 9
5236      */
5237     public static  MethodHandle empty(MethodType type) {
5238         Objects.requireNonNull(type);
5239         return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes());
5240     }
5241 
5242     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5243     private static MethodHandle makeIdentity(Class<?> ptype) {
5244         MethodType mtype = MethodType.methodType(ptype, ptype);
5245         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5246         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5247     }
5248 
5249     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5250         int pos = btw.ordinal();
5251         MethodHandle zero = ZERO_MHS[pos];
5252         if (zero == null) {
5253             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5254         }
5255         if (zero.type().returnType() == rtype)
5256             return zero;
5257         assert(btw == Wrapper.OBJECT);
5258         return makeZero(rtype);
5259     }
5260     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5261     private static MethodHandle makeZero(Class<?> rtype) {
5262         MethodType mtype = methodType(rtype);
5263         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5264         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
5265     }
5266 
5267     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
5268         // Simulate a CAS, to avoid racy duplication of results.
5269         MethodHandle prev = cache[pos];
5270         if (prev != null) return prev;
5271         return cache[pos] = value;
5272     }
5273 
5274     /**
5275      * Provides a target method handle with one or more <em>bound arguments</em>
5276      * in advance of the method handle's invocation.
5277      * The formal parameters to the target corresponding to the bound
5278      * arguments are called <em>bound parameters</em>.
5279      * Returns a new method handle which saves away the bound arguments.
5280      * When it is invoked, it receives arguments for any non-bound parameters,
5281      * binds the saved arguments to their corresponding parameters,
5282      * and calls the original target.
5283      * <p>
5284      * The type of the new method handle will drop the types for the bound
5285      * parameters from the original target type, since the new method handle
5286      * will no longer require those arguments to be supplied by its callers.
5287      * <p>
5288      * Each given argument object must match the corresponding bound parameter type.
5289      * If a bound parameter type is a primitive, the argument object
5290      * must be a wrapper, and will be unboxed to produce the primitive value.
5291      * <p>
5292      * The {@code pos} argument selects which parameters are to be bound.
5293      * It may range between zero and <i>N-L</i> (inclusively),
5294      * where <i>N</i> is the arity of the target method handle
5295      * and <i>L</i> is the length of the values array.
5296      * <p>
5297      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5298      * variable-arity method handle}, even if the original target method handle was.
5299      * @param target the method handle to invoke after the argument is inserted
5300      * @param pos where to insert the argument (zero for the first)
5301      * @param values the series of arguments to insert
5302      * @return a method handle which inserts an additional argument,
5303      *         before calling the original method handle
5304      * @throws NullPointerException if the target or the {@code values} array is null
5305      * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than
5306      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
5307      *         is the length of the values array.
5308      * @throws ClassCastException if an argument does not match the corresponding bound parameter
5309      *         type.
5310      * @see MethodHandle#bindTo
5311      */
5312     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
5313         int insCount = values.length;
5314         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
5315         if (insCount == 0)  return target;
5316         BoundMethodHandle result = target.rebind();
5317         for (int i = 0; i < insCount; i++) {
5318             Object value = values[i];
5319             Class<?> ptype = ptypes[pos+i];
5320             if (ptype.isPrimitive()) {
5321                 result = insertArgumentPrimitive(result, pos, ptype, value);
5322             } else {
5323                 value = ptype.cast(value);  // throw CCE if needed
5324                 result = result.bindArgumentL(pos, value);
5325             }
5326         }
5327         return result;
5328     }
5329 
5330     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5331                                                              Class<?> ptype, Object value) {
5332         Wrapper w = Wrapper.forPrimitiveType(ptype);
5333         // perform unboxing and/or primitive conversion
5334         value = w.convert(value, ptype);
5335         return switch (w) {
5336             case INT    -> result.bindArgumentI(pos, (int) value);
5337             case LONG   -> result.bindArgumentJ(pos, (long) value);
5338             case FLOAT  -> result.bindArgumentF(pos, (float) value);
5339             case DOUBLE -> result.bindArgumentD(pos, (double) value);
5340             default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5341         };
5342     }
5343 
5344     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5345         MethodType oldType = target.type();
5346         int outargs = oldType.parameterCount();
5347         int inargs  = outargs - insCount;
5348         if (inargs < 0)
5349             throw newIllegalArgumentException("too many values to insert");
5350         if (pos < 0 || pos > inargs)
5351             throw newIllegalArgumentException("no argument type to append");
5352         return oldType.ptypes();
5353     }
5354 
5355     /**
5356      * Produces a method handle which will discard some dummy arguments
5357      * before calling some other specified <i>target</i> method handle.
5358      * The type of the new method handle will be the same as the target's type,
5359      * except it will also include the dummy argument types,
5360      * at some given position.
5361      * <p>
5362      * The {@code pos} argument may range between zero and <i>N</i>,
5363      * where <i>N</i> is the arity of the target.
5364      * If {@code pos} is zero, the dummy arguments will precede
5365      * the target's real arguments; if {@code pos} is <i>N</i>
5366      * they will come after.
5367      * <p>
5368      * <b>Example:</b>
5369      * {@snippet lang="java" :
5370 import static java.lang.invoke.MethodHandles.*;
5371 import static java.lang.invoke.MethodType.*;
5372 ...
5373 MethodHandle cat = lookup().findVirtual(String.class,
5374   "concat", methodType(String.class, String.class));
5375 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5376 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5377 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5378 assertEquals(bigType, d0.type());
5379 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5380      * }
5381      * <p>
5382      * This method is also equivalent to the following code:
5383      * <blockquote><pre>
5384      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5385      * </pre></blockquote>
5386      * @param target the method handle to invoke after the arguments are dropped
5387      * @param pos position of first argument to drop (zero for the leftmost)
5388      * @param valueTypes the type(s) of the argument(s) to drop
5389      * @return a method handle which drops arguments of the given types,
5390      *         before calling the original method handle
5391      * @throws NullPointerException if the target is null,
5392      *                              or if the {@code valueTypes} list or any of its elements is null
5393      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5394      *                  or if {@code pos} is negative or greater than the arity of the target,
5395      *                  or if the new method handle's type would have too many parameters
5396      */
5397     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5398         return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone());
5399     }
5400 
5401     static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) {
5402         MethodType oldType = target.type();  // get NPE
5403         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5404         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5405         if (dropped == 0)  return target;
5406         BoundMethodHandle result = target.rebind();
5407         LambdaForm lform = result.form;
5408         int insertFormArg = 1 + pos;
5409         for (Class<?> ptype : valueTypes) {
5410             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5411         }
5412         result = result.copyWith(newType, lform);
5413         return result;
5414     }
5415 
5416     private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) {
5417         int dropped = valueTypes.length;
5418         MethodType.checkSlotCount(dropped);
5419         int outargs = oldType.parameterCount();
5420         int inargs  = outargs + dropped;
5421         if (pos < 0 || pos > outargs)
5422             throw newIllegalArgumentException("no argument type to remove"
5423                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5424                     );
5425         return dropped;
5426     }
5427 
5428     /**
5429      * Produces a method handle which will discard some dummy arguments
5430      * before calling some other specified <i>target</i> method handle.
5431      * The type of the new method handle will be the same as the target's type,
5432      * except it will also include the dummy argument types,
5433      * at some given position.
5434      * <p>
5435      * The {@code pos} argument may range between zero and <i>N</i>,
5436      * where <i>N</i> is the arity of the target.
5437      * If {@code pos} is zero, the dummy arguments will precede
5438      * the target's real arguments; if {@code pos} is <i>N</i>
5439      * they will come after.
5440      * @apiNote
5441      * {@snippet lang="java" :
5442 import static java.lang.invoke.MethodHandles.*;
5443 import static java.lang.invoke.MethodType.*;
5444 ...
5445 MethodHandle cat = lookup().findVirtual(String.class,
5446   "concat", methodType(String.class, String.class));
5447 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5448 MethodHandle d0 = dropArguments(cat, 0, String.class);
5449 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5450 MethodHandle d1 = dropArguments(cat, 1, String.class);
5451 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5452 MethodHandle d2 = dropArguments(cat, 2, String.class);
5453 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5454 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5455 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5456      * }
5457      * <p>
5458      * This method is also equivalent to the following code:
5459      * <blockquote><pre>
5460      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5461      * </pre></blockquote>
5462      * @param target the method handle to invoke after the arguments are dropped
5463      * @param pos position of first argument to drop (zero for the leftmost)
5464      * @param valueTypes the type(s) of the argument(s) to drop
5465      * @return a method handle which drops arguments of the given types,
5466      *         before calling the original method handle
5467      * @throws NullPointerException if the target is null,
5468      *                              or if the {@code valueTypes} array or any of its elements is null
5469      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5470      *                  or if {@code pos} is negative or greater than the arity of the target,
5471      *                  or if the new method handle's type would have
5472      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
5473      */
5474     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5475         return dropArgumentsTrusted(target, pos, valueTypes.clone());
5476     }
5477 
5478     /* Convenience overloads for trusting internal low-arity call-sites */
5479     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) {
5480         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 });
5481     }
5482     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) {
5483         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 });
5484     }
5485 
5486     // private version which allows caller some freedom with error handling
5487     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos,
5488                                       boolean nullOnFailure) {
5489         Class<?>[] oldTypes = target.type().ptypes();
5490         int match = oldTypes.length;
5491         if (skip != 0) {
5492             if (skip < 0 || skip > match) {
5493                 throw newIllegalArgumentException("illegal skip", skip, target);
5494             }
5495             oldTypes = Arrays.copyOfRange(oldTypes, skip, match);
5496             match -= skip;
5497         }
5498         Class<?>[] addTypes = newTypes;
5499         int add = addTypes.length;
5500         if (pos != 0) {
5501             if (pos < 0 || pos > add) {
5502                 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes));
5503             }
5504             addTypes = Arrays.copyOfRange(addTypes, pos, add);
5505             add -= pos;
5506             assert(addTypes.length == add);
5507         }
5508         // Do not add types which already match the existing arguments.
5509         if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) {
5510             if (nullOnFailure) {
5511                 return null;
5512             }
5513             throw newIllegalArgumentException("argument lists do not match",
5514                 Arrays.toString(oldTypes), Arrays.toString(newTypes));
5515         }
5516         addTypes = Arrays.copyOfRange(addTypes, match, add);
5517         add -= match;
5518         assert(addTypes.length == add);
5519         // newTypes:     (   P*[pos], M*[match], A*[add] )
5520         // target: ( S*[skip],        M*[match]  )
5521         MethodHandle adapter = target;
5522         if (add > 0) {
5523             adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes);
5524         }
5525         // adapter: (S*[skip],        M*[match], A*[add] )
5526         if (pos > 0) {
5527             adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos));
5528         }
5529         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5530         return adapter;
5531     }
5532 
5533     /**
5534      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5535      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5536      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5537      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5538      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5539      * {@link #dropArguments(MethodHandle, int, Class[])}.
5540      * <p>
5541      * The resulting handle will have the same return type as the target handle.
5542      * <p>
5543      * In more formal terms, assume these two type lists:<ul>
5544      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5545      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5546      * {@code newTypes}.
5547      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5548      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5549      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5550      * sub-list.
5551      * </ul>
5552      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5553      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5554      * {@link #dropArguments(MethodHandle, int, Class[])}.
5555      *
5556      * @apiNote
5557      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5558      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5559      * {@snippet lang="java" :
5560 import static java.lang.invoke.MethodHandles.*;
5561 import static java.lang.invoke.MethodType.*;
5562 ...
5563 ...
5564 MethodHandle h0 = constant(boolean.class, true);
5565 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5566 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5567 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5568 if (h1.type().parameterCount() < h2.type().parameterCount())
5569     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5570 else
5571     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5572 MethodHandle h3 = guardWithTest(h0, h1, h2);
5573 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5574      * }
5575      * @param target the method handle to adapt
5576      * @param skip number of targets parameters to disregard (they will be unchanged)
5577      * @param newTypes the list of types to match {@code target}'s parameter type list to
5578      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5579      * @return a possibly adapted method handle
5580      * @throws NullPointerException if either argument is null
5581      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5582      *         or if {@code skip} is negative or greater than the arity of the target,
5583      *         or if {@code pos} is negative or greater than the newTypes list size,
5584      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5585      *         {@code pos}.
5586      * @since 9
5587      */
5588     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5589         Objects.requireNonNull(target);
5590         Objects.requireNonNull(newTypes);
5591         return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false);
5592     }
5593 
5594     /**
5595      * Drop the return value of the target handle (if any).
5596      * The returned method handle will have a {@code void} return type.
5597      *
5598      * @param target the method handle to adapt
5599      * @return a possibly adapted method handle
5600      * @throws NullPointerException if {@code target} is null
5601      * @since 16
5602      */
5603     public static MethodHandle dropReturn(MethodHandle target) {
5604         Objects.requireNonNull(target);
5605         MethodType oldType = target.type();
5606         Class<?> oldReturnType = oldType.returnType();
5607         if (oldReturnType == void.class)
5608             return target;
5609         MethodType newType = oldType.changeReturnType(void.class);
5610         BoundMethodHandle result = target.rebind();
5611         LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5612         result = result.copyWith(newType, lform);
5613         return result;
5614     }
5615 
5616     /**
5617      * Adapts a target method handle by pre-processing
5618      * one or more of its arguments, each with its own unary filter function,
5619      * and then calling the target with each pre-processed argument
5620      * replaced by the result of its corresponding filter function.
5621      * <p>
5622      * The pre-processing is performed by one or more method handles,
5623      * specified in the elements of the {@code filters} array.
5624      * The first element of the filter array corresponds to the {@code pos}
5625      * argument of the target, and so on in sequence.
5626      * The filter functions are invoked in left to right order.
5627      * <p>
5628      * Null arguments in the array are treated as identity functions,
5629      * and the corresponding arguments left unchanged.
5630      * (If there are no non-null elements in the array, the original target is returned.)
5631      * Each filter is applied to the corresponding argument of the adapter.
5632      * <p>
5633      * If a filter {@code F} applies to the {@code N}th argument of
5634      * the target, then {@code F} must be a method handle which
5635      * takes exactly one argument.  The type of {@code F}'s sole argument
5636      * replaces the corresponding argument type of the target
5637      * in the resulting adapted method handle.
5638      * The return type of {@code F} must be identical to the corresponding
5639      * parameter type of the target.
5640      * <p>
5641      * It is an error if there are elements of {@code filters}
5642      * (null or not)
5643      * which do not correspond to argument positions in the target.
5644      * <p><b>Example:</b>
5645      * {@snippet lang="java" :
5646 import static java.lang.invoke.MethodHandles.*;
5647 import static java.lang.invoke.MethodType.*;
5648 ...
5649 MethodHandle cat = lookup().findVirtual(String.class,
5650   "concat", methodType(String.class, String.class));
5651 MethodHandle upcase = lookup().findVirtual(String.class,
5652   "toUpperCase", methodType(String.class));
5653 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5654 MethodHandle f0 = filterArguments(cat, 0, upcase);
5655 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5656 MethodHandle f1 = filterArguments(cat, 1, upcase);
5657 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5658 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5659 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5660      * }
5661      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5662      * denotes the return type of both the {@code target} and resulting adapter.
5663      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5664      * of the parameters and arguments that precede and follow the filter position
5665      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5666      * values of the filtered parameters and arguments; they also represent the
5667      * return types of the {@code filter[i]} handles. The latter accept arguments
5668      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5669      * the resulting adapter.
5670      * {@snippet lang="java" :
5671      * T target(P... p, A[i]... a[i], B... b);
5672      * A[i] filter[i](V[i]);
5673      * T adapter(P... p, V[i]... v[i], B... b) {
5674      *   return target(p..., filter[i](v[i])..., b...);
5675      * }
5676      * }
5677      * <p>
5678      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5679      * variable-arity method handle}, even if the original target method handle was.
5680      *
5681      * @param target the method handle to invoke after arguments are filtered
5682      * @param pos the position of the first argument to filter
5683      * @param filters method handles to call initially on filtered arguments
5684      * @return method handle which incorporates the specified argument filtering logic
5685      * @throws NullPointerException if the target is null
5686      *                              or if the {@code filters} array is null
5687      * @throws IllegalArgumentException if a non-null element of {@code filters}
5688      *          does not match a corresponding argument type of target as described above,
5689      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5690      *          or if the resulting method handle's type would have
5691      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5692      */
5693     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5694         // In method types arguments start at index 0, while the LF
5695         // editor have the MH receiver at position 0 - adjust appropriately.
5696         final int MH_RECEIVER_OFFSET = 1;
5697         filterArgumentsCheckArity(target, pos, filters);
5698         MethodHandle adapter = target;
5699 
5700         // keep track of currently matched filters, as to optimize repeated filters
5701         int index = 0;
5702         int[] positions = new int[filters.length];
5703         MethodHandle filter = null;
5704 
5705         // process filters in reverse order so that the invocation of
5706         // the resulting adapter will invoke the filters in left-to-right order
5707         for (int i = filters.length - 1; i >= 0; --i) {
5708             MethodHandle newFilter = filters[i];
5709             if (newFilter == null) continue;  // ignore null elements of filters
5710 
5711             // flush changes on update
5712             if (filter != newFilter) {
5713                 if (filter != null) {
5714                     if (index > 1) {
5715                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5716                     } else {
5717                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5718                     }
5719                 }
5720                 filter = newFilter;
5721                 index = 0;
5722             }
5723 
5724             filterArgumentChecks(target, pos + i, newFilter);
5725             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5726         }
5727         if (index > 1) {
5728             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5729         } else if (index == 1) {
5730             adapter = filterArgument(adapter, positions[0] - 1, filter);
5731         }
5732         return adapter;
5733     }
5734 
5735     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5736         MethodType targetType = adapter.type();
5737         MethodType filterType = filter.type();
5738         BoundMethodHandle result = adapter.rebind();
5739         Class<?> newParamType = filterType.parameterType(0);
5740 
5741         Class<?>[] ptypes = targetType.ptypes().clone();
5742         for (int pos : positions) {
5743             ptypes[pos - 1] = newParamType;
5744         }
5745         MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true);
5746 
5747         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5748         return result.copyWithExtendL(newType, lform, filter);
5749     }
5750 
5751     /*non-public*/
5752     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5753         filterArgumentChecks(target, pos, filter);
5754         MethodType targetType = target.type();
5755         MethodType filterType = filter.type();
5756         BoundMethodHandle result = target.rebind();
5757         Class<?> newParamType = filterType.parameterType(0);
5758         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5759         MethodType newType = targetType.changeParameterType(pos, newParamType);
5760         result = result.copyWithExtendL(newType, lform, filter);
5761         return result;
5762     }
5763 
5764     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5765         MethodType targetType = target.type();
5766         int maxPos = targetType.parameterCount();
5767         if (pos + filters.length > maxPos)
5768             throw newIllegalArgumentException("too many filters");
5769     }
5770 
5771     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5772         MethodType targetType = target.type();
5773         MethodType filterType = filter.type();
5774         if (filterType.parameterCount() != 1
5775             || filterType.returnType() != targetType.parameterType(pos))
5776             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5777     }
5778 
5779     /**
5780      * Adapts a target method handle by pre-processing
5781      * a sub-sequence of its arguments with a filter (another method handle).
5782      * The pre-processed arguments are replaced by the result (if any) of the
5783      * filter function.
5784      * The target is then called on the modified (usually shortened) argument list.
5785      * <p>
5786      * If the filter returns a value, the target must accept that value as
5787      * its argument in position {@code pos}, preceded and/or followed by
5788      * any arguments not passed to the filter.
5789      * If the filter returns void, the target must accept all arguments
5790      * not passed to the filter.
5791      * No arguments are reordered, and a result returned from the filter
5792      * replaces (in order) the whole subsequence of arguments originally
5793      * passed to the adapter.
5794      * <p>
5795      * The argument types (if any) of the filter
5796      * replace zero or one argument types of the target, at position {@code pos},
5797      * in the resulting adapted method handle.
5798      * The return type of the filter (if any) must be identical to the
5799      * argument type of the target at position {@code pos}, and that target argument
5800      * is supplied by the return value of the filter.
5801      * <p>
5802      * In all cases, {@code pos} must be greater than or equal to zero, and
5803      * {@code pos} must also be less than or equal to the target's arity.
5804      * <p><b>Example:</b>
5805      * {@snippet lang="java" :
5806 import static java.lang.invoke.MethodHandles.*;
5807 import static java.lang.invoke.MethodType.*;
5808 ...
5809 MethodHandle deepToString = publicLookup()
5810   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5811 
5812 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5813 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5814 
5815 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5816 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5817 
5818 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5819 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5820 assertEquals("[top, [up, down], strange]",
5821              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5822 
5823 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5824 assertEquals("[top, [up, down], [strange]]",
5825              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5826 
5827 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5828 assertEquals("[top, [[up, down, strange], charm], bottom]",
5829              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5830      * }
5831      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5832      * represents the return type of the {@code target} and resulting adapter.
5833      * {@code V}/{@code v} stand for the return type and value of the
5834      * {@code filter}, which are also found in the signature and arguments of
5835      * the {@code target}, respectively, unless {@code V} is {@code void}.
5836      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5837      * and values preceding and following the collection position, {@code pos},
5838      * in the {@code target}'s signature. They also turn up in the resulting
5839      * adapter's signature and arguments, where they surround
5840      * {@code B}/{@code b}, which represent the parameter types and arguments
5841      * to the {@code filter} (if any).
5842      * {@snippet lang="java" :
5843      * T target(A...,V,C...);
5844      * V filter(B...);
5845      * T adapter(A... a,B... b,C... c) {
5846      *   V v = filter(b...);
5847      *   return target(a...,v,c...);
5848      * }
5849      * // and if the filter has no arguments:
5850      * T target2(A...,V,C...);
5851      * V filter2();
5852      * T adapter2(A... a,C... c) {
5853      *   V v = filter2();
5854      *   return target2(a...,v,c...);
5855      * }
5856      * // and if the filter has a void return:
5857      * T target3(A...,C...);
5858      * void filter3(B...);
5859      * T adapter3(A... a,B... b,C... c) {
5860      *   filter3(b...);
5861      *   return target3(a...,c...);
5862      * }
5863      * }
5864      * <p>
5865      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5866      * one which first "folds" the affected arguments, and then drops them, in separate
5867      * steps as follows:
5868      * {@snippet lang="java" :
5869      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5870      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5871      * }
5872      * If the target method handle consumes no arguments besides than the result
5873      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5874      * is equivalent to {@code filterReturnValue(coll, mh)}.
5875      * If the filter method handle {@code coll} consumes one argument and produces
5876      * a non-void result, then {@code collectArguments(mh, N, coll)}
5877      * is equivalent to {@code filterArguments(mh, N, coll)}.
5878      * Other equivalences are possible but would require argument permutation.
5879      * <p>
5880      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5881      * variable-arity method handle}, even if the original target method handle was.
5882      *
5883      * @param target the method handle to invoke after filtering the subsequence of arguments
5884      * @param pos the position of the first adapter argument to pass to the filter,
5885      *            and/or the target argument which receives the result of the filter
5886      * @param filter method handle to call on the subsequence of arguments
5887      * @return method handle which incorporates the specified argument subsequence filtering logic
5888      * @throws NullPointerException if either argument is null
5889      * @throws IllegalArgumentException if the return type of {@code filter}
5890      *          is non-void and is not the same as the {@code pos} argument of the target,
5891      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5892      *          or if the resulting method handle's type would have
5893      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5894      * @see MethodHandles#foldArguments
5895      * @see MethodHandles#filterArguments
5896      * @see MethodHandles#filterReturnValue
5897      */
5898     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5899         MethodType newType = collectArgumentsChecks(target, pos, filter);
5900         MethodType collectorType = filter.type();
5901         BoundMethodHandle result = target.rebind();
5902         LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5903         return result.copyWithExtendL(newType, lform, filter);
5904     }
5905 
5906     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5907         MethodType targetType = target.type();
5908         MethodType filterType = filter.type();
5909         Class<?> rtype = filterType.returnType();
5910         Class<?>[] filterArgs = filterType.ptypes();
5911         if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5912                        (rtype != void.class && pos >= targetType.parameterCount())) {
5913             throw newIllegalArgumentException("position is out of range for target", target, pos);
5914         }
5915         if (rtype == void.class) {
5916             return targetType.insertParameterTypes(pos, filterArgs);
5917         }
5918         if (rtype != targetType.parameterType(pos)) {
5919             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5920         }
5921         return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs);
5922     }
5923 
5924     /**
5925      * Adapts a target method handle by post-processing
5926      * its return value (if any) with a filter (another method handle).
5927      * The result of the filter is returned from the adapter.
5928      * <p>
5929      * If the target returns a value, the filter must accept that value as
5930      * its only argument.
5931      * If the target returns void, the filter must accept no arguments.
5932      * <p>
5933      * The return type of the filter
5934      * replaces the return type of the target
5935      * in the resulting adapted method handle.
5936      * The argument type of the filter (if any) must be identical to the
5937      * return type of the target.
5938      * <p><b>Example:</b>
5939      * {@snippet lang="java" :
5940 import static java.lang.invoke.MethodHandles.*;
5941 import static java.lang.invoke.MethodType.*;
5942 ...
5943 MethodHandle cat = lookup().findVirtual(String.class,
5944   "concat", methodType(String.class, String.class));
5945 MethodHandle length = lookup().findVirtual(String.class,
5946   "length", methodType(int.class));
5947 System.out.println((String) cat.invokeExact("x", "y")); // xy
5948 MethodHandle f0 = filterReturnValue(cat, length);
5949 System.out.println((int) f0.invokeExact("x", "y")); // 2
5950      * }
5951      * <p>Here is pseudocode for the resulting adapter. In the code,
5952      * {@code T}/{@code t} represent the result type and value of the
5953      * {@code target}; {@code V}, the result type of the {@code filter}; and
5954      * {@code A}/{@code a}, the types and values of the parameters and arguments
5955      * of the {@code target} as well as the resulting adapter.
5956      * {@snippet lang="java" :
5957      * T target(A...);
5958      * V filter(T);
5959      * V adapter(A... a) {
5960      *   T t = target(a...);
5961      *   return filter(t);
5962      * }
5963      * // and if the target has a void return:
5964      * void target2(A...);
5965      * V filter2();
5966      * V adapter2(A... a) {
5967      *   target2(a...);
5968      *   return filter2();
5969      * }
5970      * // and if the filter has a void return:
5971      * T target3(A...);
5972      * void filter3(V);
5973      * void adapter3(A... a) {
5974      *   T t = target3(a...);
5975      *   filter3(t);
5976      * }
5977      * }
5978      * <p>
5979      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5980      * variable-arity method handle}, even if the original target method handle was.
5981      * @param target the method handle to invoke before filtering the return value
5982      * @param filter method handle to call on the return value
5983      * @return method handle which incorporates the specified return value filtering logic
5984      * @throws NullPointerException if either argument is null
5985      * @throws IllegalArgumentException if the argument list of {@code filter}
5986      *          does not match the return type of target as described above
5987      */
5988     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5989         MethodType targetType = target.type();
5990         MethodType filterType = filter.type();
5991         filterReturnValueChecks(targetType, filterType);
5992         BoundMethodHandle result = target.rebind();
5993         BasicType rtype = BasicType.basicType(filterType.returnType());
5994         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5995         MethodType newType = targetType.changeReturnType(filterType.returnType());
5996         result = result.copyWithExtendL(newType, lform, filter);
5997         return result;
5998     }
5999 
6000     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
6001         Class<?> rtype = targetType.returnType();
6002         int filterValues = filterType.parameterCount();
6003         if (filterValues == 0
6004                 ? (rtype != void.class)
6005                 : (rtype != filterType.parameterType(0) || filterValues != 1))
6006             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
6007     }
6008 
6009     /**
6010      * Filter the return value of a target method handle with a filter function. The filter function is
6011      * applied to the return value of the original handle; if the filter specifies more than one parameters,
6012      * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
6013      * as follows:
6014      * {@snippet lang="java" :
6015      * T target(A...)
6016      * V filter(B... , T)
6017      * V adapter(A... a, B... b) {
6018      *     T t = target(a...);
6019      *     return filter(b..., t);
6020      * }
6021      * }
6022      * <p>
6023      * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
6024      *
6025      * @param target the target method handle
6026      * @param filter the filter method handle
6027      * @return the adapter method handle
6028      */
6029     /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
6030         MethodType targetType = target.type();
6031         MethodType filterType = filter.type();
6032         BoundMethodHandle result = target.rebind();
6033         LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
6034         MethodType newType = targetType.changeReturnType(filterType.returnType());
6035         if (filterType.parameterCount() > 1) {
6036             for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
6037                 newType = newType.appendParameterTypes(filterType.parameterType(i));
6038             }
6039         }
6040         result = result.copyWithExtendL(newType, lform, filter);
6041         return result;
6042     }
6043 
6044     /**
6045      * Adapts a target method handle by pre-processing
6046      * some of its arguments, and then calling the target with
6047      * the result of the pre-processing, inserted into the original
6048      * sequence of arguments.
6049      * <p>
6050      * The pre-processing is performed by {@code combiner}, a second method handle.
6051      * Of the arguments passed to the adapter, the first {@code N} arguments
6052      * are copied to the combiner, which is then called.
6053      * (Here, {@code N} is defined as the parameter count of the combiner.)
6054      * After this, control passes to the target, with any result
6055      * from the combiner inserted before the original {@code N} incoming
6056      * arguments.
6057      * <p>
6058      * If the combiner returns a value, the first parameter type of the target
6059      * must be identical with the return type of the combiner, and the next
6060      * {@code N} parameter types of the target must exactly match the parameters
6061      * of the combiner.
6062      * <p>
6063      * If the combiner has a void return, no result will be inserted,
6064      * and the first {@code N} parameter types of the target
6065      * must exactly match the parameters of the combiner.
6066      * <p>
6067      * The resulting adapter is the same type as the target, except that the
6068      * first parameter type is dropped,
6069      * if it corresponds to the result of the combiner.
6070      * <p>
6071      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
6072      * that either the combiner or the target does not wish to receive.
6073      * If some of the incoming arguments are destined only for the combiner,
6074      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
6075      * arguments will not need to be live on the stack on entry to the
6076      * target.)
6077      * <p><b>Example:</b>
6078      * {@snippet lang="java" :
6079 import static java.lang.invoke.MethodHandles.*;
6080 import static java.lang.invoke.MethodType.*;
6081 ...
6082 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6083   "println", methodType(void.class, String.class))
6084     .bindTo(System.out);
6085 MethodHandle cat = lookup().findVirtual(String.class,
6086   "concat", methodType(String.class, String.class));
6087 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6088 MethodHandle catTrace = foldArguments(cat, trace);
6089 // also prints "boo":
6090 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6091      * }
6092      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6093      * represents the result type of the {@code target} and resulting adapter.
6094      * {@code V}/{@code v} represent the type and value of the parameter and argument
6095      * of {@code target} that precedes the folding position; {@code V} also is
6096      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6097      * types and values of the {@code N} parameters and arguments at the folding
6098      * position. {@code B}/{@code b} represent the types and values of the
6099      * {@code target} parameters and arguments that follow the folded parameters
6100      * and arguments.
6101      * {@snippet lang="java" :
6102      * // there are N arguments in A...
6103      * T target(V, A[N]..., B...);
6104      * V combiner(A...);
6105      * T adapter(A... a, B... b) {
6106      *   V v = combiner(a...);
6107      *   return target(v, a..., b...);
6108      * }
6109      * // and if the combiner has a void return:
6110      * T target2(A[N]..., B...);
6111      * void combiner2(A...);
6112      * T adapter2(A... a, B... b) {
6113      *   combiner2(a...);
6114      *   return target2(a..., b...);
6115      * }
6116      * }
6117      * <p>
6118      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6119      * variable-arity method handle}, even if the original target method handle was.
6120      * @param target the method handle to invoke after arguments are combined
6121      * @param combiner method handle to call initially on the incoming arguments
6122      * @return method handle which incorporates the specified argument folding logic
6123      * @throws NullPointerException if either argument is null
6124      * @throws IllegalArgumentException if {@code combiner}'s return type
6125      *          is non-void and not the same as the first argument type of
6126      *          the target, or if the initial {@code N} argument types
6127      *          of the target
6128      *          (skipping one matching the {@code combiner}'s return type)
6129      *          are not identical with the argument types of {@code combiner}
6130      */
6131     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
6132         return foldArguments(target, 0, combiner);
6133     }
6134 
6135     /**
6136      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
6137      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
6138      * before the folded arguments.
6139      * <p>
6140      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
6141      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
6142      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
6143      * 0.
6144      *
6145      * @apiNote Example:
6146      * {@snippet lang="java" :
6147     import static java.lang.invoke.MethodHandles.*;
6148     import static java.lang.invoke.MethodType.*;
6149     ...
6150     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6151     "println", methodType(void.class, String.class))
6152     .bindTo(System.out);
6153     MethodHandle cat = lookup().findVirtual(String.class,
6154     "concat", methodType(String.class, String.class));
6155     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6156     MethodHandle catTrace = foldArguments(cat, 1, trace);
6157     // also prints "jum":
6158     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6159      * }
6160      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6161      * represents the result type of the {@code target} and resulting adapter.
6162      * {@code V}/{@code v} represent the type and value of the parameter and argument
6163      * of {@code target} that precedes the folding position; {@code V} also is
6164      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6165      * types and values of the {@code N} parameters and arguments at the folding
6166      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
6167      * and values of the {@code target} parameters and arguments that precede and
6168      * follow the folded parameters and arguments starting at {@code pos},
6169      * respectively.
6170      * {@snippet lang="java" :
6171      * // there are N arguments in A...
6172      * T target(Z..., V, A[N]..., B...);
6173      * V combiner(A...);
6174      * T adapter(Z... z, A... a, B... b) {
6175      *   V v = combiner(a...);
6176      *   return target(z..., v, a..., b...);
6177      * }
6178      * // and if the combiner has a void return:
6179      * T target2(Z..., A[N]..., B...);
6180      * void combiner2(A...);
6181      * T adapter2(Z... z, A... a, B... b) {
6182      *   combiner2(a...);
6183      *   return target2(z..., a..., b...);
6184      * }
6185      * }
6186      * <p>
6187      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6188      * variable-arity method handle}, even if the original target method handle was.
6189      *
6190      * @param target the method handle to invoke after arguments are combined
6191      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
6192      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6193      * @param combiner method handle to call initially on the incoming arguments
6194      * @return method handle which incorporates the specified argument folding logic
6195      * @throws NullPointerException if either argument is null
6196      * @throws IllegalArgumentException if either of the following two conditions holds:
6197      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6198      *              {@code pos} of the target signature;
6199      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
6200      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
6201      *
6202      * @see #foldArguments(MethodHandle, MethodHandle)
6203      * @since 9
6204      */
6205     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
6206         MethodType targetType = target.type();
6207         MethodType combinerType = combiner.type();
6208         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
6209         BoundMethodHandle result = target.rebind();
6210         boolean dropResult = rtype == void.class;
6211         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
6212         MethodType newType = targetType;
6213         if (!dropResult) {
6214             newType = newType.dropParameterTypes(pos, pos + 1);
6215         }
6216         result = result.copyWithExtendL(newType, lform, combiner);
6217         return result;
6218     }
6219 
6220     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
6221         int foldArgs   = combinerType.parameterCount();
6222         Class<?> rtype = combinerType.returnType();
6223         int foldVals = rtype == void.class ? 0 : 1;
6224         int afterInsertPos = foldPos + foldVals;
6225         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
6226         if (ok) {
6227             for (int i = 0; i < foldArgs; i++) {
6228                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
6229                     ok = false;
6230                     break;
6231                 }
6232             }
6233         }
6234         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
6235             ok = false;
6236         if (!ok)
6237             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6238         return rtype;
6239     }
6240 
6241     /**
6242      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
6243      * of the pre-processing replacing the argument at the given position.
6244      *
6245      * @param target the method handle to invoke after arguments are combined
6246      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6247      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6248      * @param combiner method handle to call initially on the incoming arguments
6249      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6250      * @return method handle which incorporates the specified argument folding logic
6251      * @throws NullPointerException if either argument is null
6252      * @throws IllegalArgumentException if either of the following two conditions holds:
6253      *          (1) {@code combiner}'s return type is not the same as the argument type at position
6254      *              {@code pos} of the target signature;
6255      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
6256      *              not identical with the argument types of {@code combiner}.
6257      */
6258     /*non-public*/
6259     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6260         return argumentsWithCombiner(true, target, position, combiner, argPositions);
6261     }
6262 
6263     /**
6264      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
6265      * the pre-processing inserted into the original sequence of arguments at the given position.
6266      *
6267      * @param target the method handle to invoke after arguments are combined
6268      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6269      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6270      * @param combiner method handle to call initially on the incoming arguments
6271      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6272      * @return method handle which incorporates the specified argument folding logic
6273      * @throws NullPointerException if either argument is null
6274      * @throws IllegalArgumentException if either of the following two conditions holds:
6275      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6276      *              {@code pos} of the target signature;
6277      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
6278      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
6279      *              with the argument types of {@code combiner}.
6280      */
6281     /*non-public*/
6282     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6283         return argumentsWithCombiner(false, target, position, combiner, argPositions);
6284     }
6285 
6286     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6287         MethodType targetType = target.type();
6288         MethodType combinerType = combiner.type();
6289         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
6290         BoundMethodHandle result = target.rebind();
6291 
6292         MethodType newType = targetType;
6293         LambdaForm lform;
6294         if (filter) {
6295             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
6296         } else {
6297             boolean dropResult = rtype == void.class;
6298             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
6299             if (!dropResult) {
6300                 newType = newType.dropParameterTypes(position, position + 1);
6301             }
6302         }
6303         result = result.copyWithExtendL(newType, lform, combiner);
6304         return result;
6305     }
6306 
6307     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
6308         int combinerArgs = combinerType.parameterCount();
6309         if (argPos.length != combinerArgs) {
6310             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
6311         }
6312         Class<?> rtype = combinerType.returnType();
6313 
6314         for (int i = 0; i < combinerArgs; i++) {
6315             int arg = argPos[i];
6316             if (arg < 0 || arg > targetType.parameterCount()) {
6317                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
6318             }
6319             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
6320                 throw newIllegalArgumentException("target argument type at position " + arg
6321                         + " must match combiner argument type at index " + i + ": " + targetType
6322                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6323             }
6324         }
6325         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6326             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6327         }
6328         return rtype;
6329     }
6330 
6331     /**
6332      * Makes a method handle which adapts a target method handle,
6333      * by guarding it with a test, a boolean-valued method handle.
6334      * If the guard fails, a fallback handle is called instead.
6335      * All three method handles must have the same corresponding
6336      * argument and return types, except that the return type
6337      * of the test must be boolean, and the test is allowed
6338      * to have fewer arguments than the other two method handles.
6339      * <p>
6340      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6341      * represents the uniform result type of the three involved handles;
6342      * {@code A}/{@code a}, the types and values of the {@code target}
6343      * parameters and arguments that are consumed by the {@code test}; and
6344      * {@code B}/{@code b}, those types and values of the {@code target}
6345      * parameters and arguments that are not consumed by the {@code test}.
6346      * {@snippet lang="java" :
6347      * boolean test(A...);
6348      * T target(A...,B...);
6349      * T fallback(A...,B...);
6350      * T adapter(A... a,B... b) {
6351      *   if (test(a...))
6352      *     return target(a..., b...);
6353      *   else
6354      *     return fallback(a..., b...);
6355      * }
6356      * }
6357      * Note that the test arguments ({@code a...} in the pseudocode) cannot
6358      * be modified by execution of the test, and so are passed unchanged
6359      * from the caller to the target or fallback as appropriate.
6360      * @param test method handle used for test, must return boolean
6361      * @param target method handle to call if test passes
6362      * @param fallback method handle to call if test fails
6363      * @return method handle which incorporates the specified if/then/else logic
6364      * @throws NullPointerException if any argument is null
6365      * @throws IllegalArgumentException if {@code test} does not return boolean,
6366      *          or if all three method types do not match (with the return
6367      *          type of {@code test} changed to match that of the target).
6368      */
6369     public static MethodHandle guardWithTest(MethodHandle test,
6370                                MethodHandle target,
6371                                MethodHandle fallback) {
6372         MethodType gtype = test.type();
6373         MethodType ttype = target.type();
6374         MethodType ftype = fallback.type();
6375         if (!ttype.equals(ftype))
6376             throw misMatchedTypes("target and fallback types", ttype, ftype);
6377         if (gtype.returnType() != boolean.class)
6378             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6379 
6380         test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true);
6381         if (test == null) {
6382             throw misMatchedTypes("target and test types", ttype, gtype);
6383         }
6384         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6385     }
6386 
6387     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6388         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6389     }
6390 
6391     /**
6392      * Makes a method handle which adapts a target method handle,
6393      * by running it inside an exception handler.
6394      * If the target returns normally, the adapter returns that value.
6395      * If an exception matching the specified type is thrown, the fallback
6396      * handle is called instead on the exception, plus the original arguments.
6397      * <p>
6398      * The target and handler must have the same corresponding
6399      * argument and return types, except that handler may omit trailing arguments
6400      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6401      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6402      * <p>
6403      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6404      * represents the return type of the {@code target} and {@code handler},
6405      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6406      * the types and values of arguments to the resulting handle consumed by
6407      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6408      * resulting handle discarded by {@code handler}.
6409      * {@snippet lang="java" :
6410      * T target(A..., B...);
6411      * T handler(ExType, A...);
6412      * T adapter(A... a, B... b) {
6413      *   try {
6414      *     return target(a..., b...);
6415      *   } catch (ExType ex) {
6416      *     return handler(ex, a...);
6417      *   }
6418      * }
6419      * }
6420      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6421      * be modified by execution of the target, and so are passed unchanged
6422      * from the caller to the handler, if the handler is invoked.
6423      * <p>
6424      * The target and handler must return the same type, even if the handler
6425      * always throws.  (This might happen, for instance, because the handler
6426      * is simulating a {@code finally} clause).
6427      * To create such a throwing handler, compose the handler creation logic
6428      * with {@link #throwException throwException},
6429      * in order to create a method handle of the correct return type.
6430      * @param target method handle to call
6431      * @param exType the type of exception which the handler will catch
6432      * @param handler method handle to call if a matching exception is thrown
6433      * @return method handle which incorporates the specified try/catch logic
6434      * @throws NullPointerException if any argument is null
6435      * @throws IllegalArgumentException if {@code handler} does not accept
6436      *          the given exception type, or if the method handle types do
6437      *          not match in their return types and their
6438      *          corresponding parameters
6439      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6440      */
6441     public static MethodHandle catchException(MethodHandle target,
6442                                 Class<? extends Throwable> exType,
6443                                 MethodHandle handler) {
6444         MethodType ttype = target.type();
6445         MethodType htype = handler.type();
6446         if (!Throwable.class.isAssignableFrom(exType))
6447             throw new ClassCastException(exType.getName());
6448         if (htype.parameterCount() < 1 ||
6449             !htype.parameterType(0).isAssignableFrom(exType))
6450             throw newIllegalArgumentException("handler does not accept exception type "+exType);
6451         if (htype.returnType() != ttype.returnType())
6452             throw misMatchedTypes("target and handler return types", ttype, htype);
6453         handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true);
6454         if (handler == null) {
6455             throw misMatchedTypes("target and handler types", ttype, htype);
6456         }
6457         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6458     }
6459 
6460     /**
6461      * Produces a method handle which will throw exceptions of the given {@code exType}.
6462      * The method handle will accept a single argument of {@code exType},
6463      * and immediately throw it as an exception.
6464      * The method type will nominally specify a return of {@code returnType}.
6465      * The return type may be anything convenient:  It doesn't matter to the
6466      * method handle's behavior, since it will never return normally.
6467      * @param returnType the return type of the desired method handle
6468      * @param exType the parameter type of the desired method handle
6469      * @return method handle which can throw the given exceptions
6470      * @throws NullPointerException if either argument is null
6471      */
6472     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6473         if (!Throwable.class.isAssignableFrom(exType))
6474             throw new ClassCastException(exType.getName());
6475         return MethodHandleImpl.throwException(methodType(returnType, exType));
6476     }
6477 
6478     /**
6479      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6480      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6481      * delivers the loop's result, which is the return value of the resulting handle.
6482      * <p>
6483      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6484      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6485      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6486      * terms of method handles, each clause will specify up to four independent actions:<ul>
6487      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6488      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6489      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6490      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6491      * </ul>
6492      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6493      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
6494      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6495      * <p>
6496      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6497      * this case. See below for a detailed description.
6498      * <p>
6499      * <em>Parameters optional everywhere:</em>
6500      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6501      * As an exception, the init functions cannot take any {@code v} parameters,
6502      * because those values are not yet computed when the init functions are executed.
6503      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6504      * In fact, any clause function may take no arguments at all.
6505      * <p>
6506      * <em>Loop parameters:</em>
6507      * A clause function may take all the iteration variable values it is entitled to, in which case
6508      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6509      * with their types and values notated as {@code (A...)} and {@code (a...)}.
6510      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6511      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6512      * init function is automatically a loop parameter {@code a}.)
6513      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6514      * These loop parameters act as loop-invariant values visible across the whole loop.
6515      * <p>
6516      * <em>Parameters visible everywhere:</em>
6517      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6518      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6519      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6520      * Most clause functions will not need all of this information, but they will be formally connected to it
6521      * as if by {@link #dropArguments}.
6522      * <a id="astar"></a>
6523      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6524      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6525      * In that notation, the general form of an init function parameter list
6526      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6527      * <p>
6528      * <em>Checking clause structure:</em>
6529      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6530      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6531      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6532      * met by the inputs to the loop combinator.
6533      * <p>
6534      * <em>Effectively identical sequences:</em>
6535      * <a id="effid"></a>
6536      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6537      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6538      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6539      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6540      * that longest list.
6541      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6542      * and the same is true if more sequences of the form {@code (V... A*)} are added.
6543      * <p>
6544      * <em>Step 0: Determine clause structure.</em><ol type="a">
6545      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6546      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6547      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6548      * four. Padding takes place by appending elements to the array.
6549      * <li>Clauses with all {@code null}s are disregarded.
6550      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6551      * </ol>
6552      * <p>
6553      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6554      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6555      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6556      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6557      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6558      * iteration variable type.
6559      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6560      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6561      * </ol>
6562      * <p>
6563      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6564      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6565      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6566      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6567      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6568      * (These types will be checked in step 2, along with all the clause function types.)
6569      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6570      * <li>All of the collected parameter lists must be effectively identical.
6571      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6572      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6573      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6574      * the "internal parameter list".
6575      * </ul>
6576      * <p>
6577      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6578      * <li>Examine fini function return types, disregarding omitted fini functions.
6579      * <li>If there are no fini functions, the loop return type is {@code void}.
6580      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6581      * type.
6582      * </ol>
6583      * <p>
6584      * <em>Step 1D: Check other types.</em><ol type="a">
6585      * <li>There must be at least one non-omitted pred function.
6586      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6587      * </ol>
6588      * <p>
6589      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6590      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6591      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6592      * (Note that their parameter lists are already effectively identical to this list.)
6593      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6594      * effectively identical to the internal parameter list {@code (V... A...)}.
6595      * </ol>
6596      * <p>
6597      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6598      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6599      * type.
6600      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6601      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6602      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6603      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6604      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6605      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6606      * loop return type.
6607      * </ol>
6608      * <p>
6609      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6610      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6611      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6612      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6613      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6614      * pad out the end of the list.
6615      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6616      * </ol>
6617      * <p>
6618      * <em>Final observations.</em><ol type="a">
6619      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6620      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6621      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6622      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6623      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6624      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6625      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6626      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6627      * </ol>
6628      * <p>
6629      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6630      * <ul>
6631      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6632      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6633      * (Only one {@code Pn} has to be non-{@code null}.)
6634      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6635      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6636      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6637      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6638      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6639      * the resulting loop handle's parameter types {@code (A...)}.
6640      * </ul>
6641      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6642      * which is natural if most of the loop computation happens in the steps.  For some loops,
6643      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6644      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6645      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6646      * where the init functions will need the extra parameters.  For such reasons, the rules for
6647      * determining these parameters are as symmetric as possible, across all clause parts.
6648      * In general, the loop parameters function as common invariant values across the whole
6649      * loop, while the iteration variables function as common variant values, or (if there is
6650      * no step function) as internal loop invariant temporaries.
6651      * <p>
6652      * <em>Loop execution.</em><ol type="a">
6653      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6654      * every clause function. These locals are loop invariant.
6655      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6656      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6657      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6658      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6659      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6660      * (in argument order).
6661      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6662      * returns {@code false}.
6663      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6664      * sequence {@code (v...)} of loop variables.
6665      * The updated value is immediately visible to all subsequent function calls.
6666      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6667      * (of type {@code R}) is returned from the loop as a whole.
6668      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6669      * except by throwing an exception.
6670      * </ol>
6671      * <p>
6672      * <em>Usage tips.</em>
6673      * <ul>
6674      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6675      * sometimes a step function only needs to observe the current value of its own variable.
6676      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6677      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6678      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6679      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6680      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6681      * <li>If some of the clause functions are virtual methods on an instance, the instance
6682      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6683      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6684      * will be the first iteration variable value, and it will be easy to use virtual
6685      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6686      * </ul>
6687      * <p>
6688      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6689      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6690      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6691      * {@snippet lang="java" :
6692      * V... init...(A...);
6693      * boolean pred...(V..., A...);
6694      * V... step...(V..., A...);
6695      * R fini...(V..., A...);
6696      * R loop(A... a) {
6697      *   V... v... = init...(a...);
6698      *   for (;;) {
6699      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6700      *       v = s(v..., a...);
6701      *       if (!p(v..., a...)) {
6702      *         return f(v..., a...);
6703      *       }
6704      *     }
6705      *   }
6706      * }
6707      * }
6708      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6709      * to their full length, even though individual clause functions may neglect to take them all.
6710      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6711      *
6712      * @apiNote Example:
6713      * {@snippet lang="java" :
6714      * // iterative implementation of the factorial function as a loop handle
6715      * static int one(int k) { return 1; }
6716      * static int inc(int i, int acc, int k) { return i + 1; }
6717      * static int mult(int i, int acc, int k) { return i * acc; }
6718      * static boolean pred(int i, int acc, int k) { return i < k; }
6719      * static int fin(int i, int acc, int k) { return acc; }
6720      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6721      * // null initializer for counter, should initialize to 0
6722      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6723      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6724      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6725      * assertEquals(120, loop.invoke(5));
6726      * }
6727      * The same example, dropping arguments and using combinators:
6728      * {@snippet lang="java" :
6729      * // simplified implementation of the factorial function as a loop handle
6730      * static int inc(int i) { return i + 1; } // drop acc, k
6731      * static int mult(int i, int acc) { return i * acc; } //drop k
6732      * static boolean cmp(int i, int k) { return i < k; }
6733      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6734      * // null initializer for counter, should initialize to 0
6735      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6736      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6737      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6738      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6739      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6740      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6741      * assertEquals(720, loop.invoke(6));
6742      * }
6743      * A similar example, using a helper object to hold a loop parameter:
6744      * {@snippet lang="java" :
6745      * // instance-based implementation of the factorial function as a loop handle
6746      * static class FacLoop {
6747      *   final int k;
6748      *   FacLoop(int k) { this.k = k; }
6749      *   int inc(int i) { return i + 1; }
6750      *   int mult(int i, int acc) { return i * acc; }
6751      *   boolean pred(int i) { return i < k; }
6752      *   int fin(int i, int acc) { return acc; }
6753      * }
6754      * // assume MH_FacLoop is a handle to the constructor
6755      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6756      * // null initializer for counter, should initialize to 0
6757      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6758      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6759      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6760      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6761      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6762      * assertEquals(5040, loop.invoke(7));
6763      * }
6764      *
6765      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6766      *
6767      * @return a method handle embodying the looping behavior as defined by the arguments.
6768      *
6769      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6770      *
6771      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6772      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6773      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6774      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6775      * @since 9
6776      */
6777     public static MethodHandle loop(MethodHandle[]... clauses) {
6778         // Step 0: determine clause structure.
6779         loopChecks0(clauses);
6780 
6781         List<MethodHandle> init = new ArrayList<>();
6782         List<MethodHandle> step = new ArrayList<>();
6783         List<MethodHandle> pred = new ArrayList<>();
6784         List<MethodHandle> fini = new ArrayList<>();
6785 
6786         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6787             init.add(clause[0]); // all clauses have at least length 1
6788             step.add(clause.length <= 1 ? null : clause[1]);
6789             pred.add(clause.length <= 2 ? null : clause[2]);
6790             fini.add(clause.length <= 3 ? null : clause[3]);
6791         });
6792 
6793         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6794         final int nclauses = init.size();
6795 
6796         // Step 1A: determine iteration variables (V...).
6797         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6798         for (int i = 0; i < nclauses; ++i) {
6799             MethodHandle in = init.get(i);
6800             MethodHandle st = step.get(i);
6801             if (in == null && st == null) {
6802                 iterationVariableTypes.add(void.class);
6803             } else if (in != null && st != null) {
6804                 loopChecks1a(i, in, st);
6805                 iterationVariableTypes.add(in.type().returnType());
6806             } else {
6807                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6808             }
6809         }
6810         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6811 
6812         // Step 1B: determine loop parameters (A...).
6813         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6814         loopChecks1b(init, commonSuffix);
6815 
6816         // Step 1C: determine loop return type.
6817         // Step 1D: check other types.
6818         // local variable required here; see JDK-8223553
6819         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6820                 .map(MethodType::returnType);
6821         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6822         loopChecks1cd(pred, fini, loopReturnType);
6823 
6824         // Step 2: determine parameter lists.
6825         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6826         commonParameterSequence.addAll(commonSuffix);
6827         loopChecks2(step, pred, fini, commonParameterSequence);
6828         // Step 3: fill in omitted functions.
6829         for (int i = 0; i < nclauses; ++i) {
6830             Class<?> t = iterationVariableTypes.get(i);
6831             if (init.get(i) == null) {
6832                 init.set(i, empty(methodType(t, commonSuffix)));
6833             }
6834             if (step.get(i) == null) {
6835                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6836             }
6837             if (pred.get(i) == null) {
6838                 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
6839             }
6840             if (fini.get(i) == null) {
6841                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6842             }
6843         }
6844 
6845         // Step 4: fill in missing parameter types.
6846         // Also convert all handles to fixed-arity handles.
6847         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6848         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6849         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6850         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6851 
6852         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6853                 allMatch(pl -> pl.equals(commonSuffix));
6854         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6855                 allMatch(pl -> pl.equals(commonParameterSequence));
6856 
6857         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6858     }
6859 
6860     private static void loopChecks0(MethodHandle[][] clauses) {
6861         if (clauses == null || clauses.length == 0) {
6862             throw newIllegalArgumentException("null or no clauses passed");
6863         }
6864         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6865             throw newIllegalArgumentException("null clauses are not allowed");
6866         }
6867         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6868             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6869         }
6870     }
6871 
6872     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6873         if (in.type().returnType() != st.type().returnType()) {
6874             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6875                     st.type().returnType());
6876         }
6877     }
6878 
6879     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6880         return mhs.filter(Objects::nonNull)
6881                 // take only those that can contribute to a common suffix because they are longer than the prefix
6882                 .map(MethodHandle::type)
6883                 .filter(t -> t.parameterCount() > skipSize)
6884                 .max(Comparator.comparingInt(MethodType::parameterCount))
6885                 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount())))
6886                 .orElse(List.of());
6887     }
6888 
6889     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6890         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6891         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6892         return longest1.size() >= longest2.size() ? longest1 : longest2;
6893     }
6894 
6895     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6896         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6897                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6898             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6899                     " (common suffix: " + commonSuffix + ")");
6900         }
6901     }
6902 
6903     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6904         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6905                 anyMatch(t -> t != loopReturnType)) {
6906             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6907                     loopReturnType + ")");
6908         }
6909 
6910         if (pred.stream().noneMatch(Objects::nonNull)) {
6911             throw newIllegalArgumentException("no predicate found", pred);
6912         }
6913         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6914                 anyMatch(t -> t != boolean.class)) {
6915             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6916         }
6917     }
6918 
6919     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6920         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6921                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6922             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6923                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6924         }
6925     }
6926 
6927     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6928         return hs.stream().map(h -> {
6929             int pc = h.type().parameterCount();
6930             int tpsize = targetParams.size();
6931             return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
6932         }).toList();
6933     }
6934 
6935     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6936         return hs.stream().map(MethodHandle::asFixedArity).toList();
6937     }
6938 
6939     /**
6940      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6941      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6942      * <p>
6943      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6944      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6945      * evaluates to {@code true}).
6946      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6947      * <p>
6948      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6949      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6950      * and updated with the value returned from its invocation. The result of loop execution will be
6951      * the final value of the additional loop-local variable (if present).
6952      * <p>
6953      * The following rules hold for these argument handles:<ul>
6954      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6955      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6956      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6957      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6958      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6959      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6960      * It will constrain the parameter lists of the other loop parts.
6961      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6962      * list {@code (A...)} is called the <em>external parameter list</em>.
6963      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6964      * additional state variable of the loop.
6965      * The body must both accept and return a value of this type {@code V}.
6966      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6967      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6968      * <a href="MethodHandles.html#effid">effectively identical</a>
6969      * to the external parameter list {@code (A...)}.
6970      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6971      * {@linkplain #empty default value}.
6972      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6973      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6974      * effectively identical to the internal parameter list.
6975      * </ul>
6976      * <p>
6977      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6978      * <li>The loop handle's result type is the result type {@code V} of the body.
6979      * <li>The loop handle's parameter types are the types {@code (A...)},
6980      * from the external parameter list.
6981      * </ul>
6982      * <p>
6983      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6984      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6985      * passed to the loop.
6986      * {@snippet lang="java" :
6987      * V init(A...);
6988      * boolean pred(V, A...);
6989      * V body(V, A...);
6990      * V whileLoop(A... a...) {
6991      *   V v = init(a...);
6992      *   while (pred(v, a...)) {
6993      *     v = body(v, a...);
6994      *   }
6995      *   return v;
6996      * }
6997      * }
6998      *
6999      * @apiNote Example:
7000      * {@snippet lang="java" :
7001      * // implement the zip function for lists as a loop handle
7002      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
7003      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
7004      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
7005      *   zip.add(a.next());
7006      *   zip.add(b.next());
7007      *   return zip;
7008      * }
7009      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
7010      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
7011      * List<String> a = Arrays.asList("a", "b", "c", "d");
7012      * List<String> b = Arrays.asList("e", "f", "g", "h");
7013      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
7014      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
7015      * }
7016      *
7017      *
7018      * @apiNote The implementation of this method can be expressed as follows:
7019      * {@snippet lang="java" :
7020      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
7021      *     MethodHandle fini = (body.type().returnType() == void.class
7022      *                         ? null : identity(body.type().returnType()));
7023      *     MethodHandle[]
7024      *         checkExit = { null, null, pred, fini },
7025      *         varBody   = { init, body };
7026      *     return loop(checkExit, varBody);
7027      * }
7028      * }
7029      *
7030      * @param init optional initializer, providing the initial value of the loop variable.
7031      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7032      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7033      *             above for other constraints.
7034      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7035      *             See above for other constraints.
7036      *
7037      * @return a method handle implementing the {@code while} loop as described by the arguments.
7038      * @throws IllegalArgumentException if the rules for the arguments are violated.
7039      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7040      *
7041      * @see #loop(MethodHandle[][])
7042      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
7043      * @since 9
7044      */
7045     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
7046         whileLoopChecks(init, pred, body);
7047         MethodHandle fini = identityOrVoid(body.type().returnType());
7048         MethodHandle[] checkExit = { null, null, pred, fini };
7049         MethodHandle[] varBody = { init, body };
7050         return loop(checkExit, varBody);
7051     }
7052 
7053     /**
7054      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
7055      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7056      * <p>
7057      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
7058      * method will, in each iteration, first execute its body and then evaluate the predicate.
7059      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
7060      * <p>
7061      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
7062      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
7063      * and updated with the value returned from its invocation. The result of loop execution will be
7064      * the final value of the additional loop-local variable (if present).
7065      * <p>
7066      * The following rules hold for these argument handles:<ul>
7067      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7068      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
7069      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7070      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
7071      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
7072      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
7073      * It will constrain the parameter lists of the other loop parts.
7074      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
7075      * list {@code (A...)} is called the <em>external parameter list</em>.
7076      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7077      * additional state variable of the loop.
7078      * The body must both accept and return a value of this type {@code V}.
7079      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7080      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7081      * <a href="MethodHandles.html#effid">effectively identical</a>
7082      * to the external parameter list {@code (A...)}.
7083      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7084      * {@linkplain #empty default value}.
7085      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
7086      * Its parameter list (either empty or of the form {@code (V A*)}) must be
7087      * effectively identical to the internal parameter list.
7088      * </ul>
7089      * <p>
7090      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7091      * <li>The loop handle's result type is the result type {@code V} of the body.
7092      * <li>The loop handle's parameter types are the types {@code (A...)},
7093      * from the external parameter list.
7094      * </ul>
7095      * <p>
7096      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7097      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
7098      * passed to the loop.
7099      * {@snippet lang="java" :
7100      * V init(A...);
7101      * boolean pred(V, A...);
7102      * V body(V, A...);
7103      * V doWhileLoop(A... a...) {
7104      *   V v = init(a...);
7105      *   do {
7106      *     v = body(v, a...);
7107      *   } while (pred(v, a...));
7108      *   return v;
7109      * }
7110      * }
7111      *
7112      * @apiNote Example:
7113      * {@snippet lang="java" :
7114      * // int i = 0; while (i < limit) { ++i; } return i; => limit
7115      * static int zero(int limit) { return 0; }
7116      * static int step(int i, int limit) { return i + 1; }
7117      * static boolean pred(int i, int limit) { return i < limit; }
7118      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
7119      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
7120      * assertEquals(23, loop.invoke(23));
7121      * }
7122      *
7123      *
7124      * @apiNote The implementation of this method can be expressed as follows:
7125      * {@snippet lang="java" :
7126      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7127      *     MethodHandle fini = (body.type().returnType() == void.class
7128      *                         ? null : identity(body.type().returnType()));
7129      *     MethodHandle[] clause = { init, body, pred, fini };
7130      *     return loop(clause);
7131      * }
7132      * }
7133      *
7134      * @param init optional initializer, providing the initial value of the loop variable.
7135      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7136      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7137      *             See above for other constraints.
7138      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7139      *             above for other constraints.
7140      *
7141      * @return a method handle implementing the {@code while} loop as described by the arguments.
7142      * @throws IllegalArgumentException if the rules for the arguments are violated.
7143      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7144      *
7145      * @see #loop(MethodHandle[][])
7146      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
7147      * @since 9
7148      */
7149     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7150         whileLoopChecks(init, pred, body);
7151         MethodHandle fini = identityOrVoid(body.type().returnType());
7152         MethodHandle[] clause = {init, body, pred, fini };
7153         return loop(clause);
7154     }
7155 
7156     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
7157         Objects.requireNonNull(pred);
7158         Objects.requireNonNull(body);
7159         MethodType bodyType = body.type();
7160         Class<?> returnType = bodyType.returnType();
7161         List<Class<?>> innerList = bodyType.parameterList();
7162         List<Class<?>> outerList = innerList;
7163         if (returnType == void.class) {
7164             // OK
7165         } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
7166             // leading V argument missing => error
7167             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7168             throw misMatchedTypes("body function", bodyType, expected);
7169         } else {
7170             outerList = innerList.subList(1, innerList.size());
7171         }
7172         MethodType predType = pred.type();
7173         if (predType.returnType() != boolean.class ||
7174                 !predType.effectivelyIdenticalParameters(0, innerList)) {
7175             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
7176         }
7177         if (init != null) {
7178             MethodType initType = init.type();
7179             if (initType.returnType() != returnType ||
7180                     !initType.effectivelyIdenticalParameters(0, outerList)) {
7181                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7182             }
7183         }
7184     }
7185 
7186     /**
7187      * Constructs a loop that runs a given number of iterations.
7188      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7189      * <p>
7190      * The number of iterations is determined by the {@code iterations} handle evaluation result.
7191      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
7192      * It will be initialized to 0 and incremented by 1 in each iteration.
7193      * <p>
7194      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7195      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7196      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7197      * <p>
7198      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7199      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7200      * iteration variable.
7201      * The result of the loop handle execution will be the final {@code V} value of that variable
7202      * (or {@code void} if there is no {@code V} variable).
7203      * <p>
7204      * The following rules hold for the argument handles:<ul>
7205      * <li>The {@code iterations} handle must not be {@code null}, and must return
7206      * the type {@code int}, referred to here as {@code I} in parameter type lists.
7207      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7208      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7209      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7210      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7211      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7212      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7213      * of types called the <em>internal parameter list</em>.
7214      * It will constrain the parameter lists of the other loop parts.
7215      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7216      * with no additional {@code A} types, then the internal parameter list is extended by
7217      * the argument types {@code A...} of the {@code iterations} handle.
7218      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7219      * list {@code (A...)} is called the <em>external parameter list</em>.
7220      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7221      * additional state variable of the loop.
7222      * The body must both accept a leading parameter and return a value of this type {@code V}.
7223      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7224      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7225      * <a href="MethodHandles.html#effid">effectively identical</a>
7226      * to the external parameter list {@code (A...)}.
7227      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7228      * {@linkplain #empty default value}.
7229      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
7230      * effectively identical to the external parameter list {@code (A...)}.
7231      * </ul>
7232      * <p>
7233      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7234      * <li>The loop handle's result type is the result type {@code V} of the body.
7235      * <li>The loop handle's parameter types are the types {@code (A...)},
7236      * from the external parameter list.
7237      * </ul>
7238      * <p>
7239      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7240      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7241      * arguments passed to the loop.
7242      * {@snippet lang="java" :
7243      * int iterations(A...);
7244      * V init(A...);
7245      * V body(V, int, A...);
7246      * V countedLoop(A... a...) {
7247      *   int end = iterations(a...);
7248      *   V v = init(a...);
7249      *   for (int i = 0; i < end; ++i) {
7250      *     v = body(v, i, a...);
7251      *   }
7252      *   return v;
7253      * }
7254      * }
7255      *
7256      * @apiNote Example with a fully conformant body method:
7257      * {@snippet lang="java" :
7258      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7259      * // => a variation on a well known theme
7260      * static String step(String v, int counter, String init) { return "na " + v; }
7261      * // assume MH_step is a handle to the method above
7262      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
7263      * MethodHandle start = MethodHandles.identity(String.class);
7264      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
7265      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
7266      * }
7267      *
7268      * @apiNote Example with the simplest possible body method type,
7269      * and passing the number of iterations to the loop invocation:
7270      * {@snippet lang="java" :
7271      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7272      * // => a variation on a well known theme
7273      * static String step(String v, int counter ) { return "na " + v; }
7274      * // assume MH_step is a handle to the method above
7275      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
7276      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
7277      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
7278      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
7279      * }
7280      *
7281      * @apiNote Example that treats the number of iterations, string to append to, and string to append
7282      * as loop parameters:
7283      * {@snippet lang="java" :
7284      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7285      * // => a variation on a well known theme
7286      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
7287      * // assume MH_step is a handle to the method above
7288      * MethodHandle count = MethodHandles.identity(int.class);
7289      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
7290      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
7291      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
7292      * }
7293      *
7294      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
7295      * to enforce a loop type:
7296      * {@snippet lang="java" :
7297      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7298      * // => a variation on a well known theme
7299      * static String step(String v, int counter, String pre) { return pre + " " + v; }
7300      * // assume MH_step is a handle to the method above
7301      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
7302      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
7303      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
7304      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
7305      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
7306      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
7307      * }
7308      *
7309      * @apiNote The implementation of this method can be expressed as follows:
7310      * {@snippet lang="java" :
7311      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7312      *     return countedLoop(empty(iterations.type()), iterations, init, body);
7313      * }
7314      * }
7315      *
7316      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
7317      *                   result type must be {@code int}. See above for other constraints.
7318      * @param init optional initializer, providing the initial value of the loop variable.
7319      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7320      * @param body body of the loop, which may not be {@code null}.
7321      *             It controls the loop parameters and result type in the standard case (see above for details).
7322      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7323      *             and may accept any number of additional types.
7324      *             See above for other constraints.
7325      *
7326      * @return a method handle representing the loop.
7327      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7328      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7329      *
7330      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7331      * @since 9
7332      */
7333     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7334         return countedLoop(empty(iterations.type()), iterations, init, body);
7335     }
7336 
7337     /**
7338      * Constructs a loop that counts over a range of numbers.
7339      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7340      * <p>
7341      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7342      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7343      * values of the loop counter.
7344      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7345      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7346      * <p>
7347      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7348      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7349      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7350      * <p>
7351      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7352      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7353      * iteration variable.
7354      * The result of the loop handle execution will be the final {@code V} value of that variable
7355      * (or {@code void} if there is no {@code V} variable).
7356      * <p>
7357      * The following rules hold for the argument handles:<ul>
7358      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7359      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7360      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7361      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7362      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7363      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7364      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7365      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7366      * of types called the <em>internal parameter list</em>.
7367      * It will constrain the parameter lists of the other loop parts.
7368      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7369      * with no additional {@code A} types, then the internal parameter list is extended by
7370      * the argument types {@code A...} of the {@code end} handle.
7371      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7372      * list {@code (A...)} is called the <em>external parameter list</em>.
7373      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7374      * additional state variable of the loop.
7375      * The body must both accept a leading parameter and return a value of this type {@code V}.
7376      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7377      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7378      * <a href="MethodHandles.html#effid">effectively identical</a>
7379      * to the external parameter list {@code (A...)}.
7380      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7381      * {@linkplain #empty default value}.
7382      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7383      * effectively identical to the external parameter list {@code (A...)}.
7384      * <li>Likewise, the parameter list of {@code end} must be effectively identical
7385      * to the external parameter list.
7386      * </ul>
7387      * <p>
7388      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7389      * <li>The loop handle's result type is the result type {@code V} of the body.
7390      * <li>The loop handle's parameter types are the types {@code (A...)},
7391      * from the external parameter list.
7392      * </ul>
7393      * <p>
7394      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7395      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7396      * arguments passed to the loop.
7397      * {@snippet lang="java" :
7398      * int start(A...);
7399      * int end(A...);
7400      * V init(A...);
7401      * V body(V, int, A...);
7402      * V countedLoop(A... a...) {
7403      *   int e = end(a...);
7404      *   int s = start(a...);
7405      *   V v = init(a...);
7406      *   for (int i = s; i < e; ++i) {
7407      *     v = body(v, i, a...);
7408      *   }
7409      *   return v;
7410      * }
7411      * }
7412      *
7413      * @apiNote The implementation of this method can be expressed as follows:
7414      * {@snippet lang="java" :
7415      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7416      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7417      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7418      *     // the following semantics:
7419      *     // MH_increment: (int limit, int counter) -> counter + 1
7420      *     // MH_predicate: (int limit, int counter) -> counter < limit
7421      *     Class<?> counterType = start.type().returnType();  // int
7422      *     Class<?> returnType = body.type().returnType();
7423      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7424      *     if (returnType != void.class) {  // ignore the V variable
7425      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7426      *         pred = dropArguments(pred, 1, returnType);  // ditto
7427      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7428      *     }
7429      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
7430      *     MethodHandle[]
7431      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7432      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
7433      *         indexVar   = { start, incr };           // i = start(); i = i + 1
7434      *     return loop(loopLimit, bodyClause, indexVar);
7435      * }
7436      * }
7437      *
7438      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7439      *              See above for other constraints.
7440      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7441      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
7442      * @param init optional initializer, providing the initial value of the loop variable.
7443      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7444      * @param body body of the loop, which may not be {@code null}.
7445      *             It controls the loop parameters and result type in the standard case (see above for details).
7446      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7447      *             and may accept any number of additional types.
7448      *             See above for other constraints.
7449      *
7450      * @return a method handle representing the loop.
7451      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7452      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7453      *
7454      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7455      * @since 9
7456      */
7457     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7458         countedLoopChecks(start, end, init, body);
7459         Class<?> counterType = start.type().returnType();  // int, but who's counting?
7460         Class<?> limitType   = end.type().returnType();    // yes, int again
7461         Class<?> returnType  = body.type().returnType();
7462         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7463         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7464         MethodHandle retv = null;
7465         if (returnType != void.class) {
7466             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7467             pred = dropArguments(pred, 1, returnType);  // ditto
7468             retv = dropArguments(identity(returnType), 0, counterType);
7469         }
7470         body = dropArguments(body, 0, counterType);  // ignore the limit variable
7471         MethodHandle[]
7472             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7473             bodyClause = { init, body },            // v = init(); v = body(v, i)
7474             indexVar   = { start, incr };           // i = start(); i = i + 1
7475         return loop(loopLimit, bodyClause, indexVar);
7476     }
7477 
7478     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7479         Objects.requireNonNull(start);
7480         Objects.requireNonNull(end);
7481         Objects.requireNonNull(body);
7482         Class<?> counterType = start.type().returnType();
7483         if (counterType != int.class) {
7484             MethodType expected = start.type().changeReturnType(int.class);
7485             throw misMatchedTypes("start function", start.type(), expected);
7486         } else if (end.type().returnType() != counterType) {
7487             MethodType expected = end.type().changeReturnType(counterType);
7488             throw misMatchedTypes("end function", end.type(), expected);
7489         }
7490         MethodType bodyType = body.type();
7491         Class<?> returnType = bodyType.returnType();
7492         List<Class<?>> innerList = bodyType.parameterList();
7493         // strip leading V value if present
7494         int vsize = (returnType == void.class ? 0 : 1);
7495         if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7496             // argument list has no "V" => error
7497             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7498             throw misMatchedTypes("body function", bodyType, expected);
7499         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7500             // missing I type => error
7501             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7502             throw misMatchedTypes("body function", bodyType, expected);
7503         }
7504         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7505         if (outerList.isEmpty()) {
7506             // special case; take lists from end handle
7507             outerList = end.type().parameterList();
7508             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7509         }
7510         MethodType expected = methodType(counterType, outerList);
7511         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7512             throw misMatchedTypes("start parameter types", start.type(), expected);
7513         }
7514         if (end.type() != start.type() &&
7515             !end.type().effectivelyIdenticalParameters(0, outerList)) {
7516             throw misMatchedTypes("end parameter types", end.type(), expected);
7517         }
7518         if (init != null) {
7519             MethodType initType = init.type();
7520             if (initType.returnType() != returnType ||
7521                 !initType.effectivelyIdenticalParameters(0, outerList)) {
7522                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7523             }
7524         }
7525     }
7526 
7527     /**
7528      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7529      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7530      * <p>
7531      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7532      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7533      * <p>
7534      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7535      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7536      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7537      * <p>
7538      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7539      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7540      * iteration variable.
7541      * The result of the loop handle execution will be the final {@code V} value of that variable
7542      * (or {@code void} if there is no {@code V} variable).
7543      * <p>
7544      * The following rules hold for the argument handles:<ul>
7545      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7546      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7547      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7548      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7549      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7550      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7551      * of types called the <em>internal parameter list</em>.
7552      * It will constrain the parameter lists of the other loop parts.
7553      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7554      * with no additional {@code A} types, then the internal parameter list is extended by
7555      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7556      * single type {@code Iterable} is added and constitutes the {@code A...} list.
7557      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7558      * list {@code (A...)} is called the <em>external parameter list</em>.
7559      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7560      * additional state variable of the loop.
7561      * The body must both accept a leading parameter and return a value of this type {@code V}.
7562      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7563      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7564      * <a href="MethodHandles.html#effid">effectively identical</a>
7565      * to the external parameter list {@code (A...)}.
7566      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7567      * {@linkplain #empty default value}.
7568      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7569      * type {@code java.util.Iterator} or a subtype thereof.
7570      * The iterator it produces when the loop is executed will be assumed
7571      * to yield values which can be converted to type {@code T}.
7572      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7573      * effectively identical to the external parameter list {@code (A...)}.
7574      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7575      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7576      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7577      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7578      * the {@link MethodHandle#asType asType} conversion method.
7579      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7580      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7581      * </ul>
7582      * <p>
7583      * The type {@code T} may be either a primitive or reference.
7584      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7585      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7586      * as if by the {@link MethodHandle#asType asType} conversion method.
7587      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7588      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7589      * <p>
7590      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7591      * <li>The loop handle's result type is the result type {@code V} of the body.
7592      * <li>The loop handle's parameter types are the types {@code (A...)},
7593      * from the external parameter list.
7594      * </ul>
7595      * <p>
7596      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7597      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7598      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7599      * {@snippet lang="java" :
7600      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7601      * V init(A...);
7602      * V body(V,T,A...);
7603      * V iteratedLoop(A... a...) {
7604      *   Iterator<T> it = iterator(a...);
7605      *   V v = init(a...);
7606      *   while (it.hasNext()) {
7607      *     T t = it.next();
7608      *     v = body(v, t, a...);
7609      *   }
7610      *   return v;
7611      * }
7612      * }
7613      *
7614      * @apiNote Example:
7615      * {@snippet lang="java" :
7616      * // get an iterator from a list
7617      * static List<String> reverseStep(List<String> r, String e) {
7618      *   r.add(0, e);
7619      *   return r;
7620      * }
7621      * static List<String> newArrayList() { return new ArrayList<>(); }
7622      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7623      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7624      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7625      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7626      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7627      * }
7628      *
7629      * @apiNote The implementation of this method can be expressed approximately as follows:
7630      * {@snippet lang="java" :
7631      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7632      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7633      *     Class<?> returnType = body.type().returnType();
7634      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7635      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7636      *     MethodHandle retv = null, step = body, startIter = iterator;
7637      *     if (returnType != void.class) {
7638      *         // the simple thing first:  in (I V A...), drop the I to get V
7639      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7640      *         // body type signature (V T A...), internal loop types (I V A...)
7641      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7642      *     }
7643      *     if (startIter == null)  startIter = MH_getIter;
7644      *     MethodHandle[]
7645      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7646      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7647      *     return loop(iterVar, bodyClause);
7648      * }
7649      * }
7650      *
7651      * @param iterator an optional handle to return the iterator to start the loop.
7652      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7653      *                 See above for other constraints.
7654      * @param init optional initializer, providing the initial value of the loop variable.
7655      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7656      * @param body body of the loop, which may not be {@code null}.
7657      *             It controls the loop parameters and result type in the standard case (see above for details).
7658      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7659      *             and may accept any number of additional types.
7660      *             See above for other constraints.
7661      *
7662      * @return a method handle embodying the iteration loop functionality.
7663      * @throws NullPointerException if the {@code body} handle is {@code null}.
7664      * @throws IllegalArgumentException if any argument violates the above requirements.
7665      *
7666      * @since 9
7667      */
7668     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7669         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7670         Class<?> returnType = body.type().returnType();
7671         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7672         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7673         MethodHandle startIter;
7674         MethodHandle nextVal;
7675         {
7676             MethodType iteratorType;
7677             if (iterator == null) {
7678                 // derive argument type from body, if available, else use Iterable
7679                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7680                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7681             } else {
7682                 // force return type to the internal iterator class
7683                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7684                 startIter = iterator;
7685             }
7686             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7687             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7688 
7689             // perform the asType transforms under an exception transformer, as per spec.:
7690             try {
7691                 startIter = startIter.asType(iteratorType);
7692                 nextVal = nextRaw.asType(nextValType);
7693             } catch (WrongMethodTypeException ex) {
7694                 throw new IllegalArgumentException(ex);
7695             }
7696         }
7697 
7698         MethodHandle retv = null, step = body;
7699         if (returnType != void.class) {
7700             // the simple thing first:  in (I V A...), drop the I to get V
7701             retv = dropArguments(identity(returnType), 0, Iterator.class);
7702             // body type signature (V T A...), internal loop types (I V A...)
7703             step = swapArguments(body, 0, 1);  // swap V <-> T
7704         }
7705 
7706         MethodHandle[]
7707             iterVar    = { startIter, null, hasNext, retv },
7708             bodyClause = { init, filterArgument(step, 0, nextVal) };
7709         return loop(iterVar, bodyClause);
7710     }
7711 
7712     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7713         Objects.requireNonNull(body);
7714         MethodType bodyType = body.type();
7715         Class<?> returnType = bodyType.returnType();
7716         List<Class<?>> internalParamList = bodyType.parameterList();
7717         // strip leading V value if present
7718         int vsize = (returnType == void.class ? 0 : 1);
7719         if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7720             // argument list has no "V" => error
7721             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7722             throw misMatchedTypes("body function", bodyType, expected);
7723         } else if (internalParamList.size() <= vsize) {
7724             // missing T type => error
7725             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7726             throw misMatchedTypes("body function", bodyType, expected);
7727         }
7728         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7729         Class<?> iterableType = null;
7730         if (iterator != null) {
7731             // special case; if the body handle only declares V and T then
7732             // the external parameter list is obtained from iterator handle
7733             if (externalParamList.isEmpty()) {
7734                 externalParamList = iterator.type().parameterList();
7735             }
7736             MethodType itype = iterator.type();
7737             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7738                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7739             }
7740             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7741                 MethodType expected = methodType(itype.returnType(), externalParamList);
7742                 throw misMatchedTypes("iterator parameters", itype, expected);
7743             }
7744         } else {
7745             if (externalParamList.isEmpty()) {
7746                 // special case; if the iterator handle is null and the body handle
7747                 // only declares V and T then the external parameter list consists
7748                 // of Iterable
7749                 externalParamList = List.of(Iterable.class);
7750                 iterableType = Iterable.class;
7751             } else {
7752                 // special case; if the iterator handle is null and the external
7753                 // parameter list is not empty then the first parameter must be
7754                 // assignable to Iterable
7755                 iterableType = externalParamList.get(0);
7756                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7757                     throw newIllegalArgumentException(
7758                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7759                 }
7760             }
7761         }
7762         if (init != null) {
7763             MethodType initType = init.type();
7764             if (initType.returnType() != returnType ||
7765                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7766                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7767             }
7768         }
7769         return iterableType;  // help the caller a bit
7770     }
7771 
7772     /*non-public*/
7773     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7774         // there should be a better way to uncross my wires
7775         int arity = mh.type().parameterCount();
7776         int[] order = new int[arity];
7777         for (int k = 0; k < arity; k++)  order[k] = k;
7778         order[i] = j; order[j] = i;
7779         Class<?>[] types = mh.type().parameterArray();
7780         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7781         MethodType swapType = methodType(mh.type().returnType(), types);
7782         return permuteArguments(mh, swapType, order);
7783     }
7784 
7785     /**
7786      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7787      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7788      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7789      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7790      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7791      * {@code try-finally} handle.
7792      * <p>
7793      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7794      * The first is the exception thrown during the
7795      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7796      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7797      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7798      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7799      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7800      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7801      * <p>
7802      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7803      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7804      * two extra leading parameters:<ul>
7805      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7806      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7807      * the result from the execution of the {@code target} handle.
7808      * This parameter is not present if the {@code target} returns {@code void}.
7809      * </ul>
7810      * <p>
7811      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7812      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7813      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7814      * the cleanup.
7815      * {@snippet lang="java" :
7816      * V target(A..., B...);
7817      * V cleanup(Throwable, V, A...);
7818      * V adapter(A... a, B... b) {
7819      *   V result = (zero value for V);
7820      *   Throwable throwable = null;
7821      *   try {
7822      *     result = target(a..., b...);
7823      *   } catch (Throwable t) {
7824      *     throwable = t;
7825      *     throw t;
7826      *   } finally {
7827      *     result = cleanup(throwable, result, a...);
7828      *   }
7829      *   return result;
7830      * }
7831      * }
7832      * <p>
7833      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7834      * be modified by execution of the target, and so are passed unchanged
7835      * from the caller to the cleanup, if it is invoked.
7836      * <p>
7837      * The target and cleanup must return the same type, even if the cleanup
7838      * always throws.
7839      * To create such a throwing cleanup, compose the cleanup logic
7840      * with {@link #throwException throwException},
7841      * in order to create a method handle of the correct return type.
7842      * <p>
7843      * Note that {@code tryFinally} never converts exceptions into normal returns.
7844      * In rare cases where exceptions must be converted in that way, first wrap
7845      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7846      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7847      * <p>
7848      * It is recommended that the first parameter type of {@code cleanup} be
7849      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7850      * {@code cleanup} will always be invoked with whatever exception that
7851      * {@code target} throws.  Declaring a narrower type may result in a
7852      * {@code ClassCastException} being thrown by the {@code try-finally}
7853      * handle if the type of the exception thrown by {@code target} is not
7854      * assignable to the first parameter type of {@code cleanup}.  Note that
7855      * various exception types of {@code VirtualMachineError},
7856      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7857      * thrown by almost any kind of Java code, and a finally clause that
7858      * catches (say) only {@code IOException} would mask any of the others
7859      * behind a {@code ClassCastException}.
7860      *
7861      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7862      * @param cleanup the handle that is invoked in the finally block.
7863      *
7864      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7865      * @throws NullPointerException if any argument is null
7866      * @throws IllegalArgumentException if {@code cleanup} does not accept
7867      *          the required leading arguments, or if the method handle types do
7868      *          not match in their return types and their
7869      *          corresponding trailing parameters
7870      *
7871      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7872      * @since 9
7873      */
7874     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7875         Class<?>[] targetParamTypes = target.type().ptypes();
7876         Class<?> rtype = target.type().returnType();
7877 
7878         tryFinallyChecks(target, cleanup);
7879 
7880         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7881         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7882         // target parameter list.
7883         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false);
7884 
7885         // Ensure that the intrinsic type checks the instance thrown by the
7886         // target against the first parameter of cleanup
7887         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7888 
7889         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7890         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7891     }
7892 
7893     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7894         Class<?> rtype = target.type().returnType();
7895         if (rtype != cleanup.type().returnType()) {
7896             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7897         }
7898         MethodType cleanupType = cleanup.type();
7899         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7900             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7901         }
7902         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7903             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7904         }
7905         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7906         // target parameter list.
7907         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7908         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7909             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7910                     cleanup.type(), target.type());
7911         }
7912     }
7913 
7914     /**
7915      * Creates a table switch method handle, which can be used to switch over a set of target
7916      * method handles, based on a given target index, called selector.
7917      * <p>
7918      * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7919      * and where {@code N} is the number of target method handles, the table switch method
7920      * handle will invoke the n-th target method handle from the list of target method handles.
7921      * <p>
7922      * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7923      * method handle will invoke the given fallback method handle.
7924      * <p>
7925      * All method handles passed to this method must have the same type, with the additional
7926      * requirement that the leading parameter be of type {@code int}. The leading parameter
7927      * represents the selector.
7928      * <p>
7929      * Any trailing parameters present in the type will appear on the returned table switch
7930      * method handle as well. Any arguments assigned to these parameters will be forwarded,
7931      * together with the selector value, to the selected method handle when invoking it.
7932      *
7933      * @apiNote Example:
7934      * The cases each drop the {@code selector} value they are given, and take an additional
7935      * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7936      * to a specific constant label string for each case:
7937      * {@snippet lang="java" :
7938      * MethodHandles.Lookup lookup = MethodHandles.lookup();
7939      * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7940      *         MethodType.methodType(String.class, String.class));
7941      * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7942      *
7943      * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7944      * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7945      * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7946      *
7947      * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7948      *     caseDefault,
7949      *     case0,
7950      *     case1
7951      * );
7952      *
7953      * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7954      * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7955      * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7956      * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7957      * }
7958      *
7959      * @param fallback the fallback method handle that is called when the selector is not
7960      *                 within the range {@code [0, N)}.
7961      * @param targets array of target method handles.
7962      * @return the table switch method handle.
7963      * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7964      *                              any of the elements of the {@code targets} array are
7965      *                              {@code null}.
7966      * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7967      *                                  parameter of the fallback handle or any of the target
7968      *                                  handles is not {@code int}, or if the types of
7969      *                                  the fallback handle and all of target handles are
7970      *                                  not the same.
7971      */
7972     public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7973         Objects.requireNonNull(fallback);
7974         Objects.requireNonNull(targets);
7975         targets = targets.clone();
7976         MethodType type = tableSwitchChecks(fallback, targets);
7977         return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7978     }
7979 
7980     private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7981         if (caseActions.length == 0)
7982             throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7983 
7984         MethodType expectedType = defaultCase.type();
7985 
7986         if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7987             throw new IllegalArgumentException(
7988                 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7989 
7990         for (MethodHandle mh : caseActions) {
7991             Objects.requireNonNull(mh);
7992             if (mh.type() != expectedType)
7993                 throw new IllegalArgumentException(
7994                     "Case actions must have the same type: " + Arrays.toString(caseActions));
7995         }
7996 
7997         return expectedType;
7998     }
7999 
8000     /**
8001      * Creates a var handle object, which can be used to dereference a {@linkplain java.lang.foreign.MemorySegment memory segment}
8002      * at a given byte offset, using the provided value layout.
8003      *
8004      * <p>The provided layout specifies the {@linkplain ValueLayout#carrier() carrier type},
8005      * the {@linkplain ValueLayout#byteSize() byte size},
8006      * the {@linkplain ValueLayout#byteAlignment() byte alignment} and the {@linkplain ValueLayout#order() byte order}
8007      * associated with the returned var handle.
8008      *
8009      * <p>The list of coordinate types associated with the returned var handle is {@code (MemorySegment, long)},
8010      * where the {@code long} coordinate type corresponds to byte offset into the given memory segment coordinate.
8011      * Thus, the returned var handle accesses bytes at an offset in a given memory segment, composing bytes to or from
8012      * a value of the var handle type. Moreover, the access operation will honor the endianness and the
8013      * alignment constraints expressed in the provided layout.
8014      *
8015      * <p>As an example, consider the memory layout expressed by a {@link GroupLayout} instance constructed as follows:
8016      * {@snippet lang="java" :
8017      *     GroupLayout seq = java.lang.foreign.MemoryLayout.structLayout(
8018      *             MemoryLayout.paddingLayout(4),
8019      *             ValueLayout.JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN).withName("value")
8020      *     );
8021      * }
8022      * To access the member layout named {@code value}, we can construct a memory segment view var handle as follows:
8023      * {@snippet lang="java" :
8024      *     VarHandle handle = MethodHandles.memorySegmentViewVarHandle(ValueLayout.JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN)); //(MemorySegment, long) -> int
8025      *     handle = MethodHandles.insertCoordinates(handle, 1, 4); //(MemorySegment) -> int
8026      * }
8027      *
8028      * @apiNote The resulting var handle features certain <i>access mode restrictions</i>,
8029      * which are common to all memory segment view var handles. A memory segment view var handle is associated
8030      * with an access size {@code S} and an alignment constraint {@code B}
8031      * (both expressed in bytes). We say that a memory access operation is <em>fully aligned</em> if it occurs
8032      * at a memory address {@code A} which is compatible with both alignment constraints {@code S} and {@code B}.
8033      * If access is fully aligned then following access modes are supported and are
8034      * guaranteed to support atomic access:
8035      * <ul>
8036      * <li>read write access modes for all {@code T}, with the exception of
8037      *     access modes {@code get} and {@code set} for {@code long} and
8038      *     {@code double} on 32-bit platforms.
8039      * <li>atomic update access modes for {@code int}, {@code long},
8040      *     {@code float}, {@code double} or {@link MemorySegment}.
8041      *     (Future major platform releases of the JDK may support additional
8042      *     types for certain currently unsupported access modes.)
8043      * <li>numeric atomic update access modes for {@code int}, {@code long} and {@link MemorySegment}.
8044      *     (Future major platform releases of the JDK may support additional
8045      *     numeric types for certain currently unsupported access modes.)
8046      * <li>bitwise atomic update access modes for {@code int}, {@code long} and {@link MemorySegment}.
8047      *     (Future major platform releases of the JDK may support additional
8048      *     numeric types for certain currently unsupported access modes.)
8049      * </ul>
8050      *
8051      * If {@code T} is {@code float}, {@code double} or {@link MemorySegment} then atomic
8052      * update access modes compare values using their bitwise representation
8053      * (see {@link Float#floatToRawIntBits},
8054      * {@link Double#doubleToRawLongBits} and {@link MemorySegment#address()}, respectively).
8055      * <p>
8056      * Alternatively, a memory access operation is <em>partially aligned</em> if it occurs at a memory address {@code A}
8057      * which is only compatible with the alignment constraint {@code B}; in such cases, access for anything other than the
8058      * {@code get} and {@code set} access modes will result in an {@code IllegalStateException}. If access is partially aligned,
8059      * atomic access is only guaranteed with respect to the largest power of two that divides the GCD of {@code A} and {@code S}.
8060      * <p>
8061      * In all other cases, we say that a memory access operation is <em>misaligned</em>; in such cases an
8062      * {@code IllegalStateException} is thrown, irrespective of the access mode being used.
8063      * <p>
8064      * Finally, if {@code T} is {@code MemorySegment} all write access modes throw {@link IllegalArgumentException}
8065      * unless the value to be written is a {@linkplain MemorySegment#isNative() native} memory segment.
8066      *
8067      * @param layout the value layout for which a memory access handle is to be obtained.
8068      * @return the new memory segment view var handle.
8069      * @throws NullPointerException if {@code layout} is {@code null}.
8070      * @see MemoryLayout#varHandle(MemoryLayout.PathElement...)
8071      * @since 19
8072      */
8073     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8074     public static VarHandle memorySegmentViewVarHandle(ValueLayout layout) {
8075         Objects.requireNonNull(layout);
8076         return Utils.makeSegmentViewVarHandle(layout);
8077     }
8078 
8079     /**
8080      * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions.
8081      * <p>
8082      * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where
8083      * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed
8084      * to the target var handle.
8085      * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from
8086      * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function)
8087      * is processed using the second filter and returned to the caller. More advanced access mode types, such as
8088      * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time.
8089      * <p>
8090      * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and
8091      * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case,
8092      * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which
8093      * will be appended to the coordinates of the target var handle).
8094      * <p>
8095      * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will
8096      * throw an {@link IllegalStateException}.
8097      * <p>
8098      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8099      * atomic access guarantees as those featured by the target var handle.
8100      *
8101      * @param target the target var handle
8102      * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target}
8103      * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S}
8104      * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions.
8105      * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types
8106      * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle,
8107      * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions.
8108      * @throws NullPointerException if any of the arguments is {@code null}.
8109      * @since 19
8110      */
8111     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8112     public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
8113         return VarHandles.filterValue(target, filterToTarget, filterFromTarget);
8114     }
8115 
8116     /**
8117      * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions.
8118      * <p>
8119      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values
8120      * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types
8121      * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the
8122      * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered
8123      * by the adaptation) to the target var handle.
8124      * <p>
8125      * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn},
8126      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
8127      * <p>
8128      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8129      * throw an {@link IllegalStateException}.
8130      * <p>
8131      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8132      * atomic access guarantees as those featured by the target var handle.
8133      *
8134      * @param target the target var handle
8135      * @param pos the position of the first coordinate to be transformed
8136      * @param filters the unary functions which are used to transform coordinates starting at position {@code pos}
8137      * @return an adapter var handle which accepts new coordinate types, applying the provided transformation
8138      * to the new coordinate values.
8139      * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types
8140      * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting
8141      * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8142      * or if more filters are provided than the actual number of coordinate types available starting at {@code pos},
8143      * or if it's determined that any of the filters throws any checked exceptions.
8144      * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}.
8145      * @since 19
8146      */
8147     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8148     public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
8149         return VarHandles.filterCoordinates(target, pos, filters);
8150     }
8151 
8152     /**
8153      * Provides a target var handle with one or more <em>bound coordinates</em>
8154      * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less
8155      * coordinate types than the target var handle.
8156      * <p>
8157      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values
8158      * are joined with bound coordinate values, and then passed to the target var handle.
8159      * <p>
8160      * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn },
8161      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
8162      * <p>
8163      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8164      * atomic access guarantees as those featured by the target var handle.
8165      *
8166      * @param target the var handle to invoke after the bound coordinates are inserted
8167      * @param pos the position of the first coordinate to be inserted
8168      * @param values the series of bound coordinates to insert
8169      * @return an adapter var handle which inserts additional coordinates,
8170      *         before calling the target var handle
8171      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8172      * or if more values are provided than the actual number of coordinate types available starting at {@code pos}.
8173      * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types
8174      * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos}
8175      * of the target var handle.
8176      * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}.
8177      * @since 19
8178      */
8179     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8180     public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
8181         return VarHandles.insertCoordinates(target, pos, values);
8182     }
8183 
8184     /**
8185      * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them
8186      * so that the new coordinates match the provided ones.
8187      * <p>
8188      * The given array controls the reordering.
8189      * Call {@code #I} the number of incoming coordinates (the value
8190      * {@code newCoordinates.size()}), and call {@code #O} the number
8191      * of outgoing coordinates (the number of coordinates associated with the target var handle).
8192      * Then the length of the reordering array must be {@code #O},
8193      * and each element must be a non-negative number less than {@code #I}.
8194      * For every {@code N} less than {@code #O}, the {@code N}-th
8195      * outgoing coordinate will be taken from the {@code I}-th incoming
8196      * coordinate, where {@code I} is {@code reorder[N]}.
8197      * <p>
8198      * No coordinate value conversions are applied.
8199      * The type of each incoming coordinate, as determined by {@code newCoordinates},
8200      * must be identical to the type of the corresponding outgoing coordinate
8201      * in the target var handle.
8202      * <p>
8203      * The reordering array need not specify an actual permutation.
8204      * An incoming coordinate will be duplicated if its index appears
8205      * more than once in the array, and an incoming coordinate will be dropped
8206      * if its index does not appear in the array.
8207      * <p>
8208      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8209      * atomic access guarantees as those featured by the target var handle.
8210      * @param target the var handle to invoke after the coordinates have been reordered
8211      * @param newCoordinates the new coordinate types
8212      * @param reorder an index array which controls the reordering
8213      * @return an adapter var handle which re-arranges the incoming coordinate values,
8214      * before calling the target var handle
8215      * @throws IllegalArgumentException if the index array length is not equal to
8216      * the number of coordinates of the target var handle, or if any index array element is not a valid index for
8217      * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in
8218      * the target var handle and in {@code newCoordinates} are not identical.
8219      * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}.
8220      * @since 19
8221      */
8222     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8223     public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
8224         return VarHandles.permuteCoordinates(target, newCoordinates, reorder);
8225     }
8226 
8227     /**
8228      * Adapts a target var handle by pre-processing
8229      * a sub-sequence of its coordinate values with a filter (a method handle).
8230      * The pre-processed coordinates are replaced by the result (if any) of the
8231      * filter function and the target var handle is then called on the modified (usually shortened)
8232      * coordinate list.
8233      * <p>
8234      * If {@code R} is the return type of the filter, then:
8235      * <ul>
8236      * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in
8237      * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos}
8238      * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first,
8239      * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the
8240      * target var handle.</li>
8241      * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the
8242      * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle
8243      * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a
8244      * downstream invocation of the target var handle.</li>
8245      * </ul>
8246      * <p>
8247      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8248      * throw an {@link IllegalStateException}.
8249      * <p>
8250      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8251      * atomic access guarantees as those featured by the target var handle.
8252      *
8253      * @param target the var handle to invoke after the coordinates have been filtered
8254      * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted
8255      * @param filter the filter method handle
8256      * @return an adapter var handle which filters the incoming coordinate values,
8257      * before calling the target var handle
8258      * @throws IllegalArgumentException if the return type of {@code filter}
8259      * is not void, and it is not the same as the {@code pos} coordinate of the target var handle,
8260      * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8261      * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>,
8262      * or if it's determined that {@code filter} throws any checked exceptions.
8263      * @throws NullPointerException if any of the arguments is {@code null}.
8264      * @since 19
8265      */
8266     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8267     public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
8268         return VarHandles.collectCoordinates(target, pos, filter);
8269     }
8270 
8271     /**
8272      * Returns a var handle which will discard some dummy coordinates before delegating to the
8273      * target var handle. As a consequence, the resulting var handle will feature more
8274      * coordinate types than the target var handle.
8275      * <p>
8276      * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the
8277      * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede
8278      * the target's real arguments; if {@code pos} is <i>N</i> they will come after.
8279      * <p>
8280      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8281      * atomic access guarantees as those featured by the target var handle.
8282      *
8283      * @param target the var handle to invoke after the dummy coordinates are dropped
8284      * @param pos position of the first coordinate to drop (zero for the leftmost)
8285      * @param valueTypes the type(s) of the coordinate(s) to drop
8286      * @return an adapter var handle which drops some dummy coordinates,
8287      *         before calling the target var handle
8288      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive.
8289      * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}.
8290      * @since 19
8291      */
8292     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8293     public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
8294         return VarHandles.dropCoordinates(target, pos, valueTypes);
8295     }
8296 }