1 /*
   2  * Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import jdk.internal.access.SharedSecrets;
  29 import jdk.internal.foreign.Utils;
  30 import jdk.internal.javac.PreviewFeature;
  31 import jdk.internal.misc.Unsafe;
  32 import jdk.internal.misc.VM;
  33 import jdk.internal.org.objectweb.asm.ClassReader;
  34 import jdk.internal.org.objectweb.asm.Opcodes;
  35 import jdk.internal.org.objectweb.asm.Type;
  36 import jdk.internal.reflect.CallerSensitive;
  37 import jdk.internal.reflect.CallerSensitiveAdapter;
  38 import jdk.internal.reflect.Reflection;
  39 import jdk.internal.util.ClassFileDumper;
  40 import jdk.internal.vm.annotation.ForceInline;
  41 import sun.invoke.util.ValueConversions;
  42 import sun.invoke.util.VerifyAccess;
  43 import sun.invoke.util.Wrapper;
  44 import sun.reflect.misc.ReflectUtil;
  45 import sun.security.util.SecurityConstants;
  46 
  47 import java.lang.constant.ConstantDescs;
  48 import java.lang.foreign.GroupLayout;
  49 import java.lang.foreign.MemoryLayout;
  50 import java.lang.foreign.MemorySegment;
  51 import java.lang.foreign.ValueLayout;
  52 import java.lang.invoke.LambdaForm.BasicType;
  53 import java.lang.reflect.Constructor;
  54 import java.lang.reflect.Field;
  55 import java.lang.reflect.Member;
  56 import java.lang.reflect.Method;
  57 import java.lang.reflect.Modifier;
  58 import java.nio.ByteOrder;
  59 import java.security.ProtectionDomain;
  60 import java.util.ArrayList;
  61 import java.util.Arrays;
  62 import java.util.BitSet;
  63 import java.util.Comparator;
  64 import java.util.Iterator;
  65 import java.util.List;
  66 import java.util.Objects;
  67 import java.util.Set;
  68 import java.util.concurrent.ConcurrentHashMap;
  69 import java.util.stream.Stream;
  70 
  71 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
  72 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  73 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  74 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
  75 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  76 import static java.lang.invoke.MethodHandleStatics.newInternalError;
  77 import static java.lang.invoke.MethodType.methodType;
  78 
  79 /**
  80  * This class consists exclusively of static methods that operate on or return
  81  * method handles. They fall into several categories:
  82  * <ul>
  83  * <li>Lookup methods which help create method handles for methods and fields.
  84  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  85  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  86  * </ul>
  87  * A lookup, combinator, or factory method will fail and throw an
  88  * {@code IllegalArgumentException} if the created method handle's type
  89  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  90  *
  91  * @author John Rose, JSR 292 EG
  92  * @since 1.7
  93  */
  94 public class MethodHandles {
  95 
  96     private MethodHandles() { }  // do not instantiate
  97 
  98     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  99 
 100     // See IMPL_LOOKUP below.
 101 
 102     //// Method handle creation from ordinary methods.
 103 
 104     /**
 105      * Returns a {@link Lookup lookup object} with
 106      * full capabilities to emulate all supported bytecode behaviors of the caller.
 107      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
 108      * Factory methods on the lookup object can create
 109      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
 110      * for any member that the caller has access to via bytecodes,
 111      * including protected and private fields and methods.
 112      * This lookup object is created by the original lookup class
 113      * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
 114      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 115      * Do not store it in place where untrusted code can access it.
 116      * <p>
 117      * This method is caller sensitive, which means that it may return different
 118      * values to different callers.
 119      * In cases where {@code MethodHandles.lookup} is called from a context where
 120      * there is no caller frame on the stack (e.g. when called directly
 121      * from a JNI attached thread), {@code IllegalCallerException} is thrown.
 122      * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will
 123      * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()}
 124      * to obtain a low-privileged lookup instead.
 125      * @return a lookup object for the caller of this method, with
 126      * {@linkplain Lookup#ORIGINAL original} and
 127      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
 128      * @throws IllegalCallerException if there is no caller frame on the stack.
 129      */
 130     @CallerSensitive
 131     @ForceInline // to ensure Reflection.getCallerClass optimization
 132     public static Lookup lookup() {
 133         final Class<?> c = Reflection.getCallerClass();
 134         if (c == null) {
 135             throw new IllegalCallerException("no caller frame");
 136         }
 137         return new Lookup(c);
 138     }
 139 
 140     /**
 141      * This lookup method is the alternate implementation of
 142      * the lookup method with a leading caller class argument which is
 143      * non-caller-sensitive.  This method is only invoked by reflection
 144      * and method handle.
 145      */
 146     @CallerSensitiveAdapter
 147     private static Lookup lookup(Class<?> caller) {
 148         if (caller.getClassLoader() == null) {
 149             throw newInternalError("calling lookup() reflectively is not supported: "+caller);
 150         }
 151         return new Lookup(caller);
 152     }
 153 
 154     /**
 155      * Returns a {@link Lookup lookup object} which is trusted minimally.
 156      * The lookup has the {@code UNCONDITIONAL} mode.
 157      * It can only be used to create method handles to public members of
 158      * public classes in packages that are exported unconditionally.
 159      * <p>
 160      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 161      * of this lookup object will be {@link java.lang.Object}.
 162      *
 163      * @apiNote The use of Object is conventional, and because the lookup modes are
 164      * limited, there is no special access provided to the internals of Object, its package
 165      * or its module.  This public lookup object or other lookup object with
 166      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 167      * is not used to determine the lookup context.
 168      *
 169      * <p style="font-size:smaller;">
 170      * <em>Discussion:</em>
 171      * The lookup class can be changed to any other class {@code C} using an expression of the form
 172      * {@link Lookup#in publicLookup().in(C.class)}.
 173      * A public lookup object is always subject to
 174      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 175      * Also, it cannot access
 176      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 177      * @return a lookup object which is trusted minimally
 178      */
 179     public static Lookup publicLookup() {
 180         return Lookup.PUBLIC_LOOKUP;
 181     }
 182 
 183     /**
 184      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 185      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 186      * The returned lookup object can provide access to classes in modules and packages,
 187      * and members of those classes, outside the normal rules of Java access control,
 188      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 189      * <p>
 190      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 191      * allowed to do deep reflection on module {@code M2} and package of the target class
 192      * if and only if all of the following conditions are {@code true}:
 193      * <ul>
 194      * <li>If there is a security manager, its {@code checkPermission} method is
 195      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 196      * that must return normally.
 197      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 198      * full privilege access}.  Specifically:
 199      *   <ul>
 200      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 201      *         (This is because otherwise there would be no way to ensure the original lookup
 202      *         creator was a member of any particular module, and so any subsequent checks
 203      *         for readability and qualified exports would become ineffective.)
 204      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 205      *         (This is because an application intending to share intra-module access
 206      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 207      *         deep reflection to its own module.)
 208      *   </ul>
 209      * <li>The target class must be a proper class, not a primitive or array class.
 210      * (Thus, {@code M2} is well-defined.)
 211      * <li>If the caller module {@code M1} differs from
 212      * the target module {@code M2} then both of the following must be true:
 213      *   <ul>
 214      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 215      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 216      *         containing the target class to at least {@code M1}.</li>
 217      *   </ul>
 218      * </ul>
 219      * <p>
 220      * If any of the above checks is violated, this method fails with an
 221      * exception.
 222      * <p>
 223      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 224      * returns a {@code Lookup} on {@code targetClass} with
 225      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 226      * with {@code null} previous lookup class.
 227      * <p>
 228      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 229      * returns a {@code Lookup} on {@code targetClass} that records
 230      * the lookup class of the caller as the new previous lookup class with
 231      * {@code PRIVATE} access but no {@code MODULE} access.
 232      * <p>
 233      * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
 234      *
 235      * @apiNote The {@code Lookup} object returned by this method is allowed to
 236      * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
 237      * of {@code targetClass}. Extreme caution should be taken when opening a package
 238      * to another module as such defined classes have the same full privilege
 239      * access as other members in {@code targetClass}'s module.
 240      *
 241      * @param targetClass the target class
 242      * @param caller the caller lookup object
 243      * @return a lookup object for the target class, with private access
 244      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 245      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 246      * @throws SecurityException if denied by the security manager
 247      * @throws IllegalAccessException if any of the other access checks specified above fails
 248      * @since 9
 249      * @see Lookup#dropLookupMode
 250      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 251      */
 252     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 253         if (caller.allowedModes == Lookup.TRUSTED) {
 254             return new Lookup(targetClass);
 255         }
 256 
 257         @SuppressWarnings("removal")
 258         SecurityManager sm = System.getSecurityManager();
 259         if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 260         if (targetClass.isPrimitive())
 261             throw new IllegalArgumentException(targetClass + " is a primitive class");
 262         if (targetClass.isArray())
 263             throw new IllegalArgumentException(targetClass + " is an array class");
 264         // Ensure that we can reason accurately about private and module access.
 265         int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
 266         if ((caller.lookupModes() & requireAccess) != requireAccess)
 267             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 268 
 269         // previous lookup class is never set if it has MODULE access
 270         assert caller.previousLookupClass() == null;
 271 
 272         Class<?> callerClass = caller.lookupClass();
 273         Module callerModule = callerClass.getModule();  // M1
 274         Module targetModule = targetClass.getModule();  // M2
 275         Class<?> newPreviousClass = null;
 276         int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
 277 
 278         if (targetModule != callerModule) {
 279             if (!callerModule.canRead(targetModule))
 280                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 281             if (targetModule.isNamed()) {
 282                 String pn = targetClass.getPackageName();
 283                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 284                 if (!targetModule.isOpen(pn, callerModule))
 285                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 286             }
 287 
 288             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 289             newPreviousClass = callerClass;
 290             newModes &= ~Lookup.MODULE;
 291         }
 292         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 293     }
 294 
 295     /**
 296      * Returns the <em>class data</em> associated with the lookup class
 297      * of the given {@code caller} lookup object, or {@code null}.
 298      *
 299      * <p> A hidden class with class data can be created by calling
 300      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 301      * Lookup::defineHiddenClassWithClassData}.
 302      * This method will cause the static class initializer of the lookup
 303      * class of the given {@code caller} lookup object be executed if
 304      * it has not been initialized.
 305      *
 306      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 307      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 308      * {@code null} is returned if this method is called on the lookup object
 309      * on these classes.
 310      *
 311      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 312      * must have {@linkplain Lookup#ORIGINAL original access}
 313      * in order to retrieve the class data.
 314      *
 315      * @apiNote
 316      * This method can be called as a bootstrap method for a dynamically computed
 317      * constant.  A framework can create a hidden class with class data, for
 318      * example that can be {@code Class} or {@code MethodHandle} object.
 319      * The class data is accessible only to the lookup object
 320      * created by the original caller but inaccessible to other members
 321      * in the same nest.  If a framework passes security sensitive objects
 322      * to a hidden class via class data, it is recommended to load the value
 323      * of class data as a dynamically computed constant instead of storing
 324      * the class data in private static field(s) which are accessible to
 325      * other nestmates.
 326      *
 327      * @param <T> the type to cast the class data object to
 328      * @param caller the lookup context describing the class performing the
 329      * operation (normally stacked by the JVM)
 330      * @param name must be {@link ConstantDescs#DEFAULT_NAME}
 331      *             ({@code "_"})
 332      * @param type the type of the class data
 333      * @return the value of the class data if present in the lookup class;
 334      * otherwise {@code null}
 335      * @throws IllegalArgumentException if name is not {@code "_"}
 336      * @throws IllegalAccessException if the lookup context does not have
 337      * {@linkplain Lookup#ORIGINAL original} access
 338      * @throws ClassCastException if the class data cannot be converted to
 339      * the given {@code type}
 340      * @throws NullPointerException if {@code caller} or {@code type} argument
 341      * is {@code null}
 342      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 343      * @see MethodHandles#classDataAt(Lookup, String, Class, int)
 344      * @since 16
 345      * @jvms 5.5 Initialization
 346      */
 347      public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 348          Objects.requireNonNull(caller);
 349          Objects.requireNonNull(type);
 350          if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
 351              throw new IllegalArgumentException("name must be \"_\": " + name);
 352          }
 353 
 354          if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL)  {
 355              throw new IllegalAccessException(caller + " does not have ORIGINAL access");
 356          }
 357 
 358          Object classdata = classData(caller.lookupClass());
 359          if (classdata == null) return null;
 360 
 361          try {
 362              return BootstrapMethodInvoker.widenAndCast(classdata, type);
 363          } catch (RuntimeException|Error e) {
 364              throw e; // let CCE and other runtime exceptions through
 365          } catch (Throwable e) {
 366              throw new InternalError(e);
 367          }
 368     }
 369 
 370     /*
 371      * Returns the class data set by the VM in the Class::classData field.
 372      *
 373      * This is also invoked by LambdaForms as it cannot use condy via
 374      * MethodHandles::classData due to bootstrapping issue.
 375      */
 376     static Object classData(Class<?> c) {
 377         UNSAFE.ensureClassInitialized(c);
 378         return SharedSecrets.getJavaLangAccess().classData(c);
 379     }
 380 
 381     /**
 382      * Returns the element at the specified index in the
 383      * {@linkplain #classData(Lookup, String, Class) class data},
 384      * if the class data associated with the lookup class
 385      * of the given {@code caller} lookup object is a {@code List}.
 386      * If the class data is not present in this lookup class, this method
 387      * returns {@code null}.
 388      *
 389      * <p> A hidden class with class data can be created by calling
 390      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 391      * Lookup::defineHiddenClassWithClassData}.
 392      * This method will cause the static class initializer of the lookup
 393      * class of the given {@code caller} lookup object be executed if
 394      * it has not been initialized.
 395      *
 396      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 397      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 398      * {@code null} is returned if this method is called on the lookup object
 399      * on these classes.
 400      *
 401      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 402      * must have {@linkplain Lookup#ORIGINAL original access}
 403      * in order to retrieve the class data.
 404      *
 405      * @apiNote
 406      * This method can be called as a bootstrap method for a dynamically computed
 407      * constant.  A framework can create a hidden class with class data, for
 408      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 409      * one object and use this method to load one element at a specific index.
 410      * The class data is accessible only to the lookup object
 411      * created by the original caller but inaccessible to other members
 412      * in the same nest.  If a framework passes security sensitive objects
 413      * to a hidden class via class data, it is recommended to load the value
 414      * of class data as a dynamically computed constant instead of storing
 415      * the class data in private static field(s) which are accessible to other
 416      * nestmates.
 417      *
 418      * @param <T> the type to cast the result object to
 419      * @param caller the lookup context describing the class performing the
 420      * operation (normally stacked by the JVM)
 421      * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
 422      *             ({@code "_"})
 423      * @param type the type of the element at the given index in the class data
 424      * @param index index of the element in the class data
 425      * @return the element at the given index in the class data
 426      * if the class data is present; otherwise {@code null}
 427      * @throws IllegalArgumentException if name is not {@code "_"}
 428      * @throws IllegalAccessException if the lookup context does not have
 429      * {@linkplain Lookup#ORIGINAL original} access
 430      * @throws ClassCastException if the class data cannot be converted to {@code List}
 431      * or the element at the specified index cannot be converted to the given type
 432      * @throws IndexOutOfBoundsException if the index is out of range
 433      * @throws NullPointerException if {@code caller} or {@code type} argument is
 434      * {@code null}; or if unboxing operation fails because
 435      * the element at the given index is {@code null}
 436      *
 437      * @since 16
 438      * @see #classData(Lookup, String, Class)
 439      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 440      */
 441     public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
 442             throws IllegalAccessException
 443     {
 444         @SuppressWarnings("unchecked")
 445         List<Object> classdata = (List<Object>)classData(caller, name, List.class);
 446         if (classdata == null) return null;
 447 
 448         try {
 449             Object element = classdata.get(index);
 450             return BootstrapMethodInvoker.widenAndCast(element, type);
 451         } catch (RuntimeException|Error e) {
 452             throw e; // let specified exceptions and other runtime exceptions/errors through
 453         } catch (Throwable e) {
 454             throw new InternalError(e);
 455         }
 456     }
 457 
 458     /**
 459      * Performs an unchecked "crack" of a
 460      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 461      * The result is as if the user had obtained a lookup object capable enough
 462      * to crack the target method handle, called
 463      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 464      * on the target to obtain its symbolic reference, and then called
 465      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 466      * to resolve the symbolic reference to a member.
 467      * <p>
 468      * If there is a security manager, its {@code checkPermission} method
 469      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 470      * @param <T> the desired type of the result, either {@link Member} or a subtype
 471      * @param target a direct method handle to crack into symbolic reference components
 472      * @param expected a class object representing the desired result type {@code T}
 473      * @return a reference to the method, constructor, or field object
 474      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 475      * @throws    NullPointerException if either argument is {@code null}
 476      * @throws    IllegalArgumentException if the target is not a direct method handle
 477      * @throws    ClassCastException if the member is not of the expected type
 478      * @since 1.8
 479      */
 480     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 481         @SuppressWarnings("removal")
 482         SecurityManager smgr = System.getSecurityManager();
 483         if (smgr != null)  smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 484         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 485         return lookup.revealDirect(target).reflectAs(expected, lookup);
 486     }
 487 
 488     /**
 489      * A <em>lookup object</em> is a factory for creating method handles,
 490      * when the creation requires access checking.
 491      * Method handles do not perform
 492      * access checks when they are called, but rather when they are created.
 493      * Therefore, method handle access
 494      * restrictions must be enforced when a method handle is created.
 495      * The caller class against which those restrictions are enforced
 496      * is known as the {@linkplain #lookupClass() lookup class}.
 497      * <p>
 498      * A lookup class which needs to create method handles will call
 499      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 500      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 501      * determined, and securely stored in the {@code Lookup} object.
 502      * The lookup class (or its delegates) may then use factory methods
 503      * on the {@code Lookup} object to create method handles for access-checked members.
 504      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 505      * even private ones.
 506      *
 507      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 508      * The factory methods on a {@code Lookup} object correspond to all major
 509      * use cases for methods, constructors, and fields.
 510      * Each method handle created by a factory method is the functional
 511      * equivalent of a particular <em>bytecode behavior</em>.
 512      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 513      * the Java Virtual Machine Specification.)
 514      * Here is a summary of the correspondence between these factory methods and
 515      * the behavior of the resulting method handles:
 516      * <table class="striped">
 517      * <caption style="display:none">lookup method behaviors</caption>
 518      * <thead>
 519      * <tr>
 520      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 521      *     <th scope="col">member</th>
 522      *     <th scope="col">bytecode behavior</th>
 523      * </tr>
 524      * </thead>
 525      * <tbody>
 526      * <tr>
 527      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 528      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 529      * </tr>
 530      * <tr>
 531      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 532      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 533      * </tr>
 534      * <tr>
 535      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 536      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 537      * </tr>
 538      * <tr>
 539      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 540      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 541      * </tr>
 542      * <tr>
 543      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 544      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 545      * </tr>
 546      * <tr>
 547      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 548      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 549      * </tr>
 550      * <tr>
 551      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 552      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 553      * </tr>
 554      * <tr>
 555      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 556      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 557      * </tr>
 558      * <tr>
 559      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 560      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 561      * </tr>
 562      * <tr>
 563      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 564      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 565      * </tr>
 566      * <tr>
 567      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 568      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 569      * </tr>
 570      * <tr>
 571      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 572      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 573      * </tr>
 574      * <tr>
 575      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 576      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 577      * </tr>
 578      * <tr>
 579      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 580      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 581      * </tr>
 582      * </tbody>
 583      * </table>
 584      *
 585      * Here, the type {@code C} is the class or interface being searched for a member,
 586      * documented as a parameter named {@code refc} in the lookup methods.
 587      * The method type {@code MT} is composed from the return type {@code T}
 588      * and the sequence of argument types {@code A*}.
 589      * The constructor also has a sequence of argument types {@code A*} and
 590      * is deemed to return the newly-created object of type {@code C}.
 591      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 592      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 593      * if it is present, it is always the leading argument to the method handle invocation.
 594      * (In the case of some {@code protected} members, {@code this} may be
 595      * restricted in type to the lookup class; see below.)
 596      * The name {@code arg} stands for all the other method handle arguments.
 597      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 598      * stands for a null reference if the accessed method or field is static,
 599      * and {@code this} otherwise.
 600      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 601      * for reflective objects corresponding to the given members declared in type {@code C}.
 602      * <p>
 603      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 604      * as if by {@code ldc CONSTANT_Class}.
 605      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 606      * <p>
 607      * In cases where the given member is of variable arity (i.e., a method or constructor)
 608      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 609      * In all other cases, the returned method handle will be of fixed arity.
 610      * <p style="font-size:smaller;">
 611      * <em>Discussion:</em>
 612      * The equivalence between looked-up method handles and underlying
 613      * class members and bytecode behaviors
 614      * can break down in a few ways:
 615      * <ul style="font-size:smaller;">
 616      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 617      * the lookup can still succeed, even when there is no equivalent
 618      * Java expression or bytecoded constant.
 619      * <li>Likewise, if {@code T} or {@code MT}
 620      * is not symbolically accessible from the lookup class's loader,
 621      * the lookup can still succeed.
 622      * For example, lookups for {@code MethodHandle.invokeExact} and
 623      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 624      * <li>If there is a security manager installed, it can forbid the lookup
 625      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 626      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 627      * constant is not subject to security manager checks.
 628      * <li>If the looked-up method has a
 629      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 630      * the method handle creation may fail with an
 631      * {@code IllegalArgumentException}, due to the method handle type having
 632      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 633      * </ul>
 634      *
 635      * <h2><a id="access"></a>Access checking</h2>
 636      * Access checks are applied in the factory methods of {@code Lookup},
 637      * when a method handle is created.
 638      * This is a key difference from the Core Reflection API, since
 639      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 640      * performs access checking against every caller, on every call.
 641      * <p>
 642      * All access checks start from a {@code Lookup} object, which
 643      * compares its recorded lookup class against all requests to
 644      * create method handles.
 645      * A single {@code Lookup} object can be used to create any number
 646      * of access-checked method handles, all checked against a single
 647      * lookup class.
 648      * <p>
 649      * A {@code Lookup} object can be shared with other trusted code,
 650      * such as a metaobject protocol.
 651      * A shared {@code Lookup} object delegates the capability
 652      * to create method handles on private members of the lookup class.
 653      * Even if privileged code uses the {@code Lookup} object,
 654      * the access checking is confined to the privileges of the
 655      * original lookup class.
 656      * <p>
 657      * A lookup can fail, because
 658      * the containing class is not accessible to the lookup class, or
 659      * because the desired class member is missing, or because the
 660      * desired class member is not accessible to the lookup class, or
 661      * because the lookup object is not trusted enough to access the member.
 662      * In the case of a field setter function on a {@code final} field,
 663      * finality enforcement is treated as a kind of access control,
 664      * and the lookup will fail, except in special cases of
 665      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 666      * In any of these cases, a {@code ReflectiveOperationException} will be
 667      * thrown from the attempted lookup.  The exact class will be one of
 668      * the following:
 669      * <ul>
 670      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 671      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 672      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 673      * </ul>
 674      * <p>
 675      * In general, the conditions under which a method handle may be
 676      * looked up for a method {@code M} are no more restrictive than the conditions
 677      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 678      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 679      * a method handle lookup will generally raise a corresponding
 680      * checked exception, such as {@code NoSuchMethodException}.
 681      * And the effect of invoking the method handle resulting from the lookup
 682      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 683      * to executing the compiled, verified, and resolved call to {@code M}.
 684      * The same point is true of fields and constructors.
 685      * <p style="font-size:smaller;">
 686      * <em>Discussion:</em>
 687      * Access checks only apply to named and reflected methods,
 688      * constructors, and fields.
 689      * Other method handle creation methods, such as
 690      * {@link MethodHandle#asType MethodHandle.asType},
 691      * do not require any access checks, and are used
 692      * independently of any {@code Lookup} object.
 693      * <p>
 694      * If the desired member is {@code protected}, the usual JVM rules apply,
 695      * including the requirement that the lookup class must either be in the
 696      * same package as the desired member, or must inherit that member.
 697      * (See the Java Virtual Machine Specification, sections {@jvms
 698      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 699      * In addition, if the desired member is a non-static field or method
 700      * in a different package, the resulting method handle may only be applied
 701      * to objects of the lookup class or one of its subclasses.
 702      * This requirement is enforced by narrowing the type of the leading
 703      * {@code this} parameter from {@code C}
 704      * (which will necessarily be a superclass of the lookup class)
 705      * to the lookup class itself.
 706      * <p>
 707      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 708      * that the receiver argument must match both the resolved method <em>and</em>
 709      * the current class.  Again, this requirement is enforced by narrowing the
 710      * type of the leading parameter to the resulting method handle.
 711      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 712      * <p>
 713      * The JVM represents constructors and static initializer blocks as internal methods
 714      * with special names ({@value ConstantDescs#INIT_NAME} and {@value
 715      * ConstantDescs#CLASS_INIT_NAME}).
 716      * The internal syntax of invocation instructions allows them to refer to such internal
 717      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 718      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 719      * <p>
 720      * If the relationship between nested types is expressed directly through the
 721      * {@code NestHost} and {@code NestMembers} attributes
 722      * (see the Java Virtual Machine Specification, sections {@jvms
 723      * 4.7.28} and {@jvms 4.7.29}),
 724      * then the associated {@code Lookup} object provides direct access to
 725      * the lookup class and all of its nestmates
 726      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 727      * Otherwise, access between nested classes is obtained by the Java compiler creating
 728      * a wrapper method to access a private method of another class in the same nest.
 729      * For example, a nested class {@code C.D}
 730      * can access private members within other related classes such as
 731      * {@code C}, {@code C.D.E}, or {@code C.B},
 732      * but the Java compiler may need to generate wrapper methods in
 733      * those related classes.  In such cases, a {@code Lookup} object on
 734      * {@code C.E} would be unable to access those private members.
 735      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 736      * which can transform a lookup on {@code C.E} into one on any of those other
 737      * classes, without special elevation of privilege.
 738      * <p>
 739      * The accesses permitted to a given lookup object may be limited,
 740      * according to its set of {@link #lookupModes lookupModes},
 741      * to a subset of members normally accessible to the lookup class.
 742      * For example, the {@link MethodHandles#publicLookup publicLookup}
 743      * method produces a lookup object which is only allowed to access
 744      * public members in public classes of exported packages.
 745      * The caller sensitive method {@link MethodHandles#lookup lookup}
 746      * produces a lookup object with full capabilities relative to
 747      * its caller class, to emulate all supported bytecode behaviors.
 748      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 749      * with fewer access modes than the original lookup object.
 750      *
 751      * <p style="font-size:smaller;">
 752      * <a id="privacc"></a>
 753      * <em>Discussion of private and module access:</em>
 754      * We say that a lookup has <em>private access</em>
 755      * if its {@linkplain #lookupModes lookup modes}
 756      * include the possibility of accessing {@code private} members
 757      * (which includes the private members of nestmates).
 758      * As documented in the relevant methods elsewhere,
 759      * only lookups with private access possess the following capabilities:
 760      * <ul style="font-size:smaller;">
 761      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 762      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 763      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 764      *     for classes accessible to the lookup class
 765      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 766      *     within the same package member
 767      * </ul>
 768      * <p style="font-size:smaller;">
 769      * Similarly, a lookup with module access ensures that the original lookup creator was
 770      * a member in the same module as the lookup class.
 771      * <p style="font-size:smaller;">
 772      * Private and module access are independently determined modes; a lookup may have
 773      * either or both or neither.  A lookup which possesses both access modes is said to
 774      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
 775      * <p style="font-size:smaller;">
 776      * A lookup with <em>original access</em> ensures that this lookup is created by
 777      * the original lookup class and the bootstrap method invoked by the VM.
 778      * Such a lookup with original access also has private and module access
 779      * which has the following additional capability:
 780      * <ul style="font-size:smaller;">
 781      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 782      *     such as {@code Class.forName}
 783      * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
 784      * class data} associated with the lookup class</li>
 785      * </ul>
 786      * <p style="font-size:smaller;">
 787      * Each of these permissions is a consequence of the fact that a lookup object
 788      * with private access can be securely traced back to an originating class,
 789      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 790      * can be reliably determined and emulated by method handles.
 791      *
 792      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 793      * When a lookup class in one module {@code M1} accesses a class in another module
 794      * {@code M2}, extra access checking is performed beyond the access mode bits.
 795      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 796      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 797      * and when the type is in a package of {@code M2} that is exported to
 798      * at least {@code M1}.
 799      * <p>
 800      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 801      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 802      * MethodHandles.privateLookupIn} methods.
 803      * Teleporting across modules will always record the original lookup class as
 804      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 805      * and drops {@link Lookup#MODULE MODULE} access.
 806      * If the target class is in the same module as the lookup class {@code C},
 807      * then the target class becomes the new lookup class
 808      * and there is no change to the previous lookup class.
 809      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 810      * {@code C} becomes the new previous lookup class
 811      * and the target class becomes the new lookup class.
 812      * In that case, if there was already a previous lookup class in {@code M0},
 813      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 814      * drops all privileges.
 815      * For example,
 816      * {@snippet lang="java" :
 817      * Lookup lookup = MethodHandles.lookup();   // in class C
 818      * Lookup lookup2 = lookup.in(D.class);
 819      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 820      * }
 821      * <p>
 822      * The {@link #lookup()} factory method produces a {@code Lookup} object
 823      * with {@code null} previous lookup class.
 824      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 825      * to class {@code D} without elevation of privileges.
 826      * If {@code C} and {@code D} are in the same module,
 827      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 828      * same previous lookup class as the original {@code lookup}, or
 829      * {@code null} if not present.
 830      * <p>
 831      * When a {@code Lookup} teleports from a class
 832      * in one nest to another nest, {@code PRIVATE} access is dropped.
 833      * When a {@code Lookup} teleports from a class in one package to
 834      * another package, {@code PACKAGE} access is dropped.
 835      * When a {@code Lookup} teleports from a class in one module to another module,
 836      * {@code MODULE} access is dropped.
 837      * Teleporting across modules drops the ability to access non-exported classes
 838      * in both the module of the new lookup class and the module of the old lookup class
 839      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 840      * A {@code Lookup} can teleport back and forth to a class in the module of
 841      * the lookup class and the module of the previous class lookup.
 842      * Teleporting across modules can only decrease access but cannot increase it.
 843      * Teleporting to some third module drops all accesses.
 844      * <p>
 845      * In the above example, if {@code C} and {@code D} are in different modules,
 846      * {@code lookup2} records {@code D} as its lookup class and
 847      * {@code C} as its previous lookup class and {@code lookup2} has only
 848      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 849      * {@code C}'s module and {@code D}'s module.
 850      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 851      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 852      * class {@code D} is recorded as its previous lookup class.
 853      * <p>
 854      * Teleporting across modules restricts access to the public types that
 855      * both the lookup class and the previous lookup class can equally access
 856      * (see below).
 857      * <p>
 858      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 859      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 860      * and produce a new {@code Lookup} with <a href="#privacc">private access</a>
 861      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 862      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 863      * to call {@code privateLookupIn}.
 864      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 865      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 866      * produces a new {@code Lookup} on {@code T} with full capabilities.
 867      * A {@code lookup} on {@code C} is also allowed
 868      * to do deep reflection on {@code T} in another module {@code M2} if
 869      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 870      * the package containing {@code T} to at least {@code M1}.
 871      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 872      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 873      * The resulting {@code Lookup} can be used to do member lookup or teleport
 874      * to another lookup class by calling {@link #in Lookup::in}.  But
 875      * it cannot be used to obtain another private {@code Lookup} by calling
 876      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 877      * because it has no {@code MODULE} access.
 878      * <p>
 879      * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to
 880      * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
 881      * of {@code T}. Extreme caution should be taken when opening a package
 882      * to another module as such defined classes have the same full privilege
 883      * access as other members in {@code M2}.
 884      *
 885      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 886      *
 887      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 888      * allows cross-module access. The access checking is performed with respect
 889      * to both the lookup class and the previous lookup class if present.
 890      * <p>
 891      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 892      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 893      * exported unconditionally}.
 894      * <p>
 895      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 896      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 897      * that are readable to {@code M1} and the type is in a package that is exported
 898      * at least to {@code M1}.
 899      * <p>
 900      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 901      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 902      * the intersection of all public types that are accessible to {@code M1}
 903      * with all public types that are accessible to {@code M0}. {@code M0}
 904      * reads {@code M1} and hence the set of accessible types includes:
 905      *
 906      * <ul>
 907      * <li>unconditional-exported packages from {@code M1}</li>
 908      * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li>
 909      * <li>
 910      *     unconditional-exported packages from a third module {@code M2}if both {@code M0}
 911      *     and {@code M1} read {@code M2}
 912      * </li>
 913      * <li>qualified-exported packages from {@code M1} to {@code M0}</li>
 914      * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li>
 915      * <li>
 916      *     qualified-exported packages from a third module {@code M2} to both {@code M0} and
 917      *     {@code M1} if both {@code M0} and {@code M1} read {@code M2}
 918      * </li>
 919      * </ul>
 920      *
 921      * <h2><a id="access-modes"></a>Access modes</h2>
 922      *
 923      * The table below shows the access modes of a {@code Lookup} produced by
 924      * any of the following factory or transformation methods:
 925      * <ul>
 926      * <li>{@link #lookup() MethodHandles::lookup}</li>
 927      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 928      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 929      * <li>{@link Lookup#in Lookup::in}</li>
 930      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 931      * </ul>
 932      *
 933      * <table class="striped">
 934      * <caption style="display:none">
 935      * Access mode summary
 936      * </caption>
 937      * <thead>
 938      * <tr>
 939      * <th scope="col">Lookup object</th>
 940      * <th style="text-align:center">original</th>
 941      * <th style="text-align:center">protected</th>
 942      * <th style="text-align:center">private</th>
 943      * <th style="text-align:center">package</th>
 944      * <th style="text-align:center">module</th>
 945      * <th style="text-align:center">public</th>
 946      * </tr>
 947      * </thead>
 948      * <tbody>
 949      * <tr>
 950      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 951      * <td style="text-align:center">ORI</td>
 952      * <td style="text-align:center">PRO</td>
 953      * <td style="text-align:center">PRI</td>
 954      * <td style="text-align:center">PAC</td>
 955      * <td style="text-align:center">MOD</td>
 956      * <td style="text-align:center">1R</td>
 957      * </tr>
 958      * <tr>
 959      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 960      * <td></td>
 961      * <td></td>
 962      * <td></td>
 963      * <td style="text-align:center">PAC</td>
 964      * <td style="text-align:center">MOD</td>
 965      * <td style="text-align:center">1R</td>
 966      * </tr>
 967      * <tr>
 968      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 969      * <td></td>
 970      * <td></td>
 971      * <td></td>
 972      * <td></td>
 973      * <td style="text-align:center">MOD</td>
 974      * <td style="text-align:center">1R</td>
 975      * </tr>
 976      * <tr>
 977      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 978      * <td></td>
 979      * <td></td>
 980      * <td></td>
 981      * <td></td>
 982      * <td></td>
 983      * <td style="text-align:center">2R</td>
 984      * </tr>
 985      * <tr>
 986      * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th>
 987      * <td></td>
 988      * <td></td>
 989      * <td></td>
 990      * <td></td>
 991      * <td></td>
 992      * <td style="text-align:center">2R</td>
 993      * </tr>
 994      * <tr>
 995      * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th>
 996      * <td></td>
 997      * <td style="text-align:center">PRO</td>
 998      * <td style="text-align:center">PRI</td>
 999      * <td style="text-align:center">PAC</td>
1000      * <td style="text-align:center">MOD</td>
1001      * <td style="text-align:center">1R</td>
1002      * </tr>
1003      * <tr>
1004      * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th>
1005      * <td></td>
1006      * <td style="text-align:center">PRO</td>
1007      * <td style="text-align:center">PRI</td>
1008      * <td style="text-align:center">PAC</td>
1009      * <td style="text-align:center">MOD</td>
1010      * <td style="text-align:center">1R</td>
1011      * </tr>
1012      * <tr>
1013      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th>
1014      * <td></td>
1015      * <td></td>
1016      * <td></td>
1017      * <td style="text-align:center">PAC</td>
1018      * <td style="text-align:center">MOD</td>
1019      * <td style="text-align:center">1R</td>
1020      * </tr>
1021      * <tr>
1022      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th>
1023      * <td></td>
1024      * <td></td>
1025      * <td></td>
1026      * <td></td>
1027      * <td style="text-align:center">MOD</td>
1028      * <td style="text-align:center">1R</td>
1029      * </tr>
1030      * <tr>
1031      * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th>
1032      * <td></td>
1033      * <td></td>
1034      * <td></td>
1035      * <td></td>
1036      * <td></td>
1037      * <td style="text-align:center">2R</td>
1038      * </tr>
1039      * <tr>
1040      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th>
1041      * <td></td>
1042      * <td></td>
1043      * <td style="text-align:center">PRI</td>
1044      * <td style="text-align:center">PAC</td>
1045      * <td style="text-align:center">MOD</td>
1046      * <td style="text-align:center">1R</td>
1047      * </tr>
1048      * <tr>
1049      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th>
1050      * <td></td>
1051      * <td></td>
1052      * <td></td>
1053      * <td style="text-align:center">PAC</td>
1054      * <td style="text-align:center">MOD</td>
1055      * <td style="text-align:center">1R</td>
1056      * </tr>
1057      * <tr>
1058      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th>
1059      * <td></td>
1060      * <td></td>
1061      * <td></td>
1062      * <td></td>
1063      * <td style="text-align:center">MOD</td>
1064      * <td style="text-align:center">1R</td>
1065      * </tr>
1066      * <tr>
1067      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th>
1068      * <td></td>
1069      * <td></td>
1070      * <td></td>
1071      * <td></td>
1072      * <td></td>
1073      * <td style="text-align:center">1R</td>
1074      * </tr>
1075      * <tr>
1076      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th>
1077      * <td></td>
1078      * <td></td>
1079      * <td></td>
1080      * <td></td>
1081      * <td></td>
1082      * <td style="text-align:center">none</td>
1083      * <tr>
1084      * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th>
1085      * <td></td>
1086      * <td style="text-align:center">PRO</td>
1087      * <td style="text-align:center">PRI</td>
1088      * <td style="text-align:center">PAC</td>
1089      * <td></td>
1090      * <td style="text-align:center">2R</td>
1091      * </tr>
1092      * <tr>
1093      * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th>
1094      * <td></td>
1095      * <td style="text-align:center">PRO</td>
1096      * <td style="text-align:center">PRI</td>
1097      * <td style="text-align:center">PAC</td>
1098      * <td></td>
1099      * <td style="text-align:center">2R</td>
1100      * </tr>
1101      * <tr>
1102      * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th>
1103      * <td></td>
1104      * <td></td>
1105      * <td></td>
1106      * <td></td>
1107      * <td></td>
1108      * <td style="text-align:center">IAE</td>
1109      * </tr>
1110      * <tr>
1111      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th>
1112      * <td></td>
1113      * <td></td>
1114      * <td></td>
1115      * <td style="text-align:center">PAC</td>
1116      * <td></td>
1117      * <td style="text-align:center">2R</td>
1118      * </tr>
1119      * <tr>
1120      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th>
1121      * <td></td>
1122      * <td></td>
1123      * <td></td>
1124      * <td></td>
1125      * <td></td>
1126      * <td style="text-align:center">2R</td>
1127      * </tr>
1128      * <tr>
1129      * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th>
1130      * <td></td>
1131      * <td></td>
1132      * <td></td>
1133      * <td></td>
1134      * <td></td>
1135      * <td style="text-align:center">2R</td>
1136      * </tr>
1137      * <tr>
1138      * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th>
1139      * <td></td>
1140      * <td></td>
1141      * <td></td>
1142      * <td></td>
1143      * <td></td>
1144      * <td style="text-align:center">none</td>
1145      * </tr>
1146      * <tr>
1147      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th>
1148      * <td></td>
1149      * <td></td>
1150      * <td style="text-align:center">PRI</td>
1151      * <td style="text-align:center">PAC</td>
1152      * <td></td>
1153      * <td style="text-align:center">2R</td>
1154      * </tr>
1155      * <tr>
1156      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th>
1157      * <td></td>
1158      * <td></td>
1159      * <td></td>
1160      * <td style="text-align:center">PAC</td>
1161      * <td></td>
1162      * <td style="text-align:center">2R</td>
1163      * </tr>
1164      * <tr>
1165      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th>
1166      * <td></td>
1167      * <td></td>
1168      * <td></td>
1169      * <td></td>
1170      * <td></td>
1171      * <td style="text-align:center">2R</td>
1172      * </tr>
1173      * <tr>
1174      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th>
1175      * <td></td>
1176      * <td></td>
1177      * <td></td>
1178      * <td></td>
1179      * <td></td>
1180      * <td style="text-align:center">2R</td>
1181      * </tr>
1182      * <tr>
1183      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th>
1184      * <td></td>
1185      * <td></td>
1186      * <td></td>
1187      * <td></td>
1188      * <td></td>
1189      * <td style="text-align:center">none</td>
1190      * </tr>
1191      * <tr>
1192      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th>
1193      * <td></td>
1194      * <td></td>
1195      * <td style="text-align:center">PRI</td>
1196      * <td style="text-align:center">PAC</td>
1197      * <td style="text-align:center">MOD</td>
1198      * <td style="text-align:center">1R</td>
1199      * </tr>
1200      * <tr>
1201      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th>
1202      * <td></td>
1203      * <td></td>
1204      * <td></td>
1205      * <td style="text-align:center">PAC</td>
1206      * <td style="text-align:center">MOD</td>
1207      * <td style="text-align:center">1R</td>
1208      * </tr>
1209      * <tr>
1210      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th>
1211      * <td></td>
1212      * <td></td>
1213      * <td></td>
1214      * <td></td>
1215      * <td style="text-align:center">MOD</td>
1216      * <td style="text-align:center">1R</td>
1217      * </tr>
1218      * <tr>
1219      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th>
1220      * <td></td>
1221      * <td></td>
1222      * <td></td>
1223      * <td></td>
1224      * <td></td>
1225      * <td style="text-align:center">1R</td>
1226      * </tr>
1227      * <tr>
1228      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th>
1229      * <td></td>
1230      * <td></td>
1231      * <td></td>
1232      * <td></td>
1233      * <td></td>
1234      * <td style="text-align:center">none</td>
1235      * </tr>
1236      * <tr>
1237      * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th>
1238      * <td></td>
1239      * <td></td>
1240      * <td></td>
1241      * <td></td>
1242      * <td></td>
1243      * <td style="text-align:center">U</td>
1244      * </tr>
1245      * <tr>
1246      * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th>
1247      * <td></td>
1248      * <td></td>
1249      * <td></td>
1250      * <td></td>
1251      * <td></td>
1252      * <td style="text-align:center">U</td>
1253      * </tr>
1254      * <tr>
1255      * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th>
1256      * <td></td>
1257      * <td></td>
1258      * <td></td>
1259      * <td></td>
1260      * <td></td>
1261      * <td style="text-align:center">U</td>
1262      * </tr>
1263      * <tr>
1264      * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th>
1265      * <td></td>
1266      * <td></td>
1267      * <td></td>
1268      * <td></td>
1269      * <td></td>
1270      * <td style="text-align:center">none</td>
1271      * </tr>
1272      * <tr>
1273      * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th>
1274      * <td></td>
1275      * <td></td>
1276      * <td></td>
1277      * <td></td>
1278      * <td></td>
1279      * <td style="text-align:center">IAE</td>
1280      * </tr>
1281      * <tr>
1282      * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th>
1283      * <td></td>
1284      * <td></td>
1285      * <td></td>
1286      * <td></td>
1287      * <td></td>
1288      * <td style="text-align:center">none</td>
1289      * </tr>
1290      * </tbody>
1291      * </table>
1292      *
1293      * <p>
1294      * Notes:
1295      * <ul>
1296      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1297      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1298      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1299      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1300      * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1301      *     {@code PRO} indicates {@link #PROTECTED} bit set,
1302      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1303      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1304      *     {@code MOD} indicates {@link #MODULE} bit set,
1305      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1306      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1307      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1308      * <li>Public access comes in three kinds:
1309      * <ul>
1310      * <li>unconditional ({@code U}): the lookup assumes readability.
1311      *     The lookup has {@code null} previous lookup class.
1312      * <li>one-module-reads ({@code 1R}): the module access checking is
1313      *     performed with respect to the lookup class.  The lookup has {@code null}
1314      *     previous lookup class.
1315      * <li>two-module-reads ({@code 2R}): the module access checking is
1316      *     performed with respect to the lookup class and the previous lookup class.
1317      *     The lookup has a non-null previous lookup class which is in a
1318      *     different module from the current lookup class.
1319      * </ul>
1320      * <li>Any attempt to reach a third module loses all access.</li>
1321      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1322      * all access modes are dropped.</li>
1323      * </ul>
1324      *
1325      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1326      * Although bytecode instructions can only refer to classes in
1327      * a related class loader, this API can search for methods in any
1328      * class, as long as a reference to its {@code Class} object is
1329      * available.  Such cross-loader references are also possible with the
1330      * Core Reflection API, and are impossible to bytecode instructions
1331      * such as {@code invokestatic} or {@code getfield}.
1332      * There is a {@linkplain java.lang.SecurityManager security manager API}
1333      * to allow applications to check such cross-loader references.
1334      * These checks apply to both the {@code MethodHandles.Lookup} API
1335      * and the Core Reflection API
1336      * (as found on {@link java.lang.Class Class}).
1337      * <p>
1338      * If a security manager is present, member and class lookups are subject to
1339      * additional checks.
1340      * From one to three calls are made to the security manager.
1341      * Any of these calls can refuse access by throwing a
1342      * {@link java.lang.SecurityException SecurityException}.
1343      * Define {@code smgr} as the security manager,
1344      * {@code lookc} as the lookup class of the current lookup object,
1345      * {@code refc} as the containing class in which the member
1346      * is being sought, and {@code defc} as the class in which the
1347      * member is actually defined.
1348      * (If a class or other type is being accessed,
1349      * the {@code refc} and {@code defc} values are the class itself.)
1350      * The value {@code lookc} is defined as <em>not present</em>
1351      * if the current lookup object does not have
1352      * {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1353      * The calls are made according to the following rules:
1354      * <ul>
1355      * <li><b>Step 1:</b>
1356      *     If {@code lookc} is not present, or if its class loader is not
1357      *     the same as or an ancestor of the class loader of {@code refc},
1358      *     then {@link SecurityManager#checkPackageAccess
1359      *     smgr.checkPackageAccess(refcPkg)} is called,
1360      *     where {@code refcPkg} is the package of {@code refc}.
1361      * <li><b>Step 2a:</b>
1362      *     If the retrieved member is not public and
1363      *     {@code lookc} is not present, then
1364      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1365      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
1366      * <li><b>Step 2b:</b>
1367      *     If the retrieved class has a {@code null} class loader,
1368      *     and {@code lookc} is not present, then
1369      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1370      *     with {@code RuntimePermission("getClassLoader")} is called.
1371      * <li><b>Step 3:</b>
1372      *     If the retrieved member is not public,
1373      *     and if {@code lookc} is not present,
1374      *     and if {@code defc} and {@code refc} are different,
1375      *     then {@link SecurityManager#checkPackageAccess
1376      *     smgr.checkPackageAccess(defcPkg)} is called,
1377      *     where {@code defcPkg} is the package of {@code defc}.
1378      * </ul>
1379      * Security checks are performed after other access checks have passed.
1380      * Therefore, the above rules presuppose a member or class that is public,
1381      * or else that is being accessed from a lookup class that has
1382      * rights to access the member or class.
1383      * <p>
1384      * If a security manager is present and the current lookup object does not have
1385      * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then
1386      * {@link #defineClass(byte[]) defineClass},
1387      * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass},
1388      * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...)
1389      * defineHiddenClassWithClassData}
1390      * calls {@link SecurityManager#checkPermission smgr.checkPermission}
1391      * with {@code RuntimePermission("defineClass")}.
1392      *
1393      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1394      * A small number of Java methods have a special property called caller sensitivity.
1395      * A <em>caller-sensitive</em> method can behave differently depending on the
1396      * identity of its immediate caller.
1397      * <p>
1398      * If a method handle for a caller-sensitive method is requested,
1399      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1400      * but they take account of the lookup class in a special way.
1401      * The resulting method handle behaves as if it were called
1402      * from an instruction contained in the lookup class,
1403      * so that the caller-sensitive method detects the lookup class.
1404      * (By contrast, the invoker of the method handle is disregarded.)
1405      * Thus, in the case of caller-sensitive methods,
1406      * different lookup classes may give rise to
1407      * differently behaving method handles.
1408      * <p>
1409      * In cases where the lookup object is
1410      * {@link MethodHandles#publicLookup() publicLookup()},
1411      * or some other lookup object without the
1412      * {@linkplain #ORIGINAL original access},
1413      * the lookup class is disregarded.
1414      * In such cases, no caller-sensitive method handle can be created,
1415      * access is forbidden, and the lookup fails with an
1416      * {@code IllegalAccessException}.
1417      * <p style="font-size:smaller;">
1418      * <em>Discussion:</em>
1419      * For example, the caller-sensitive method
1420      * {@link java.lang.Class#forName(String) Class.forName(x)}
1421      * can return varying classes or throw varying exceptions,
1422      * depending on the class loader of the class that calls it.
1423      * A public lookup of {@code Class.forName} will fail, because
1424      * there is no reasonable way to determine its bytecode behavior.
1425      * <p style="font-size:smaller;">
1426      * If an application caches method handles for broad sharing,
1427      * it should use {@code publicLookup()} to create them.
1428      * If there is a lookup of {@code Class.forName}, it will fail,
1429      * and the application must take appropriate action in that case.
1430      * It may be that a later lookup, perhaps during the invocation of a
1431      * bootstrap method, can incorporate the specific identity
1432      * of the caller, making the method accessible.
1433      * <p style="font-size:smaller;">
1434      * The function {@code MethodHandles.lookup} is caller sensitive
1435      * so that there can be a secure foundation for lookups.
1436      * Nearly all other methods in the JSR 292 API rely on lookup
1437      * objects to check access requests.
1438      */
1439     public static final
1440     class Lookup {
1441         /** The class on behalf of whom the lookup is being performed. */
1442         private final Class<?> lookupClass;
1443 
1444         /** previous lookup class */
1445         private final Class<?> prevLookupClass;
1446 
1447         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1448         private final int allowedModes;
1449 
1450         static {
1451             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1452         }
1453 
1454         /** A single-bit mask representing {@code public} access,
1455          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1456          *  The value, {@code 0x01}, happens to be the same as the value of the
1457          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1458          *  <p>
1459          *  A {@code Lookup} with this lookup mode performs cross-module access check
1460          *  with respect to the {@linkplain #lookupClass() lookup class} and
1461          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1462          */
1463         public static final int PUBLIC = Modifier.PUBLIC;
1464 
1465         /** A single-bit mask representing {@code private} access,
1466          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1467          *  The value, {@code 0x02}, happens to be the same as the value of the
1468          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1469          */
1470         public static final int PRIVATE = Modifier.PRIVATE;
1471 
1472         /** A single-bit mask representing {@code protected} access,
1473          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1474          *  The value, {@code 0x04}, happens to be the same as the value of the
1475          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1476          */
1477         public static final int PROTECTED = Modifier.PROTECTED;
1478 
1479         /** A single-bit mask representing {@code package} access (default access),
1480          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1481          *  The value is {@code 0x08}, which does not correspond meaningfully to
1482          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1483          */
1484         public static final int PACKAGE = Modifier.STATIC;
1485 
1486         /** A single-bit mask representing {@code module} access,
1487          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1488          *  The value is {@code 0x10}, which does not correspond meaningfully to
1489          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1490          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1491          *  with this lookup mode can access all public types in the module of the
1492          *  lookup class and public types in packages exported by other modules
1493          *  to the module of the lookup class.
1494          *  <p>
1495          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1496          *  previous lookup class} is always {@code null}.
1497          *
1498          *  @since 9
1499          */
1500         public static final int MODULE = PACKAGE << 1;
1501 
1502         /** A single-bit mask representing {@code unconditional} access
1503          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1504          *  The value is {@code 0x20}, which does not correspond meaningfully to
1505          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1506          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1507          *  java.lang.Module#canRead(java.lang.Module) readability}.
1508          *  This lookup mode can access all public members of public types
1509          *  of all modules when the type is in a package that is {@link
1510          *  java.lang.Module#isExported(String) exported unconditionally}.
1511          *
1512          *  <p>
1513          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1514          *  previous lookup class} is always {@code null}.
1515          *
1516          *  @since 9
1517          *  @see #publicLookup()
1518          */
1519         public static final int UNCONDITIONAL = PACKAGE << 2;
1520 
1521         /** A single-bit mask representing {@code original} access
1522          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1523          *  The value is {@code 0x40}, which does not correspond meaningfully to
1524          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1525          *
1526          *  <p>
1527          *  If this lookup mode is set, the {@code Lookup} object must be
1528          *  created by the original lookup class by calling
1529          *  {@link MethodHandles#lookup()} method or by a bootstrap method
1530          *  invoked by the VM.  The {@code Lookup} object with this lookup
1531          *  mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1532          *
1533          *  @since 16
1534          */
1535         public static final int ORIGINAL = PACKAGE << 3;
1536 
1537         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1538         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);   // with original access
1539         private static final int TRUSTED   = -1;
1540 
1541         /*
1542          * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1543          * Adjust 0 => PACKAGE
1544          */
1545         private static int fixmods(int mods) {
1546             mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1547             if (Modifier.isPublic(mods))
1548                 mods |= UNCONDITIONAL;
1549             return (mods != 0) ? mods : PACKAGE;
1550         }
1551 
1552         /** Tells which class is performing the lookup.  It is this class against
1553          *  which checks are performed for visibility and access permissions.
1554          *  <p>
1555          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1556          *  access checks are performed against both the lookup class and the previous lookup class.
1557          *  <p>
1558          *  The class implies a maximum level of access permission,
1559          *  but the permissions may be additionally limited by the bitmask
1560          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1561          *  can be accessed.
1562          *  @return the lookup class, on behalf of which this lookup object finds members
1563          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1564          */
1565         public Class<?> lookupClass() {
1566             return lookupClass;
1567         }
1568 
1569         /** Reports a lookup class in another module that this lookup object
1570          * was previously teleported from, or {@code null}.
1571          * <p>
1572          * A {@code Lookup} object produced by the factory methods, such as the
1573          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1574          * has {@code null} previous lookup class.
1575          * A {@code Lookup} object has a non-null previous lookup class
1576          * when this lookup was teleported from an old lookup class
1577          * in one module to a new lookup class in another module.
1578          *
1579          * @return the lookup class in another module that this lookup object was
1580          *         previously teleported from, or {@code null}
1581          * @since 14
1582          * @see #in(Class)
1583          * @see MethodHandles#privateLookupIn(Class, Lookup)
1584          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1585          */
1586         public Class<?> previousLookupClass() {
1587             return prevLookupClass;
1588         }
1589 
1590         // This is just for calling out to MethodHandleImpl.
1591         private Class<?> lookupClassOrNull() {
1592             return (allowedModes == TRUSTED) ? null : lookupClass;
1593         }
1594 
1595         /** Tells which access-protection classes of members this lookup object can produce.
1596          *  The result is a bit-mask of the bits
1597          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1598          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1599          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1600          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1601          *  {@linkplain #MODULE MODULE (0x10)},
1602          *  {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1603          *  and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1604          *  <p>
1605          *  A freshly-created lookup object
1606          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1607          *  all possible bits set, except {@code UNCONDITIONAL}.
1608          *  A lookup object on a new lookup class
1609          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1610          *  may have some mode bits set to zero.
1611          *  Mode bits can also be
1612          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1613          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1614          *  The purpose of this is to restrict access via the new lookup object,
1615          *  so that it can access only names which can be reached by the original
1616          *  lookup object, and also by the new lookup class.
1617          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1618          *  @see #in
1619          *  @see #dropLookupMode
1620          */
1621         public int lookupModes() {
1622             return allowedModes & ALL_MODES;
1623         }
1624 
1625         /** Embody the current class (the lookupClass) as a lookup class
1626          * for method handle creation.
1627          * Must be called by from a method in this package,
1628          * which in turn is called by a method not in this package.
1629          */
1630         Lookup(Class<?> lookupClass) {
1631             this(lookupClass, null, FULL_POWER_MODES);
1632         }
1633 
1634         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1635             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1636                     && prevLookupClass.getModule() != lookupClass.getModule());
1637             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1638             this.lookupClass = lookupClass;
1639             this.prevLookupClass = prevLookupClass;
1640             this.allowedModes = allowedModes;
1641         }
1642 
1643         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1644             // make sure we haven't accidentally picked up a privileged class:
1645             checkUnprivilegedlookupClass(lookupClass);
1646             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1647         }
1648 
1649         /**
1650          * Creates a lookup on the specified new lookup class.
1651          * The resulting object will report the specified
1652          * class as its own {@link #lookupClass() lookupClass}.
1653          *
1654          * <p>
1655          * However, the resulting {@code Lookup} object is guaranteed
1656          * to have no more access capabilities than the original.
1657          * In particular, access capabilities can be lost as follows:<ul>
1658          * <li>If the new lookup class is different from the old lookup class,
1659          * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1660          * <li>If the new lookup class is in a different module from the old one,
1661          * i.e. {@link #MODULE MODULE} access is lost.
1662          * <li>If the new lookup class is in a different package
1663          * than the old one, protected and default (package) members will not be accessible,
1664          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1665          * <li>If the new lookup class is not within the same package member
1666          * as the old one, private members will not be accessible, and protected members
1667          * will not be accessible by virtue of inheritance,
1668          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1669          * (Protected members may continue to be accessible because of package sharing.)
1670          * <li>If the new lookup class is not
1671          * {@linkplain #accessClass(Class) accessible} to this lookup,
1672          * then no members, not even public members, will be accessible
1673          * i.e. all access modes are lost.
1674          * <li>If the new lookup class, the old lookup class and the previous lookup class
1675          * are all in different modules i.e. teleporting to a third module,
1676          * all access modes are lost.
1677          * </ul>
1678          * <p>
1679          * The new previous lookup class is chosen as follows:
1680          * <ul>
1681          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1682          * the new previous lookup class is {@code null}.
1683          * <li>If the new lookup class is in the same module as the old lookup class,
1684          * the new previous lookup class is the old previous lookup class.
1685          * <li>If the new lookup class is in a different module from the old lookup class,
1686          * the new previous lookup class is the old lookup class.
1687          *</ul>
1688          * <p>
1689          * The resulting lookup's capabilities for loading classes
1690          * (used during {@link #findClass} invocations)
1691          * are determined by the lookup class' loader,
1692          * which may change due to this operation.
1693          *
1694          * @param requestedLookupClass the desired lookup class for the new lookup object
1695          * @return a lookup object which reports the desired lookup class, or the same object
1696          * if there is no change
1697          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1698          * @throws NullPointerException if the argument is null
1699          *
1700          * @see #accessClass(Class)
1701          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1702          */
1703         public Lookup in(Class<?> requestedLookupClass) {
1704             Objects.requireNonNull(requestedLookupClass);
1705             if (requestedLookupClass.isPrimitive())
1706                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1707             if (requestedLookupClass.isArray())
1708                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1709 
1710             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1711                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1712             if (requestedLookupClass == this.lookupClass)
1713                 return this;  // keep same capabilities
1714             int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1715             Module fromModule = this.lookupClass.getModule();
1716             Module targetModule = requestedLookupClass.getModule();
1717             Class<?> plc = this.previousLookupClass();
1718             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1719                 assert plc == null;
1720                 newModes = UNCONDITIONAL;
1721             } else if (fromModule != targetModule) {
1722                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1723                     // allow hopping back and forth between fromModule and plc's module
1724                     // but not the third module
1725                     newModes = 0;
1726                 }
1727                 // drop MODULE access
1728                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1729                 // teleport from this lookup class
1730                 plc = this.lookupClass;
1731             }
1732             if ((newModes & PACKAGE) != 0
1733                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1734                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1735             }
1736             // Allow nestmate lookups to be created without special privilege:
1737             if ((newModes & PRIVATE) != 0
1738                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1739                 newModes &= ~(PRIVATE|PROTECTED);
1740             }
1741             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1742                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1743                 // The requested class it not accessible from the lookup class.
1744                 // No permissions.
1745                 newModes = 0;
1746             }
1747             return newLookup(requestedLookupClass, plc, newModes);
1748         }
1749 
1750         /**
1751          * Creates a lookup on the same lookup class which this lookup object
1752          * finds members, but with a lookup mode that has lost the given lookup mode.
1753          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1754          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1755          * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1756          * {@link #UNCONDITIONAL UNCONDITIONAL}.
1757          *
1758          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1759          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1760          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1761          * lookup has no access.
1762          *
1763          * <p> If this lookup is not a public lookup, then the following applies
1764          * regardless of its {@linkplain #lookupModes() lookup modes}.
1765          * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1766          * dropped and so the resulting lookup mode will never have these access
1767          * capabilities. When dropping {@code PACKAGE}
1768          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1769          * access. When dropping {@code MODULE} then the resulting lookup will not
1770          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1771          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1772          *
1773          * @apiNote
1774          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1775          * delegate non-public access within the package of the lookup class without
1776          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1777          * A lookup with {@code MODULE} but not
1778          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1779          * the module of the lookup class without conferring package access.
1780          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1781          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1782          * to public classes accessible to both the module of the lookup class
1783          * and the module of the previous lookup class.
1784          *
1785          * @param modeToDrop the lookup mode to drop
1786          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1787          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1788          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1789          * or {@code UNCONDITIONAL}
1790          * @see MethodHandles#privateLookupIn
1791          * @since 9
1792          */
1793         public Lookup dropLookupMode(int modeToDrop) {
1794             int oldModes = lookupModes();
1795             int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1796             switch (modeToDrop) {
1797                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1798                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1799                 case PACKAGE: newModes &= ~(PRIVATE); break;
1800                 case PROTECTED:
1801                 case PRIVATE:
1802                 case ORIGINAL:
1803                 case UNCONDITIONAL: break;
1804                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1805             }
1806             if (newModes == oldModes) return this;  // return self if no change
1807             return newLookup(lookupClass(), previousLookupClass(), newModes);
1808         }
1809 
1810         /**
1811          * Creates and links a class or interface from {@code bytes}
1812          * with the same class loader and in the same runtime package and
1813          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1814          * {@linkplain #lookupClass() lookup class} as if calling
1815          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1816          * ClassLoader::defineClass}.
1817          *
1818          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1819          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1820          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1821          * that the lookup object was created by a caller in the runtime package (or derived
1822          * from a lookup originally created by suitably privileged code to a target class in
1823          * the runtime package). </p>
1824          *
1825          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1826          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1827          * same package as the lookup class. </p>
1828          *
1829          * <p> This method does not run the class initializer. The class initializer may
1830          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1831          * Specification</em>. </p>
1832          *
1833          * <p> If there is a security manager and this lookup does not have {@linkplain
1834          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1835          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1836          *
1837          * @param bytes the class bytes
1838          * @return the {@code Class} object for the class
1839          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1840          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1841          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1842          * than the lookup class or {@code bytes} is not a class or interface
1843          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1844          * @throws VerifyError if the newly created class cannot be verified
1845          * @throws LinkageError if the newly created class cannot be linked for any other reason
1846          * @throws SecurityException if a security manager is present and it
1847          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1848          * @throws NullPointerException if {@code bytes} is {@code null}
1849          * @since 9
1850          * @see Lookup#privateLookupIn
1851          * @see Lookup#dropLookupMode
1852          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1853          */
1854         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1855             ensureDefineClassPermission();
1856             if ((lookupModes() & PACKAGE) == 0)
1857                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1858             return makeClassDefiner(bytes.clone()).defineClass(false);
1859         }
1860 
1861         private void ensureDefineClassPermission() {
1862             if (allowedModes == TRUSTED)  return;
1863 
1864             if (!hasFullPrivilegeAccess()) {
1865                 @SuppressWarnings("removal")
1866                 SecurityManager sm = System.getSecurityManager();
1867                 if (sm != null)
1868                     sm.checkPermission(new RuntimePermission("defineClass"));
1869             }
1870         }
1871 
1872         /**
1873          * The set of class options that specify whether a hidden class created by
1874          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1875          * Lookup::defineHiddenClass} method is dynamically added as a new member
1876          * to the nest of a lookup class and/or whether a hidden class has
1877          * a strong relationship with the class loader marked as its defining loader.
1878          *
1879          * @since 15
1880          */
1881         public enum ClassOption {
1882             /**
1883              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1884              * of a lookup class as a nestmate.
1885              *
1886              * <p> A hidden nestmate class has access to the private members of all
1887              * classes and interfaces in the same nest.
1888              *
1889              * @see Class#getNestHost()
1890              */
1891             NESTMATE(NESTMATE_CLASS),
1892 
1893             /**
1894              * Specifies that a hidden class has a <em>strong</em>
1895              * relationship with the class loader marked as its defining loader,
1896              * as a normal class or interface has with its own defining loader.
1897              * This means that the hidden class may be unloaded if and only if
1898              * its defining loader is not reachable and thus may be reclaimed
1899              * by a garbage collector (JLS {@jls 12.7}).
1900              *
1901              * <p> By default, a hidden class or interface may be unloaded
1902              * even if the class loader that is marked as its defining loader is
1903              * <a href="../ref/package-summary.html#reachability">reachable</a>.
1904 
1905              *
1906              * @jls 12.7 Unloading of Classes and Interfaces
1907              */
1908             STRONG(STRONG_LOADER_LINK);
1909 
1910             /* the flag value is used by VM at define class time */
1911             private final int flag;
1912             ClassOption(int flag) {
1913                 this.flag = flag;
1914             }
1915 
1916             static int optionsToFlag(Set<ClassOption> options) {
1917                 int flags = 0;
1918                 for (ClassOption cp : options) {
1919                     flags |= cp.flag;
1920                 }
1921                 return flags;
1922             }
1923         }
1924 
1925         /**
1926          * Creates a <em>hidden</em> class or interface from {@code bytes},
1927          * returning a {@code Lookup} on the newly created class or interface.
1928          *
1929          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1930          * which either defines {@code C} directly or delegates to another class loader.
1931          * A class loader defines {@code C} directly by invoking
1932          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1933          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1934          * to derive {@code C} from a purported representation in {@code class} file format.
1935          * In situations where use of a class loader is undesirable, a class or interface
1936          * {@code C} can be created by this method instead. This method is capable of
1937          * defining {@code C}, and thereby creating it, without invoking
1938          * {@code ClassLoader::defineClass}.
1939          * Instead, this method defines {@code C} as if by arranging for
1940          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1941          * from a purported representation in {@code class} file format
1942          * using the following rules:
1943          *
1944          * <ol>
1945          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1946          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1947          * This level of access is needed to create {@code C} in the module
1948          * of the lookup class of this {@code Lookup}.</li>
1949          *
1950          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1951          * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1952          * The major and minor version may differ from the {@code class} file version
1953          * of the lookup class of this {@code Lookup}.</li>
1954          *
1955          * <li> The value of {@code this_class} must be a valid index in the
1956          * {@code constant_pool} table, and the entry at that index must be a valid
1957          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1958          * encoded in internal form that is specified by this structure. {@code N} must
1959          * denote a class or interface in the same package as the lookup class.</li>
1960          *
1961          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1962          * where {@code <suffix>} is an unqualified name.
1963          *
1964          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1965          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1966          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1967          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1968          * refers to the new {@code CONSTANT_Utf8_info} structure.
1969          *
1970          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1971          *
1972          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1973          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1974          * with the following adjustments:
1975          * <ul>
1976          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1977          * that includes a single {@code "."} character, even though this is not a valid
1978          * binary class or interface name in internal form.</li>
1979          *
1980          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1981          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1982          *
1983          * <li> {@code C} is considered to have the same runtime
1984          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1985          * and {@linkplain java.security.ProtectionDomain protection domain}
1986          * as the lookup class of this {@code Lookup}.
1987          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1988          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1989          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1990          * <ul>
1991          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1992          *      even though this is not a valid binary class or interface name.</li>
1993          * <li> {@link Class#descriptorString()} returns the string
1994          *      {@code "L" + N + "." + <suffix> + ";"},
1995          *      even though this is not a valid type descriptor name.</li>
1996          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
1997          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
1998          * </ul>
1999          * </ul>
2000          * </li>
2001          * </ol>
2002          *
2003          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
2004          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
2005          * <ul>
2006          * <li> During verification, whenever it is necessary to load the class named
2007          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
2008          * made of any class loader.</li>
2009          *
2010          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
2011          * by {@code this_class}, the symbolic reference is considered to be resolved to
2012          * {@code C} and resolution always succeeds immediately.</li>
2013          * </ul>
2014          *
2015          * <p> If the {@code initialize} parameter is {@code true},
2016          * then {@code C} is initialized by the Java Virtual Machine.
2017          *
2018          * <p> The newly created class or interface {@code C} serves as the
2019          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
2020          * returned by this method. {@code C} is <em>hidden</em> in the sense that
2021          * no other class or interface can refer to {@code C} via a constant pool entry.
2022          * That is, a hidden class or interface cannot be named as a supertype, a field type,
2023          * a method parameter type, or a method return type by any other class.
2024          * This is because a hidden class or interface does not have a binary name, so
2025          * there is no internal form available to record in any class's constant pool.
2026          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
2027          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
2028          * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class)
2029          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
2030          * JVM Tool Interface</a>.
2031          *
2032          * <p> A class or interface created by
2033          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
2034          * a class loader} has a strong relationship with that class loader.
2035          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
2036          * that {@linkplain Class#getClassLoader() defined it}.
2037          * This means that a class created by a class loader may be unloaded if and
2038          * only if its defining loader is not reachable and thus may be reclaimed
2039          * by a garbage collector (JLS {@jls 12.7}).
2040          *
2041          * By default, however, a hidden class or interface may be unloaded even if
2042          * the class loader that is marked as its defining loader is
2043          * <a href="../ref/package-summary.html#reachability">reachable</a>.
2044          * This behavior is useful when a hidden class or interface serves multiple
2045          * classes defined by arbitrary class loaders.  In other cases, a hidden
2046          * class or interface may be linked to a single class (or a small number of classes)
2047          * with the same defining loader as the hidden class or interface.
2048          * In such cases, where the hidden class or interface must be coterminous
2049          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
2050          * option may be passed in {@code options}.
2051          * This arranges for a hidden class to have the same strong relationship
2052          * with the class loader marked as its defining loader,
2053          * as a normal class or interface has with its own defining loader.
2054          *
2055          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
2056          * may still prevent a hidden class or interface from being
2057          * unloaded by ensuring that the {@code Class} object is reachable.
2058          *
2059          * <p> The unloading characteristics are set for each hidden class when it is
2060          * defined, and cannot be changed later.  An advantage of allowing hidden classes
2061          * to be unloaded independently of the class loader marked as their defining loader
2062          * is that a very large number of hidden classes may be created by an application.
2063          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
2064          * just as if normal classes were created by class loaders.
2065          *
2066          * <p> Classes and interfaces in a nest are allowed to have mutual access to
2067          * their private members.  The nest relationship is determined by
2068          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
2069          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
2070          * By default, a hidden class belongs to a nest consisting only of itself
2071          * because a hidden class has no binary name.
2072          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
2073          * to create a hidden class or interface {@code C} as a member of a nest.
2074          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
2075          * in the {@code ClassFile} structure from which {@code C} was derived.
2076          * Instead, the following rules determine the nest host of {@code C}:
2077          * <ul>
2078          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
2079          *     been determined, then let {@code H} be the nest host of the lookup class.
2080          *     Otherwise, the nest host of the lookup class is determined using the
2081          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
2082          * <li>The nest host of {@code C} is determined to be {@code H},
2083          *     the nest host of the lookup class.</li>
2084          * </ul>
2085          *
2086          * <p> A hidden class or interface may be serializable, but this requires a custom
2087          * serialization mechanism in order to ensure that instances are properly serialized
2088          * and deserialized. The default serialization mechanism supports only classes and
2089          * interfaces that are discoverable by their class name.
2090          *
2091          * @param bytes the bytes that make up the class data,
2092          * in the format of a valid {@code class} file as defined by
2093          * <cite>The Java Virtual Machine Specification</cite>.
2094          * @param initialize if {@code true} the class will be initialized.
2095          * @param options {@linkplain ClassOption class options}
2096          * @return the {@code Lookup} object on the hidden class,
2097          * with {@linkplain #ORIGINAL original} and
2098          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2099          *
2100          * @throws IllegalAccessException if this {@code Lookup} does not have
2101          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2102          * @throws SecurityException if a security manager is present and it
2103          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2104          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2105          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2106          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2107          * than the lookup class or {@code bytes} is not a class or interface
2108          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2109          * @throws IncompatibleClassChangeError if the class or interface named as
2110          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2111          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2112          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2113          * {@code C} is {@code C} itself
2114          * @throws VerifyError if the newly created class cannot be verified
2115          * @throws LinkageError if the newly created class cannot be linked for any other reason
2116          * @throws NullPointerException if any parameter is {@code null}
2117          *
2118          * @since 15
2119          * @see Class#isHidden()
2120          * @jvms 4.2.1 Binary Class and Interface Names
2121          * @jvms 4.2.2 Unqualified Names
2122          * @jvms 4.7.28 The {@code NestHost} Attribute
2123          * @jvms 4.7.29 The {@code NestMembers} Attribute
2124          * @jvms 5.4.3.1 Class and Interface Resolution
2125          * @jvms 5.4.4 Access Control
2126          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2127          * @jvms 5.4 Linking
2128          * @jvms 5.5 Initialization
2129          * @jls 12.7 Unloading of Classes and Interfaces
2130          */
2131         @SuppressWarnings("doclint:reference") // cross-module links
2132         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2133                 throws IllegalAccessException
2134         {
2135             Objects.requireNonNull(bytes);
2136             Objects.requireNonNull(options);
2137 
2138             ensureDefineClassPermission();
2139             if (!hasFullPrivilegeAccess()) {
2140                 throw new IllegalAccessException(this + " does not have full privilege access");
2141             }
2142 
2143             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
2144         }
2145 
2146         /**
2147          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2148          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2149          * returning a {@code Lookup} on the newly created class or interface.
2150          *
2151          * <p> This method is equivalent to calling
2152          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2153          * as if the hidden class is injected with a private static final <i>unnamed</i>
2154          * field which is initialized with the given {@code classData} at
2155          * the first instruction of the class initializer.
2156          * The newly created class is linked by the Java Virtual Machine.
2157          *
2158          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2159          * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2160          * methods can be used to retrieve the {@code classData}.
2161          *
2162          * @apiNote
2163          * A framework can create a hidden class with class data with one or more
2164          * objects and load the class data as dynamically-computed constant(s)
2165          * via a bootstrap method.  {@link MethodHandles#classData(Lookup, String, Class)
2166          * Class data} is accessible only to the lookup object created by the newly
2167          * defined hidden class but inaccessible to other members in the same nest
2168          * (unlike private static fields that are accessible to nestmates).
2169          * Care should be taken w.r.t. mutability for example when passing
2170          * an array or other mutable structure through the class data.
2171          * Changing any value stored in the class data at runtime may lead to
2172          * unpredictable behavior.
2173          * If the class data is a {@code List}, it is good practice to make it
2174          * unmodifiable for example via {@link List#of List::of}.
2175          *
2176          * @param bytes     the class bytes
2177          * @param classData pre-initialized class data
2178          * @param initialize if {@code true} the class will be initialized.
2179          * @param options   {@linkplain ClassOption class options}
2180          * @return the {@code Lookup} object on the hidden class,
2181          * with {@linkplain #ORIGINAL original} and
2182          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2183          *
2184          * @throws IllegalAccessException if this {@code Lookup} does not have
2185          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2186          * @throws SecurityException if a security manager is present and it
2187          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2188          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2189          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2190          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2191          * than the lookup class or {@code bytes} is not a class or interface
2192          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2193          * @throws IncompatibleClassChangeError if the class or interface named as
2194          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2195          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2196          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2197          * {@code C} is {@code C} itself
2198          * @throws VerifyError if the newly created class cannot be verified
2199          * @throws LinkageError if the newly created class cannot be linked for any other reason
2200          * @throws NullPointerException if any parameter is {@code null}
2201          *
2202          * @since 16
2203          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2204          * @see Class#isHidden()
2205          * @see MethodHandles#classData(Lookup, String, Class)
2206          * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2207          * @jvms 4.2.1 Binary Class and Interface Names
2208          * @jvms 4.2.2 Unqualified Names
2209          * @jvms 4.7.28 The {@code NestHost} Attribute
2210          * @jvms 4.7.29 The {@code NestMembers} Attribute
2211          * @jvms 5.4.3.1 Class and Interface Resolution
2212          * @jvms 5.4.4 Access Control
2213          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2214          * @jvms 5.4 Linking
2215          * @jvms 5.5 Initialization
2216          * @jls 12.7 Unloading of Classes and Interface
2217          */
2218         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2219                 throws IllegalAccessException
2220         {
2221             Objects.requireNonNull(bytes);
2222             Objects.requireNonNull(classData);
2223             Objects.requireNonNull(options);
2224 
2225             ensureDefineClassPermission();
2226             if (!hasFullPrivilegeAccess()) {
2227                 throw new IllegalAccessException(this + " does not have full privilege access");
2228             }
2229 
2230             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2231                        .defineClassAsLookup(initialize, classData);
2232         }
2233 
2234         // A default dumper for writing class files passed to Lookup::defineClass
2235         // and Lookup::defineHiddenClass to disk for debugging purposes.  To enable,
2236         // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or
2237         //     -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true
2238         //
2239         // This default dumper does not dump hidden classes defined by LambdaMetafactory
2240         // and LambdaForms and method handle internals.  They are dumped via
2241         // different ClassFileDumpers.
2242         private static ClassFileDumper defaultDumper() {
2243             return DEFAULT_DUMPER;
2244         }
2245 
2246         private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance(
2247                 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES");
2248 
2249         static class ClassFile {
2250             final String name;  // internal name
2251             final int accessFlags;
2252             final byte[] bytes;
2253             ClassFile(String name, int accessFlags, byte[] bytes) {
2254                 this.name = name;
2255                 this.accessFlags = accessFlags;
2256                 this.bytes = bytes;
2257             }
2258 
2259             static ClassFile newInstanceNoCheck(String name, byte[] bytes) {
2260                 return new ClassFile(name, 0, bytes);
2261             }
2262 
2263             /**
2264              * This method checks the class file version and the structure of `this_class`.
2265              * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2266              * that is in the named package.
2267              *
2268              * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2269              * or the class is not in the given package name.
2270              */
2271             static ClassFile newInstance(byte[] bytes, String pkgName) {
2272                 var cf = readClassFile(bytes);
2273 
2274                 // check if it's in the named package
2275                 int index = cf.name.lastIndexOf('/');
2276                 String pn = (index == -1) ? "" : cf.name.substring(0, index).replace('/', '.');
2277                 if (!pn.equals(pkgName)) {
2278                     throw newIllegalArgumentException(cf.name + " not in same package as lookup class");
2279                 }
2280                 return cf;
2281             }
2282 
2283             private static ClassFile readClassFile(byte[] bytes) {
2284                 int magic = readInt(bytes, 0);
2285                 if (magic != 0xCAFEBABE) {
2286                     throw new ClassFormatError("Incompatible magic value: " + magic);
2287                 }
2288                 int minor = readUnsignedShort(bytes, 4);
2289                 int major = readUnsignedShort(bytes, 6);
2290                 if (!VM.isSupportedClassFileVersion(major, minor)) {
2291                     throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2292                 }
2293 
2294                 String name;
2295                 int accessFlags;
2296                 try {
2297                     ClassReader reader = new ClassReader(bytes);
2298                     // ClassReader does not check if `this_class` is CONSTANT_Class_info
2299                     // workaround to read `this_class` using readConst and validate the value
2300                     int thisClass = reader.readUnsignedShort(reader.header + 2);
2301                     Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]);
2302                     if (!(constant instanceof Type type)) {
2303                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2304                     }
2305                     if (!type.getDescriptor().startsWith("L")) {
2306                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2307                     }
2308                     name = type.getInternalName();
2309                     accessFlags = reader.readUnsignedShort(reader.header);
2310                 } catch (RuntimeException e) {
2311                     // ASM exceptions are poorly specified
2312                     ClassFormatError cfe = new ClassFormatError();
2313                     cfe.initCause(e);
2314                     throw cfe;
2315                 }
2316                 // must be a class or interface
2317                 if ((accessFlags & Opcodes.ACC_MODULE) != 0) {
2318                     throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2319                 }
2320                 return new ClassFile(name, accessFlags, bytes);
2321             }
2322 
2323             private static int readInt(byte[] bytes, int offset) {
2324                 if ((offset+4) > bytes.length) {
2325                     throw new ClassFormatError("Invalid ClassFile structure");
2326                 }
2327                 return ((bytes[offset] & 0xFF) << 24)
2328                         | ((bytes[offset + 1] & 0xFF) << 16)
2329                         | ((bytes[offset + 2] & 0xFF) << 8)
2330                         | (bytes[offset + 3] & 0xFF);
2331             }
2332 
2333             private static int readUnsignedShort(byte[] bytes, int offset) {
2334                 if ((offset+2) > bytes.length) {
2335                     throw new ClassFormatError("Invalid ClassFile structure");
2336                 }
2337                 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2338             }
2339         }
2340 
2341         /*
2342          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2343          * from the given bytes.
2344          *
2345          * Caller should make a defensive copy of the arguments if needed
2346          * before calling this factory method.
2347          *
2348          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2349          * {@code bytes} denotes a class in a different package than the lookup class
2350          */
2351         private ClassDefiner makeClassDefiner(byte[] bytes) {
2352             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2353             return new ClassDefiner(this, cf, STRONG_LOADER_LINK, defaultDumper());
2354         }
2355 
2356         /**
2357          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2358          * from the given bytes.  No package name check on the given bytes.
2359          *
2360          * @param name    internal name
2361          * @param bytes   class bytes
2362          * @param dumper  dumper to write the given bytes to the dumper's output directory
2363          * @return ClassDefiner that defines a normal class of the given bytes.
2364          */
2365         ClassDefiner makeClassDefiner(String name, byte[] bytes, ClassFileDumper dumper) {
2366             // skip package name validation
2367             ClassFile cf = ClassFile.newInstanceNoCheck(name, bytes);
2368             return new ClassDefiner(this, cf, STRONG_LOADER_LINK, dumper);
2369         }
2370 
2371         /**
2372          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2373          * from the given bytes.  The name must be in the same package as the lookup class.
2374          *
2375          * Caller should make a defensive copy of the arguments if needed
2376          * before calling this factory method.
2377          *
2378          * @param bytes   class bytes
2379          * @param dumper dumper to write the given bytes to the dumper's output directory
2380          * @return ClassDefiner that defines a hidden class of the given bytes.
2381          *
2382          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2383          * {@code bytes} denotes a class in a different package than the lookup class
2384          */
2385         ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) {
2386             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2387             return makeHiddenClassDefiner(cf, Set.of(), false, dumper);
2388         }
2389 
2390         /**
2391          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2392          * from the given bytes and options.
2393          * The name must be in the same package as the lookup class.
2394          *
2395          * Caller should make a defensive copy of the arguments if needed
2396          * before calling this factory method.
2397          *
2398          * @param bytes   class bytes
2399          * @param options class options
2400          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2401          * @return ClassDefiner that defines a hidden class of the given bytes and options
2402          *
2403          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2404          * {@code bytes} denotes a class in a different package than the lookup class
2405          */
2406         private ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2407                                                     Set<ClassOption> options,
2408                                                     boolean accessVmAnnotations) {
2409             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2410             return makeHiddenClassDefiner(cf, options, accessVmAnnotations, defaultDumper());
2411         }
2412 
2413         /**
2414          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2415          * from the given bytes and the given options.  No package name check on the given bytes.
2416          *
2417          * @param name    internal name that specifies the prefix of the hidden class
2418          * @param bytes   class bytes
2419          * @param options class options
2420          * @param dumper  dumper to write the given bytes to the dumper's output directory
2421          * @return ClassDefiner that defines a hidden class of the given bytes and options.
2422          */
2423         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options, ClassFileDumper dumper) {
2424             Objects.requireNonNull(dumper);
2425             // skip name and access flags validation
2426             return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false, dumper);
2427         }
2428 
2429         /**
2430          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2431          * from the given class file and options.
2432          *
2433          * @param cf ClassFile
2434          * @param options class options
2435          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2436          * @param dumper dumper to write the given bytes to the dumper's output directory
2437          */
2438         private ClassDefiner makeHiddenClassDefiner(ClassFile cf,
2439                                                     Set<ClassOption> options,
2440                                                     boolean accessVmAnnotations,
2441                                                     ClassFileDumper dumper) {
2442             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2443             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2444                 // jdk.internal.vm.annotations are permitted for classes
2445                 // defined to boot loader and platform loader
2446                 flags |= ACCESS_VM_ANNOTATIONS;
2447             }
2448 
2449             return new ClassDefiner(this, cf, flags, dumper);
2450         }
2451 
2452         static class ClassDefiner {
2453             private final Lookup lookup;
2454             private final String name;  // internal name
2455             private final byte[] bytes;
2456             private final int classFlags;
2457             private final ClassFileDumper dumper;
2458 
2459             private ClassDefiner(Lookup lookup, ClassFile cf, int flags, ClassFileDumper dumper) {
2460                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2461                 this.lookup = lookup;
2462                 this.bytes = cf.bytes;
2463                 this.name = cf.name;
2464                 this.classFlags = flags;
2465                 this.dumper = dumper;
2466             }
2467 
2468             String internalName() {
2469                 return name;
2470             }
2471 
2472             Class<?> defineClass(boolean initialize) {
2473                 return defineClass(initialize, null);
2474             }
2475 
2476             Lookup defineClassAsLookup(boolean initialize) {
2477                 Class<?> c = defineClass(initialize, null);
2478                 return new Lookup(c, null, FULL_POWER_MODES);
2479             }
2480 
2481             /**
2482              * Defines the class of the given bytes and the given classData.
2483              * If {@code initialize} parameter is true, then the class will be initialized.
2484              *
2485              * @param initialize true if the class to be initialized
2486              * @param classData classData or null
2487              * @return the class
2488              *
2489              * @throws LinkageError linkage error
2490              */
2491             Class<?> defineClass(boolean initialize, Object classData) {
2492                 Class<?> lookupClass = lookup.lookupClass();
2493                 ClassLoader loader = lookupClass.getClassLoader();
2494                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2495                 Class<?> c = null;
2496                 try {
2497                     c = SharedSecrets.getJavaLangAccess()
2498                             .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2499                     assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2500                     return c;
2501                 } finally {
2502                     // dump the classfile for debugging
2503                     if (dumper.isEnabled()) {
2504                         String name = internalName();
2505                         if (c != null) {
2506                             dumper.dumpClass(name, c, bytes);
2507                         } else {
2508                             dumper.dumpFailedClass(name, bytes);
2509                         }
2510                     }
2511                 }
2512             }
2513 
2514             /**
2515              * Defines the class of the given bytes and the given classData.
2516              * If {@code initialize} parameter is true, then the class will be initialized.
2517              *
2518              * @param initialize true if the class to be initialized
2519              * @param classData classData or null
2520              * @return a Lookup for the defined class
2521              *
2522              * @throws LinkageError linkage error
2523              */
2524             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2525                 Class<?> c = defineClass(initialize, classData);
2526                 return new Lookup(c, null, FULL_POWER_MODES);
2527             }
2528 
2529             private boolean isNestmate() {
2530                 return (classFlags & NESTMATE_CLASS) != 0;
2531             }
2532         }
2533 
2534         private ProtectionDomain lookupClassProtectionDomain() {
2535             ProtectionDomain pd = cachedProtectionDomain;
2536             if (pd == null) {
2537                 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2538             }
2539             return pd;
2540         }
2541 
2542         // cached protection domain
2543         private volatile ProtectionDomain cachedProtectionDomain;
2544 
2545         // Make sure outer class is initialized first.
2546         static { IMPL_NAMES.getClass(); }
2547 
2548         /** Package-private version of lookup which is trusted. */
2549         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2550 
2551         /** Version of lookup which is trusted minimally.
2552          *  It can only be used to create method handles to publicly accessible
2553          *  members in packages that are exported unconditionally.
2554          */
2555         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2556 
2557         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2558             String name = lookupClass.getName();
2559             if (name.startsWith("java.lang.invoke."))
2560                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2561         }
2562 
2563         /**
2564          * Displays the name of the class from which lookups are to be made,
2565          * followed by "/" and the name of the {@linkplain #previousLookupClass()
2566          * previous lookup class} if present.
2567          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2568          * If there are restrictions on the access permitted to this lookup,
2569          * this is indicated by adding a suffix to the class name, consisting
2570          * of a slash and a keyword.  The keyword represents the strongest
2571          * allowed access, and is chosen as follows:
2572          * <ul>
2573          * <li>If no access is allowed, the suffix is "/noaccess".
2574          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2575          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2576          * <li>If only public and module access are allowed, the suffix is "/module".
2577          * <li>If public and package access are allowed, the suffix is "/package".
2578          * <li>If public, package, and private access are allowed, the suffix is "/private".
2579          * </ul>
2580          * If none of the above cases apply, it is the case that
2581          * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2582          * (public, module, package, private, and protected) is allowed.
2583          * In this case, no suffix is added.
2584          * This is true only of an object obtained originally from
2585          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2586          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2587          * always have restricted access, and will display a suffix.
2588          * <p>
2589          * (It may seem strange that protected access should be
2590          * stronger than private access.  Viewed independently from
2591          * package access, protected access is the first to be lost,
2592          * because it requires a direct subclass relationship between
2593          * caller and callee.)
2594          * @see #in
2595          */
2596         @Override
2597         public String toString() {
2598             String cname = lookupClass.getName();
2599             if (prevLookupClass != null)
2600                 cname += "/" + prevLookupClass.getName();
2601             switch (allowedModes) {
2602             case 0:  // no privileges
2603                 return cname + "/noaccess";
2604             case UNCONDITIONAL:
2605                 return cname + "/publicLookup";
2606             case PUBLIC:
2607                 return cname + "/public";
2608             case PUBLIC|MODULE:
2609                 return cname + "/module";
2610             case PUBLIC|PACKAGE:
2611             case PUBLIC|MODULE|PACKAGE:
2612                 return cname + "/package";
2613             case PUBLIC|PACKAGE|PRIVATE:
2614             case PUBLIC|MODULE|PACKAGE|PRIVATE:
2615                     return cname + "/private";
2616             case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2617             case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2618             case FULL_POWER_MODES:
2619                     return cname;
2620             case TRUSTED:
2621                 return "/trusted";  // internal only; not exported
2622             default:  // Should not happen, but it's a bitfield...
2623                 cname = cname + "/" + Integer.toHexString(allowedModes);
2624                 assert(false) : cname;
2625                 return cname;
2626             }
2627         }
2628 
2629         /**
2630          * Produces a method handle for a static method.
2631          * The type of the method handle will be that of the method.
2632          * (Since static methods do not take receivers, there is no
2633          * additional receiver argument inserted into the method handle type,
2634          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2635          * The method and all its argument types must be accessible to the lookup object.
2636          * <p>
2637          * The returned method handle will have
2638          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2639          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2640          * <p>
2641          * If the returned method handle is invoked, the method's class will
2642          * be initialized, if it has not already been initialized.
2643          * <p><b>Example:</b>
2644          * {@snippet lang="java" :
2645 import static java.lang.invoke.MethodHandles.*;
2646 import static java.lang.invoke.MethodType.*;
2647 ...
2648 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2649   "asList", methodType(List.class, Object[].class));
2650 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2651          * }
2652          * @param refc the class from which the method is accessed
2653          * @param name the name of the method
2654          * @param type the type of the method
2655          * @return the desired method handle
2656          * @throws NoSuchMethodException if the method does not exist
2657          * @throws IllegalAccessException if access checking fails,
2658          *                                or if the method is not {@code static},
2659          *                                or if the method's variable arity modifier bit
2660          *                                is set and {@code asVarargsCollector} fails
2661          * @throws    SecurityException if a security manager is present and it
2662          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2663          * @throws NullPointerException if any argument is null
2664          */
2665         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2666             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2667             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2668         }
2669 
2670         /**
2671          * Produces a method handle for a virtual method.
2672          * The type of the method handle will be that of the method,
2673          * with the receiver type (usually {@code refc}) prepended.
2674          * The method and all its argument types must be accessible to the lookup object.
2675          * <p>
2676          * When called, the handle will treat the first argument as a receiver
2677          * and, for non-private methods, dispatch on the receiver's type to determine which method
2678          * implementation to enter.
2679          * For private methods the named method in {@code refc} will be invoked on the receiver.
2680          * (The dispatching action is identical with that performed by an
2681          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2682          * <p>
2683          * The first argument will be of type {@code refc} if the lookup
2684          * class has full privileges to access the member.  Otherwise
2685          * the member must be {@code protected} and the first argument
2686          * will be restricted in type to the lookup class.
2687          * <p>
2688          * The returned method handle will have
2689          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2690          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2691          * <p>
2692          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2693          * instructions and method handles produced by {@code findVirtual},
2694          * if the class is {@code MethodHandle} and the name string is
2695          * {@code invokeExact} or {@code invoke}, the resulting
2696          * method handle is equivalent to one produced by
2697          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2698          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2699          * with the same {@code type} argument.
2700          * <p>
2701          * If the class is {@code VarHandle} and the name string corresponds to
2702          * the name of a signature-polymorphic access mode method, the resulting
2703          * method handle is equivalent to one produced by
2704          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2705          * the access mode corresponding to the name string and with the same
2706          * {@code type} arguments.
2707          * <p>
2708          * <b>Example:</b>
2709          * {@snippet lang="java" :
2710 import static java.lang.invoke.MethodHandles.*;
2711 import static java.lang.invoke.MethodType.*;
2712 ...
2713 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2714   "concat", methodType(String.class, String.class));
2715 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2716   "hashCode", methodType(int.class));
2717 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2718   "hashCode", methodType(int.class));
2719 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2720 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2721 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2722 // interface method:
2723 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2724   "subSequence", methodType(CharSequence.class, int.class, int.class));
2725 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2726 // constructor "internal method" must be accessed differently:
2727 MethodType MT_newString = methodType(void.class); //()V for new String()
2728 try { assertEquals("impossible", lookup()
2729         .findVirtual(String.class, "<init>", MT_newString));
2730  } catch (NoSuchMethodException ex) { } // OK
2731 MethodHandle MH_newString = publicLookup()
2732   .findConstructor(String.class, MT_newString);
2733 assertEquals("", (String) MH_newString.invokeExact());
2734          * }
2735          *
2736          * @param refc the class or interface from which the method is accessed
2737          * @param name the name of the method
2738          * @param type the type of the method, with the receiver argument omitted
2739          * @return the desired method handle
2740          * @throws NoSuchMethodException if the method does not exist
2741          * @throws IllegalAccessException if access checking fails,
2742          *                                or if the method is {@code static},
2743          *                                or if the method's variable arity modifier bit
2744          *                                is set and {@code asVarargsCollector} fails
2745          * @throws    SecurityException if a security manager is present and it
2746          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2747          * @throws NullPointerException if any argument is null
2748          */
2749         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2750             if (refc == MethodHandle.class) {
2751                 MethodHandle mh = findVirtualForMH(name, type);
2752                 if (mh != null)  return mh;
2753             } else if (refc == VarHandle.class) {
2754                 MethodHandle mh = findVirtualForVH(name, type);
2755                 if (mh != null)  return mh;
2756             }
2757             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2758             MemberName method = resolveOrFail(refKind, refc, name, type);
2759             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2760         }
2761         private MethodHandle findVirtualForMH(String name, MethodType type) {
2762             // these names require special lookups because of the implicit MethodType argument
2763             if ("invoke".equals(name))
2764                 return invoker(type);
2765             if ("invokeExact".equals(name))
2766                 return exactInvoker(type);
2767             assert(!MemberName.isMethodHandleInvokeName(name));
2768             return null;
2769         }
2770         private MethodHandle findVirtualForVH(String name, MethodType type) {
2771             try {
2772                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2773             } catch (IllegalArgumentException e) {
2774                 return null;
2775             }
2776         }
2777 
2778         /**
2779          * Produces a method handle which creates an object and initializes it, using
2780          * the constructor of the specified type.
2781          * The parameter types of the method handle will be those of the constructor,
2782          * while the return type will be a reference to the constructor's class.
2783          * The constructor and all its argument types must be accessible to the lookup object.
2784          * <p>
2785          * The requested type must have a return type of {@code void}.
2786          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2787          * <p>
2788          * The returned method handle will have
2789          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2790          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2791          * <p>
2792          * If the returned method handle is invoked, the constructor's class will
2793          * be initialized, if it has not already been initialized.
2794          * <p><b>Example:</b>
2795          * {@snippet lang="java" :
2796 import static java.lang.invoke.MethodHandles.*;
2797 import static java.lang.invoke.MethodType.*;
2798 ...
2799 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2800   ArrayList.class, methodType(void.class, Collection.class));
2801 Collection orig = Arrays.asList("x", "y");
2802 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2803 assert(orig != copy);
2804 assertEquals(orig, copy);
2805 // a variable-arity constructor:
2806 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2807   ProcessBuilder.class, methodType(void.class, String[].class));
2808 ProcessBuilder pb = (ProcessBuilder)
2809   MH_newProcessBuilder.invoke("x", "y", "z");
2810 assertEquals("[x, y, z]", pb.command().toString());
2811          * }
2812          * @param refc the class or interface from which the method is accessed
2813          * @param type the type of the method, with the receiver argument omitted, and a void return type
2814          * @return the desired method handle
2815          * @throws NoSuchMethodException if the constructor does not exist
2816          * @throws IllegalAccessException if access checking fails
2817          *                                or if the method's variable arity modifier bit
2818          *                                is set and {@code asVarargsCollector} fails
2819          * @throws    SecurityException if a security manager is present and it
2820          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2821          * @throws NullPointerException if any argument is null
2822          */
2823         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2824             if (refc.isArray()) {
2825                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2826             }
2827             String name = ConstantDescs.INIT_NAME;
2828             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2829             return getDirectConstructor(refc, ctor);
2830         }
2831 
2832         /**
2833          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2834          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2835          * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2836          * and then determines whether the class is accessible to this lookup object.
2837          * <p>
2838          * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}.
2839          * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences
2840          * of {@code '['} and followed by the element type as encoded in the
2841          * {@linkplain Class##nameFormat table} specified in {@link Class#getName}.
2842          * <p>
2843          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2844          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2845          *
2846          * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class
2847          *                   or the string representing an array class
2848          * @return the requested class.
2849          * @throws SecurityException if a security manager is present and it
2850          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2851          * @throws LinkageError if the linkage fails
2852          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2853          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2854          * modes.
2855          * @throws NullPointerException if {@code targetName} is null
2856          * @since 9
2857          * @jvms 5.4.3.1 Class and Interface Resolution
2858          */
2859         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2860             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2861             return accessClass(targetClass);
2862         }
2863 
2864         /**
2865          * Ensures that {@code targetClass} has been initialized. The class
2866          * to be initialized must be {@linkplain #accessClass accessible}
2867          * to this {@code Lookup} object.  This method causes {@code targetClass}
2868          * to be initialized if it has not been already initialized,
2869          * as specified in JVMS {@jvms 5.5}.
2870          *
2871          * <p>
2872          * This method returns when {@code targetClass} is fully initialized, or
2873          * when {@code targetClass} is being initialized by the current thread.
2874          *
2875          * @param <T> the type of the class to be initialized
2876          * @param targetClass the class to be initialized
2877          * @return {@code targetClass} that has been initialized, or that is being
2878          *         initialized by the current thread.
2879          *
2880          * @throws  IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2881          *          or array class
2882          * @throws  IllegalAccessException if {@code targetClass} is not
2883          *          {@linkplain #accessClass accessible} to this lookup
2884          * @throws  ExceptionInInitializerError if the class initialization provoked
2885          *          by this method fails
2886          * @throws  SecurityException if a security manager is present and it
2887          *          <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2888          * @since 15
2889          * @jvms 5.5 Initialization
2890          */
2891         public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException {
2892             if (targetClass.isPrimitive())
2893                 throw new IllegalArgumentException(targetClass + " is a primitive class");
2894             if (targetClass.isArray())
2895                 throw new IllegalArgumentException(targetClass + " is an array class");
2896 
2897             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2898                 throw makeAccessException(targetClass);
2899             }
2900             checkSecurityManager(targetClass);
2901 
2902             // ensure class initialization
2903             Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2904             return targetClass;
2905         }
2906 
2907         /*
2908          * Returns IllegalAccessException due to access violation to the given targetClass.
2909          *
2910          * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2911          * which verifies access to a class rather a member.
2912          */
2913         private IllegalAccessException makeAccessException(Class<?> targetClass) {
2914             String message = "access violation: "+ targetClass;
2915             if (this == MethodHandles.publicLookup()) {
2916                 message += ", from public Lookup";
2917             } else {
2918                 Module m = lookupClass().getModule();
2919                 message += ", from " + lookupClass() + " (" + m + ")";
2920                 if (prevLookupClass != null) {
2921                     message += ", previous lookup " +
2922                             prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2923                 }
2924             }
2925             return new IllegalAccessException(message);
2926         }
2927 
2928         /**
2929          * Determines if a class can be accessed from the lookup context defined by
2930          * this {@code Lookup} object. The static initializer of the class is not run.
2931          * If {@code targetClass} is an array class, {@code targetClass} is accessible
2932          * if the element type of the array class is accessible.  Otherwise,
2933          * {@code targetClass} is determined as accessible as follows.
2934          *
2935          * <p>
2936          * If {@code targetClass} is in the same module as the lookup class,
2937          * the lookup class is {@code LC} in module {@code M1} and
2938          * the previous lookup class is in module {@code M0} or
2939          * {@code null} if not present,
2940          * {@code targetClass} is accessible if and only if one of the following is true:
2941          * <ul>
2942          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2943          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2944          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2945          *     in the same runtime package of {@code LC}.</li>
2946          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2947          *     a public type in {@code M1}.</li>
2948          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2949          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2950          *     if the previous lookup class is present; otherwise, {@code targetClass}
2951          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2952          * </ul>
2953          *
2954          * <p>
2955          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2956          * can access public types in all modules when the type is in a package
2957          * that is exported unconditionally.
2958          * <p>
2959          * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2960          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2961          * is inaccessible.
2962          * <p>
2963          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2964          * {@code M1} is the module containing {@code lookupClass} and
2965          * {@code M2} is the module containing {@code targetClass},
2966          * then {@code targetClass} is accessible if and only if
2967          * <ul>
2968          * <li>{@code M1} reads {@code M2}, and
2969          * <li>{@code targetClass} is public and in a package exported by
2970          *     {@code M2} at least to {@code M1}.
2971          * </ul>
2972          * <p>
2973          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2974          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2975          * containing the previous lookup class, then {@code targetClass} is accessible
2976          * if and only if one of the following is true:
2977          * <ul>
2978          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2979          *     {@linkplain Module#reads reads} {@code M0} and the type is
2980          *     in a package that is exported to at least {@code M1}.
2981          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2982          *     {@linkplain Module#reads reads} {@code M1} and the type is
2983          *     in a package that is exported to at least {@code M0}.
2984          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2985          *     and {@code M1} reads {@code M2} and the type is in a package
2986          *     that is exported to at least both {@code M0} and {@code M2}.
2987          * </ul>
2988          * <p>
2989          * Otherwise, {@code targetClass} is not accessible.
2990          *
2991          * @param <T> the type of the class to be access-checked
2992          * @param targetClass the class to be access-checked
2993          * @return {@code targetClass} that has been access-checked
2994          * @throws IllegalAccessException if the class is not accessible from the lookup class
2995          * and previous lookup class, if present, using the allowed access modes.
2996          * @throws SecurityException if a security manager is present and it
2997          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2998          * @throws NullPointerException if {@code targetClass} is {@code null}
2999          * @since 9
3000          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
3001          */
3002         public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException {
3003             if (!isClassAccessible(targetClass)) {
3004                 throw makeAccessException(targetClass);
3005             }
3006             checkSecurityManager(targetClass);
3007             return targetClass;
3008         }
3009 
3010         /**
3011          * Produces an early-bound method handle for a virtual method.
3012          * It will bypass checks for overriding methods on the receiver,
3013          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3014          * instruction from within the explicitly specified {@code specialCaller}.
3015          * The type of the method handle will be that of the method,
3016          * with a suitably restricted receiver type prepended.
3017          * (The receiver type will be {@code specialCaller} or a subtype.)
3018          * The method and all its argument types must be accessible
3019          * to the lookup object.
3020          * <p>
3021          * Before method resolution,
3022          * if the explicitly specified caller class is not identical with the
3023          * lookup class, or if this lookup object does not have
3024          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3025          * privileges, the access fails.
3026          * <p>
3027          * The returned method handle will have
3028          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3029          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3030          * <p style="font-size:smaller;">
3031          * <em>(Note:  JVM internal methods named {@value ConstantDescs#INIT_NAME}
3032          * are not visible to this API,
3033          * even though the {@code invokespecial} instruction can refer to them
3034          * in special circumstances.  Use {@link #findConstructor findConstructor}
3035          * to access instance initialization methods in a safe manner.)</em>
3036          * <p><b>Example:</b>
3037          * {@snippet lang="java" :
3038 import static java.lang.invoke.MethodHandles.*;
3039 import static java.lang.invoke.MethodType.*;
3040 ...
3041 static class Listie extends ArrayList {
3042   public String toString() { return "[wee Listie]"; }
3043   static Lookup lookup() { return MethodHandles.lookup(); }
3044 }
3045 ...
3046 // no access to constructor via invokeSpecial:
3047 MethodHandle MH_newListie = Listie.lookup()
3048   .findConstructor(Listie.class, methodType(void.class));
3049 Listie l = (Listie) MH_newListie.invokeExact();
3050 try { assertEquals("impossible", Listie.lookup().findSpecial(
3051         Listie.class, "<init>", methodType(void.class), Listie.class));
3052  } catch (NoSuchMethodException ex) { } // OK
3053 // access to super and self methods via invokeSpecial:
3054 MethodHandle MH_super = Listie.lookup().findSpecial(
3055   ArrayList.class, "toString" , methodType(String.class), Listie.class);
3056 MethodHandle MH_this = Listie.lookup().findSpecial(
3057   Listie.class, "toString" , methodType(String.class), Listie.class);
3058 MethodHandle MH_duper = Listie.lookup().findSpecial(
3059   Object.class, "toString" , methodType(String.class), Listie.class);
3060 assertEquals("[]", (String) MH_super.invokeExact(l));
3061 assertEquals(""+l, (String) MH_this.invokeExact(l));
3062 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
3063 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
3064         String.class, "toString", methodType(String.class), Listie.class));
3065  } catch (IllegalAccessException ex) { } // OK
3066 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
3067 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
3068          * }
3069          *
3070          * @param refc the class or interface from which the method is accessed
3071          * @param name the name of the method (which must not be "&lt;init&gt;")
3072          * @param type the type of the method, with the receiver argument omitted
3073          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
3074          * @return the desired method handle
3075          * @throws NoSuchMethodException if the method does not exist
3076          * @throws IllegalAccessException if access checking fails,
3077          *                                or if the method is {@code static},
3078          *                                or if the method's variable arity modifier bit
3079          *                                is set and {@code asVarargsCollector} fails
3080          * @throws    SecurityException if a security manager is present and it
3081          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3082          * @throws NullPointerException if any argument is null
3083          */
3084         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
3085                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
3086             checkSpecialCaller(specialCaller, refc);
3087             Lookup specialLookup = this.in(specialCaller);
3088             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
3089             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
3090         }
3091 
3092         /**
3093          * Produces a method handle giving read access to a non-static field.
3094          * The type of the method handle will have a return type of the field's
3095          * value type.
3096          * The method handle's single argument will be the instance containing
3097          * the field.
3098          * Access checking is performed immediately on behalf of the lookup class.
3099          * @param refc the class or interface from which the method is accessed
3100          * @param name the field's name
3101          * @param type the field's type
3102          * @return a method handle which can load values from the field
3103          * @throws NoSuchFieldException if the field does not exist
3104          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3105          * @throws    SecurityException if a security manager is present and it
3106          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3107          * @throws NullPointerException if any argument is null
3108          * @see #findVarHandle(Class, String, Class)
3109          */
3110         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3111             MemberName field = resolveOrFail(REF_getField, refc, name, type);
3112             return getDirectField(REF_getField, refc, field);
3113         }
3114 
3115         /**
3116          * Produces a method handle giving write access to a non-static field.
3117          * The type of the method handle will have a void return type.
3118          * The method handle will take two arguments, the instance containing
3119          * the field, and the value to be stored.
3120          * The second argument will be of the field's value type.
3121          * Access checking is performed immediately on behalf of the lookup class.
3122          * @param refc the class or interface from which the method is accessed
3123          * @param name the field's name
3124          * @param type the field's type
3125          * @return a method handle which can store values into the field
3126          * @throws NoSuchFieldException if the field does not exist
3127          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3128          *                                or {@code final}
3129          * @throws    SecurityException if a security manager is present and it
3130          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3131          * @throws NullPointerException if any argument is null
3132          * @see #findVarHandle(Class, String, Class)
3133          */
3134         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3135             MemberName field = resolveOrFail(REF_putField, refc, name, type);
3136             return getDirectField(REF_putField, refc, field);
3137         }
3138 
3139         /**
3140          * Produces a VarHandle giving access to a non-static field {@code name}
3141          * of type {@code type} declared in a class of type {@code recv}.
3142          * The VarHandle's variable type is {@code type} and it has one
3143          * coordinate type, {@code recv}.
3144          * <p>
3145          * Access checking is performed immediately on behalf of the lookup
3146          * class.
3147          * <p>
3148          * Certain access modes of the returned VarHandle are unsupported under
3149          * the following conditions:
3150          * <ul>
3151          * <li>if the field is declared {@code final}, then the write, atomic
3152          *     update, numeric atomic update, and bitwise atomic update access
3153          *     modes are unsupported.
3154          * <li>if the field type is anything other than {@code byte},
3155          *     {@code short}, {@code char}, {@code int}, {@code long},
3156          *     {@code float}, or {@code double} then numeric atomic update
3157          *     access modes are unsupported.
3158          * <li>if the field type is anything other than {@code boolean},
3159          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3160          *     {@code long} then bitwise atomic update access modes are
3161          *     unsupported.
3162          * </ul>
3163          * <p>
3164          * If the field is declared {@code volatile} then the returned VarHandle
3165          * will override access to the field (effectively ignore the
3166          * {@code volatile} declaration) in accordance to its specified
3167          * access modes.
3168          * <p>
3169          * If the field type is {@code float} or {@code double} then numeric
3170          * and atomic update access modes compare values using their bitwise
3171          * representation (see {@link Float#floatToRawIntBits} and
3172          * {@link Double#doubleToRawLongBits}, respectively).
3173          * @apiNote
3174          * Bitwise comparison of {@code float} values or {@code double} values,
3175          * as performed by the numeric and atomic update access modes, differ
3176          * from the primitive {@code ==} operator and the {@link Float#equals}
3177          * and {@link Double#equals} methods, specifically with respect to
3178          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3179          * Care should be taken when performing a compare and set or a compare
3180          * and exchange operation with such values since the operation may
3181          * unexpectedly fail.
3182          * There are many possible NaN values that are considered to be
3183          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3184          * provided by Java can distinguish between them.  Operation failure can
3185          * occur if the expected or witness value is a NaN value and it is
3186          * transformed (perhaps in a platform specific manner) into another NaN
3187          * value, and thus has a different bitwise representation (see
3188          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3189          * details).
3190          * The values {@code -0.0} and {@code +0.0} have different bitwise
3191          * representations but are considered equal when using the primitive
3192          * {@code ==} operator.  Operation failure can occur if, for example, a
3193          * numeric algorithm computes an expected value to be say {@code -0.0}
3194          * and previously computed the witness value to be say {@code +0.0}.
3195          * @param recv the receiver class, of type {@code R}, that declares the
3196          * non-static field
3197          * @param name the field's name
3198          * @param type the field's type, of type {@code T}
3199          * @return a VarHandle giving access to non-static fields.
3200          * @throws NoSuchFieldException if the field does not exist
3201          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3202          * @throws    SecurityException if a security manager is present and it
3203          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3204          * @throws NullPointerException if any argument is null
3205          * @since 9
3206          */
3207         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3208             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3209             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3210             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3211         }
3212 
3213         /**
3214          * Produces a method handle giving read access to a static field.
3215          * The type of the method handle will have a return type of the field's
3216          * value type.
3217          * The method handle will take no arguments.
3218          * Access checking is performed immediately on behalf of the lookup class.
3219          * <p>
3220          * If the returned method handle is invoked, the field's class will
3221          * be initialized, if it has not already been initialized.
3222          * @param refc the class or interface from which the method is accessed
3223          * @param name the field's name
3224          * @param type the field's type
3225          * @return a method handle which can load values from the field
3226          * @throws NoSuchFieldException if the field does not exist
3227          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3228          * @throws    SecurityException if a security manager is present and it
3229          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3230          * @throws NullPointerException if any argument is null
3231          */
3232         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3233             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3234             return getDirectField(REF_getStatic, refc, field);
3235         }
3236 
3237         /**
3238          * Produces a method handle giving write access to a static field.
3239          * The type of the method handle will have a void return type.
3240          * The method handle will take a single
3241          * argument, of the field's value type, the value to be stored.
3242          * Access checking is performed immediately on behalf of the lookup class.
3243          * <p>
3244          * If the returned method handle is invoked, the field's class will
3245          * be initialized, if it has not already been initialized.
3246          * @param refc the class or interface from which the method is accessed
3247          * @param name the field's name
3248          * @param type the field's type
3249          * @return a method handle which can store values into the field
3250          * @throws NoSuchFieldException if the field does not exist
3251          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3252          *                                or is {@code final}
3253          * @throws    SecurityException if a security manager is present and it
3254          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3255          * @throws NullPointerException if any argument is null
3256          */
3257         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3258             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3259             return getDirectField(REF_putStatic, refc, field);
3260         }
3261 
3262         /**
3263          * Produces a VarHandle giving access to a static field {@code name} of
3264          * type {@code type} declared in a class of type {@code decl}.
3265          * The VarHandle's variable type is {@code type} and it has no
3266          * coordinate types.
3267          * <p>
3268          * Access checking is performed immediately on behalf of the lookup
3269          * class.
3270          * <p>
3271          * If the returned VarHandle is operated on, the declaring class will be
3272          * initialized, if it has not already been initialized.
3273          * <p>
3274          * Certain access modes of the returned VarHandle are unsupported under
3275          * the following conditions:
3276          * <ul>
3277          * <li>if the field is declared {@code final}, then the write, atomic
3278          *     update, numeric atomic update, and bitwise atomic update access
3279          *     modes are unsupported.
3280          * <li>if the field type is anything other than {@code byte},
3281          *     {@code short}, {@code char}, {@code int}, {@code long},
3282          *     {@code float}, or {@code double}, then numeric atomic update
3283          *     access modes are unsupported.
3284          * <li>if the field type is anything other than {@code boolean},
3285          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3286          *     {@code long} then bitwise atomic update access modes are
3287          *     unsupported.
3288          * </ul>
3289          * <p>
3290          * If the field is declared {@code volatile} then the returned VarHandle
3291          * will override access to the field (effectively ignore the
3292          * {@code volatile} declaration) in accordance to its specified
3293          * access modes.
3294          * <p>
3295          * If the field type is {@code float} or {@code double} then numeric
3296          * and atomic update access modes compare values using their bitwise
3297          * representation (see {@link Float#floatToRawIntBits} and
3298          * {@link Double#doubleToRawLongBits}, respectively).
3299          * @apiNote
3300          * Bitwise comparison of {@code float} values or {@code double} values,
3301          * as performed by the numeric and atomic update access modes, differ
3302          * from the primitive {@code ==} operator and the {@link Float#equals}
3303          * and {@link Double#equals} methods, specifically with respect to
3304          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3305          * Care should be taken when performing a compare and set or a compare
3306          * and exchange operation with such values since the operation may
3307          * unexpectedly fail.
3308          * There are many possible NaN values that are considered to be
3309          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3310          * provided by Java can distinguish between them.  Operation failure can
3311          * occur if the expected or witness value is a NaN value and it is
3312          * transformed (perhaps in a platform specific manner) into another NaN
3313          * value, and thus has a different bitwise representation (see
3314          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3315          * details).
3316          * The values {@code -0.0} and {@code +0.0} have different bitwise
3317          * representations but are considered equal when using the primitive
3318          * {@code ==} operator.  Operation failure can occur if, for example, a
3319          * numeric algorithm computes an expected value to be say {@code -0.0}
3320          * and previously computed the witness value to be say {@code +0.0}.
3321          * @param decl the class that declares the static field
3322          * @param name the field's name
3323          * @param type the field's type, of type {@code T}
3324          * @return a VarHandle giving access to a static field
3325          * @throws NoSuchFieldException if the field does not exist
3326          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3327          * @throws    SecurityException if a security manager is present and it
3328          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3329          * @throws NullPointerException if any argument is null
3330          * @since 9
3331          */
3332         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3333             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3334             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3335             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3336         }
3337 
3338         /**
3339          * Produces an early-bound method handle for a non-static method.
3340          * The receiver must have a supertype {@code defc} in which a method
3341          * of the given name and type is accessible to the lookup class.
3342          * The method and all its argument types must be accessible to the lookup object.
3343          * The type of the method handle will be that of the method,
3344          * without any insertion of an additional receiver parameter.
3345          * The given receiver will be bound into the method handle,
3346          * so that every call to the method handle will invoke the
3347          * requested method on the given receiver.
3348          * <p>
3349          * The returned method handle will have
3350          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3351          * the method's variable arity modifier bit ({@code 0x0080}) is set
3352          * <em>and</em> the trailing array argument is not the only argument.
3353          * (If the trailing array argument is the only argument,
3354          * the given receiver value will be bound to it.)
3355          * <p>
3356          * This is almost equivalent to the following code, with some differences noted below:
3357          * {@snippet lang="java" :
3358 import static java.lang.invoke.MethodHandles.*;
3359 import static java.lang.invoke.MethodType.*;
3360 ...
3361 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3362 MethodHandle mh1 = mh0.bindTo(receiver);
3363 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3364 return mh1;
3365          * }
3366          * where {@code defc} is either {@code receiver.getClass()} or a super
3367          * type of that class, in which the requested method is accessible
3368          * to the lookup class.
3369          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3370          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3371          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3372          * the receiver is restricted by {@code findVirtual} to the lookup class.)
3373          * @param receiver the object from which the method is accessed
3374          * @param name the name of the method
3375          * @param type the type of the method, with the receiver argument omitted
3376          * @return the desired method handle
3377          * @throws NoSuchMethodException if the method does not exist
3378          * @throws IllegalAccessException if access checking fails
3379          *                                or if the method's variable arity modifier bit
3380          *                                is set and {@code asVarargsCollector} fails
3381          * @throws    SecurityException if a security manager is present and it
3382          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3383          * @throws NullPointerException if any argument is null
3384          * @see MethodHandle#bindTo
3385          * @see #findVirtual
3386          */
3387         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3388             Class<? extends Object> refc = receiver.getClass(); // may get NPE
3389             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3390             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3391             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3392                 throw new IllegalAccessException("The restricted defining class " +
3393                                                  mh.type().leadingReferenceParameter().getName() +
3394                                                  " is not assignable from receiver class " +
3395                                                  receiver.getClass().getName());
3396             }
3397             return mh.bindArgumentL(0, receiver).setVarargs(method);
3398         }
3399 
3400         /**
3401          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3402          * to <i>m</i>, if the lookup class has permission.
3403          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3404          * If <i>m</i> is virtual, overriding is respected on every call.
3405          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3406          * The type of the method handle will be that of the method,
3407          * with the receiver type prepended (but only if it is non-static).
3408          * If the method's {@code accessible} flag is not set,
3409          * access checking is performed immediately on behalf of the lookup class.
3410          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3411          * <p>
3412          * The returned method handle will have
3413          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3414          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3415          * <p>
3416          * If <i>m</i> is static, and
3417          * if the returned method handle is invoked, the method's class will
3418          * be initialized, if it has not already been initialized.
3419          * @param m the reflected method
3420          * @return a method handle which can invoke the reflected method
3421          * @throws IllegalAccessException if access checking fails
3422          *                                or if the method's variable arity modifier bit
3423          *                                is set and {@code asVarargsCollector} fails
3424          * @throws NullPointerException if the argument is null
3425          */
3426         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3427             if (m.getDeclaringClass() == MethodHandle.class) {
3428                 MethodHandle mh = unreflectForMH(m);
3429                 if (mh != null)  return mh;
3430             }
3431             if (m.getDeclaringClass() == VarHandle.class) {
3432                 MethodHandle mh = unreflectForVH(m);
3433                 if (mh != null)  return mh;
3434             }
3435             MemberName method = new MemberName(m);
3436             byte refKind = method.getReferenceKind();
3437             if (refKind == REF_invokeSpecial)
3438                 refKind = REF_invokeVirtual;
3439             assert(method.isMethod());
3440             @SuppressWarnings("deprecation")
3441             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3442             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3443         }
3444         private MethodHandle unreflectForMH(Method m) {
3445             // these names require special lookups because they throw UnsupportedOperationException
3446             if (MemberName.isMethodHandleInvokeName(m.getName()))
3447                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3448             return null;
3449         }
3450         private MethodHandle unreflectForVH(Method m) {
3451             // these names require special lookups because they throw UnsupportedOperationException
3452             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3453                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3454             return null;
3455         }
3456 
3457         /**
3458          * Produces a method handle for a reflected method.
3459          * It will bypass checks for overriding methods on the receiver,
3460          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3461          * instruction from within the explicitly specified {@code specialCaller}.
3462          * The type of the method handle will be that of the method,
3463          * with a suitably restricted receiver type prepended.
3464          * (The receiver type will be {@code specialCaller} or a subtype.)
3465          * If the method's {@code accessible} flag is not set,
3466          * access checking is performed immediately on behalf of the lookup class,
3467          * as if {@code invokespecial} instruction were being linked.
3468          * <p>
3469          * Before method resolution,
3470          * if the explicitly specified caller class is not identical with the
3471          * lookup class, or if this lookup object does not have
3472          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3473          * privileges, the access fails.
3474          * <p>
3475          * The returned method handle will have
3476          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3477          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3478          * @param m the reflected method
3479          * @param specialCaller the class nominally calling the method
3480          * @return a method handle which can invoke the reflected method
3481          * @throws IllegalAccessException if access checking fails,
3482          *                                or if the method is {@code static},
3483          *                                or if the method's variable arity modifier bit
3484          *                                is set and {@code asVarargsCollector} fails
3485          * @throws NullPointerException if any argument is null
3486          */
3487         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3488             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3489             Lookup specialLookup = this.in(specialCaller);
3490             MemberName method = new MemberName(m, true);
3491             assert(method.isMethod());
3492             // ignore m.isAccessible:  this is a new kind of access
3493             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3494         }
3495 
3496         /**
3497          * Produces a method handle for a reflected constructor.
3498          * The type of the method handle will be that of the constructor,
3499          * with the return type changed to the declaring class.
3500          * The method handle will perform a {@code newInstance} operation,
3501          * creating a new instance of the constructor's class on the
3502          * arguments passed to the method handle.
3503          * <p>
3504          * If the constructor's {@code accessible} flag is not set,
3505          * access checking is performed immediately on behalf of the lookup class.
3506          * <p>
3507          * The returned method handle will have
3508          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3509          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3510          * <p>
3511          * If the returned method handle is invoked, the constructor's class will
3512          * be initialized, if it has not already been initialized.
3513          * @param c the reflected constructor
3514          * @return a method handle which can invoke the reflected constructor
3515          * @throws IllegalAccessException if access checking fails
3516          *                                or if the method's variable arity modifier bit
3517          *                                is set and {@code asVarargsCollector} fails
3518          * @throws NullPointerException if the argument is null
3519          */
3520         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3521             MemberName ctor = new MemberName(c);
3522             assert(ctor.isConstructor());
3523             @SuppressWarnings("deprecation")
3524             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3525             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
3526         }
3527 
3528         /*
3529          * Produces a method handle that is capable of creating instances of the given class
3530          * and instantiated by the given constructor.  No security manager check.
3531          *
3532          * This method should only be used by ReflectionFactory::newConstructorForSerialization.
3533          */
3534         /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException {
3535             MemberName ctor = new MemberName(c);
3536             assert(ctor.isConstructor() && constructorInSuperclass(decl, c));
3537             checkAccess(REF_newInvokeSpecial, decl, ctor);
3538             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
3539             return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor);
3540         }
3541 
3542         private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) {
3543             if (decl == ctor.getDeclaringClass())
3544                 return true;
3545 
3546             Class<?> cl = decl;
3547             while ((cl = cl.getSuperclass()) != null) {
3548                 if (cl == ctor.getDeclaringClass()) {
3549                     return true;
3550                 }
3551             }
3552             return false;
3553         }
3554 
3555         /**
3556          * Produces a method handle giving read access to a reflected field.
3557          * The type of the method handle will have a return type of the field's
3558          * value type.
3559          * If the field is {@code static}, the method handle will take no arguments.
3560          * Otherwise, its single argument will be the instance containing
3561          * the field.
3562          * If the {@code Field} object's {@code accessible} flag is not set,
3563          * access checking is performed immediately on behalf of the lookup class.
3564          * <p>
3565          * If the field is static, and
3566          * if the returned method handle is invoked, the field's class will
3567          * be initialized, if it has not already been initialized.
3568          * @param f the reflected field
3569          * @return a method handle which can load values from the reflected field
3570          * @throws IllegalAccessException if access checking fails
3571          * @throws NullPointerException if the argument is null
3572          */
3573         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3574             return unreflectField(f, false);
3575         }
3576 
3577         /**
3578          * Produces a method handle giving write access to a reflected field.
3579          * The type of the method handle will have a void return type.
3580          * If the field is {@code static}, the method handle will take a single
3581          * argument, of the field's value type, the value to be stored.
3582          * Otherwise, the two arguments will be the instance containing
3583          * the field, and the value to be stored.
3584          * If the {@code Field} object's {@code accessible} flag is not set,
3585          * access checking is performed immediately on behalf of the lookup class.
3586          * <p>
3587          * If the field is {@code final}, write access will not be
3588          * allowed and access checking will fail, except under certain
3589          * narrow circumstances documented for {@link Field#set Field.set}.
3590          * A method handle is returned only if a corresponding call to
3591          * the {@code Field} object's {@code set} method could return
3592          * normally.  In particular, fields which are both {@code static}
3593          * and {@code final} may never be set.
3594          * <p>
3595          * If the field is {@code static}, and
3596          * if the returned method handle is invoked, the field's class will
3597          * be initialized, if it has not already been initialized.
3598          * @param f the reflected field
3599          * @return a method handle which can store values into the reflected field
3600          * @throws IllegalAccessException if access checking fails,
3601          *         or if the field is {@code final} and write access
3602          *         is not enabled on the {@code Field} object
3603          * @throws NullPointerException if the argument is null
3604          */
3605         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3606             return unreflectField(f, true);
3607         }
3608 
3609         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3610             MemberName field = new MemberName(f, isSetter);
3611             if (isSetter && field.isFinal()) {
3612                 if (field.isTrustedFinalField()) {
3613                     String msg = field.isStatic() ? "static final field has no write access"
3614                                                   : "final field has no write access";
3615                     throw field.makeAccessException(msg, this);
3616                 }
3617             }
3618             assert(isSetter
3619                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3620                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3621             @SuppressWarnings("deprecation")
3622             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3623             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3624         }
3625 
3626         /**
3627          * Produces a VarHandle giving access to a reflected field {@code f}
3628          * of type {@code T} declared in a class of type {@code R}.
3629          * The VarHandle's variable type is {@code T}.
3630          * If the field is non-static the VarHandle has one coordinate type,
3631          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3632          * coordinate types.
3633          * <p>
3634          * Access checking is performed immediately on behalf of the lookup
3635          * class, regardless of the value of the field's {@code accessible}
3636          * flag.
3637          * <p>
3638          * If the field is static, and if the returned VarHandle is operated
3639          * on, the field's declaring class will be initialized, if it has not
3640          * already been initialized.
3641          * <p>
3642          * Certain access modes of the returned VarHandle are unsupported under
3643          * the following conditions:
3644          * <ul>
3645          * <li>if the field is declared {@code final}, then the write, atomic
3646          *     update, numeric atomic update, and bitwise atomic update access
3647          *     modes are unsupported.
3648          * <li>if the field type is anything other than {@code byte},
3649          *     {@code short}, {@code char}, {@code int}, {@code long},
3650          *     {@code float}, or {@code double} then numeric atomic update
3651          *     access modes are unsupported.
3652          * <li>if the field type is anything other than {@code boolean},
3653          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3654          *     {@code long} then bitwise atomic update access modes are
3655          *     unsupported.
3656          * </ul>
3657          * <p>
3658          * If the field is declared {@code volatile} then the returned VarHandle
3659          * will override access to the field (effectively ignore the
3660          * {@code volatile} declaration) in accordance to its specified
3661          * access modes.
3662          * <p>
3663          * If the field type is {@code float} or {@code double} then numeric
3664          * and atomic update access modes compare values using their bitwise
3665          * representation (see {@link Float#floatToRawIntBits} and
3666          * {@link Double#doubleToRawLongBits}, respectively).
3667          * @apiNote
3668          * Bitwise comparison of {@code float} values or {@code double} values,
3669          * as performed by the numeric and atomic update access modes, differ
3670          * from the primitive {@code ==} operator and the {@link Float#equals}
3671          * and {@link Double#equals} methods, specifically with respect to
3672          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3673          * Care should be taken when performing a compare and set or a compare
3674          * and exchange operation with such values since the operation may
3675          * unexpectedly fail.
3676          * There are many possible NaN values that are considered to be
3677          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3678          * provided by Java can distinguish between them.  Operation failure can
3679          * occur if the expected or witness value is a NaN value and it is
3680          * transformed (perhaps in a platform specific manner) into another NaN
3681          * value, and thus has a different bitwise representation (see
3682          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3683          * details).
3684          * The values {@code -0.0} and {@code +0.0} have different bitwise
3685          * representations but are considered equal when using the primitive
3686          * {@code ==} operator.  Operation failure can occur if, for example, a
3687          * numeric algorithm computes an expected value to be say {@code -0.0}
3688          * and previously computed the witness value to be say {@code +0.0}.
3689          * @param f the reflected field, with a field of type {@code T}, and
3690          * a declaring class of type {@code R}
3691          * @return a VarHandle giving access to non-static fields or a static
3692          * field
3693          * @throws IllegalAccessException if access checking fails
3694          * @throws NullPointerException if the argument is null
3695          * @since 9
3696          */
3697         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3698             MemberName getField = new MemberName(f, false);
3699             MemberName putField = new MemberName(f, true);
3700             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
3701                                                       f.getDeclaringClass(), getField, putField);
3702         }
3703 
3704         /**
3705          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3706          * created by this lookup object or a similar one.
3707          * Security and access checks are performed to ensure that this lookup object
3708          * is capable of reproducing the target method handle.
3709          * This means that the cracking may fail if target is a direct method handle
3710          * but was created by an unrelated lookup object.
3711          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3712          * and was created by a lookup object for a different class.
3713          * @param target a direct method handle to crack into symbolic reference components
3714          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3715          * @throws    SecurityException if a security manager is present and it
3716          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3717          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3718          * @throws    NullPointerException if the target is {@code null}
3719          * @see MethodHandleInfo
3720          * @since 1.8
3721          */
3722         public MethodHandleInfo revealDirect(MethodHandle target) {
3723             if (!target.isCrackable()) {
3724                 throw newIllegalArgumentException("not a direct method handle");
3725             }
3726             MemberName member = target.internalMemberName();
3727             Class<?> defc = member.getDeclaringClass();
3728             byte refKind = member.getReferenceKind();
3729             assert(MethodHandleNatives.refKindIsValid(refKind));
3730             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3731                 // Devirtualized method invocation is usually formally virtual.
3732                 // To avoid creating extra MemberName objects for this common case,
3733                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3734                 refKind = REF_invokeVirtual;
3735             if (refKind == REF_invokeVirtual && defc.isInterface())
3736                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3737                 refKind = REF_invokeInterface;
3738             // Check SM permissions and member access before cracking.
3739             try {
3740                 checkAccess(refKind, defc, member);
3741                 checkSecurityManager(defc, member);
3742             } catch (IllegalAccessException ex) {
3743                 throw new IllegalArgumentException(ex);
3744             }
3745             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3746                 Class<?> callerClass = target.internalCallerClass();
3747                 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3748                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3749             }
3750             // Produce the handle to the results.
3751             return new InfoFromMemberName(this, member, refKind);
3752         }
3753 
3754         /// Helper methods, all package-private.
3755 
3756         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3757             checkSymbolicClass(refc);  // do this before attempting to resolve
3758             Objects.requireNonNull(name);
3759             Objects.requireNonNull(type);
3760             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3761                                             NoSuchFieldException.class);
3762         }
3763 
3764         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3765             checkSymbolicClass(refc);  // do this before attempting to resolve
3766             Objects.requireNonNull(type);
3767             checkMethodName(refKind, name);  // implicit null-check of name
3768             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3769                                             NoSuchMethodException.class);
3770         }
3771 
3772         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3773             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3774             Objects.requireNonNull(member.getName());
3775             Objects.requireNonNull(member.getType());
3776             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3777                                             ReflectiveOperationException.class);
3778         }
3779 
3780         MemberName resolveOrNull(byte refKind, MemberName member) {
3781             // do this before attempting to resolve
3782             if (!isClassAccessible(member.getDeclaringClass())) {
3783                 return null;
3784             }
3785             Objects.requireNonNull(member.getName());
3786             Objects.requireNonNull(member.getType());
3787             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3788         }
3789 
3790         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3791             // do this before attempting to resolve
3792             if (!isClassAccessible(refc)) {
3793                 return null;
3794             }
3795             Objects.requireNonNull(type);
3796             // implicit null-check of name
3797             if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3798                 return null;
3799             }
3800             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3801         }
3802 
3803         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3804             if (!isClassAccessible(refc)) {
3805                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3806             }
3807         }
3808 
3809         boolean isClassAccessible(Class<?> refc) {
3810             Objects.requireNonNull(refc);
3811             Class<?> caller = lookupClassOrNull();
3812             Class<?> type = refc;
3813             while (type.isArray()) {
3814                 type = type.getComponentType();
3815             }
3816             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3817         }
3818 
3819         /** Check name for an illegal leading "&lt;" character. */
3820         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3821             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
3822                 throw new NoSuchMethodException("illegal method name: "+name);
3823         }
3824 
3825         /**
3826          * Find my trustable caller class if m is a caller sensitive method.
3827          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3828          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3829          */
3830         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3831             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3832                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3833                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3834             }
3835             return this;
3836         }
3837 
3838         /**
3839          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3840          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3841          *
3842          * @deprecated This method was originally designed to test {@code PRIVATE} access
3843          * that implies full privilege access but {@code MODULE} access has since become
3844          * independent of {@code PRIVATE} access.  It is recommended to call
3845          * {@link #hasFullPrivilegeAccess()} instead.
3846          * @since 9
3847          */
3848         @Deprecated(since="14")
3849         public boolean hasPrivateAccess() {
3850             return hasFullPrivilegeAccess();
3851         }
3852 
3853         /**
3854          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3855          * i.e. {@code PRIVATE} and {@code MODULE} access.
3856          * A {@code Lookup} object must have full privilege access in order to
3857          * access all members that are allowed to the
3858          * {@linkplain #lookupClass() lookup class}.
3859          *
3860          * @return {@code true} if this lookup has full privilege access.
3861          * @since 14
3862          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3863          */
3864         public boolean hasFullPrivilegeAccess() {
3865             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3866         }
3867 
3868         /**
3869          * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a>
3870          * for ensureInitialized, findClass or accessClass.
3871          */
3872         void checkSecurityManager(Class<?> refc) {
3873             if (allowedModes == TRUSTED)  return;
3874 
3875             @SuppressWarnings("removal")
3876             SecurityManager smgr = System.getSecurityManager();
3877             if (smgr == null)  return;
3878 
3879             // Step 1:
3880             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3881             if (!fullPrivilegeLookup ||
3882                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3883                 ReflectUtil.checkPackageAccess(refc);
3884             }
3885 
3886             // Step 2b:
3887             if (!fullPrivilegeLookup) {
3888                 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
3889             }
3890         }
3891 
3892         /**
3893          * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
3894          * Determines a trustable caller class to compare with refc, the symbolic reference class.
3895          * If this lookup object has full privilege access except original access,
3896          * then the caller class is the lookupClass.
3897          *
3898          * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)}
3899          * from the same module skips the security permission check.
3900          */
3901         void checkSecurityManager(Class<?> refc, MemberName m) {
3902             Objects.requireNonNull(refc);
3903             Objects.requireNonNull(m);
3904 
3905             if (allowedModes == TRUSTED)  return;
3906 
3907             @SuppressWarnings("removal")
3908             SecurityManager smgr = System.getSecurityManager();
3909             if (smgr == null)  return;
3910 
3911             // Step 1:
3912             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3913             if (!fullPrivilegeLookup ||
3914                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3915                 ReflectUtil.checkPackageAccess(refc);
3916             }
3917 
3918             // Step 2a:
3919             if (m.isPublic()) return;
3920             if (!fullPrivilegeLookup) {
3921                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3922             }
3923 
3924             // Step 3:
3925             Class<?> defc = m.getDeclaringClass();
3926             if (!fullPrivilegeLookup && defc != refc) {
3927                 ReflectUtil.checkPackageAccess(defc);
3928             }
3929         }
3930 
3931         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3932             boolean wantStatic = (refKind == REF_invokeStatic);
3933             String message;
3934             if (m.isConstructor())
3935                 message = "expected a method, not a constructor";
3936             else if (!m.isMethod())
3937                 message = "expected a method";
3938             else if (wantStatic != m.isStatic())
3939                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3940             else
3941                 { checkAccess(refKind, refc, m); return; }
3942             throw m.makeAccessException(message, this);
3943         }
3944 
3945         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3946             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3947             String message;
3948             if (wantStatic != m.isStatic())
3949                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3950             else
3951                 { checkAccess(refKind, refc, m); return; }
3952             throw m.makeAccessException(message, this);
3953         }
3954 
3955         private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) {
3956             return Modifier.isProtected(m.getModifiers()) &&
3957                     refKind == REF_invokeVirtual &&
3958                     m.getDeclaringClass() == Object.class &&
3959                     m.getName().equals("clone") &&
3960                     refc.isArray();
3961         }
3962 
3963         /** Check public/protected/private bits on the symbolic reference class and its member. */
3964         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3965             assert(m.referenceKindIsConsistentWith(refKind) &&
3966                    MethodHandleNatives.refKindIsValid(refKind) &&
3967                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3968             int allowedModes = this.allowedModes;
3969             if (allowedModes == TRUSTED)  return;
3970             int mods = m.getModifiers();
3971             if (isArrayClone(refKind, refc, m)) {
3972                 // The JVM does this hack also.
3973                 // (See ClassVerifier::verify_invoke_instructions
3974                 // and LinkResolver::check_method_accessability.)
3975                 // Because the JVM does not allow separate methods on array types,
3976                 // there is no separate method for int[].clone.
3977                 // All arrays simply inherit Object.clone.
3978                 // But for access checking logic, we make Object.clone
3979                 // (normally protected) appear to be public.
3980                 // Later on, when the DirectMethodHandle is created,
3981                 // its leading argument will be restricted to the
3982                 // requested array type.
3983                 // N.B. The return type is not adjusted, because
3984                 // that is *not* the bytecode behavior.
3985                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3986             }
3987             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3988                 // cannot "new" a protected ctor in a different package
3989                 mods ^= Modifier.PROTECTED;
3990             }
3991             if (Modifier.isFinal(mods) &&
3992                     MethodHandleNatives.refKindIsSetter(refKind))
3993                 throw m.makeAccessException("unexpected set of a final field", this);
3994             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3995             if ((requestedModes & allowedModes) != 0) {
3996                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3997                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3998                     return;
3999             } else {
4000                 // Protected members can also be checked as if they were package-private.
4001                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
4002                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
4003                     return;
4004             }
4005             throw m.makeAccessException(accessFailedMessage(refc, m), this);
4006         }
4007 
4008         String accessFailedMessage(Class<?> refc, MemberName m) {
4009             Class<?> defc = m.getDeclaringClass();
4010             int mods = m.getModifiers();
4011             // check the class first:
4012             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
4013                                (defc == refc ||
4014                                 Modifier.isPublic(refc.getModifiers())));
4015             if (!classOK && (allowedModes & PACKAGE) != 0) {
4016                 // ignore previous lookup class to check if default package access
4017                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
4018                            (defc == refc ||
4019                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
4020             }
4021             if (!classOK)
4022                 return "class is not public";
4023             if (Modifier.isPublic(mods))
4024                 return "access to public member failed";  // (how?, module not readable?)
4025             if (Modifier.isPrivate(mods))
4026                 return "member is private";
4027             if (Modifier.isProtected(mods))
4028                 return "member is protected";
4029             return "member is private to package";
4030         }
4031 
4032         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
4033             int allowedModes = this.allowedModes;
4034             if (allowedModes == TRUSTED)  return;
4035             if ((lookupModes() & PRIVATE) == 0
4036                 || (specialCaller != lookupClass()
4037                        // ensure non-abstract methods in superinterfaces can be special-invoked
4038                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
4039                 throw new MemberName(specialCaller).
4040                     makeAccessException("no private access for invokespecial", this);
4041         }
4042 
4043         private boolean restrictProtectedReceiver(MemberName method) {
4044             // The accessing class only has the right to use a protected member
4045             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
4046             if (!method.isProtected() || method.isStatic()
4047                 || allowedModes == TRUSTED
4048                 || method.getDeclaringClass() == lookupClass()
4049                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
4050                 return false;
4051             return true;
4052         }
4053         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
4054             assert(!method.isStatic());
4055             // receiver type of mh is too wide; narrow to caller
4056             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
4057                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
4058             }
4059             MethodType rawType = mh.type();
4060             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
4061             MethodType narrowType = rawType.changeParameterType(0, caller);
4062             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
4063             assert(mh.viewAsTypeChecks(narrowType, true));
4064             return mh.copyWith(narrowType, mh.form);
4065         }
4066 
4067         /** Check access and get the requested method. */
4068         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4069             final boolean doRestrict    = true;
4070             final boolean checkSecurity = true;
4071             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4072         }
4073         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
4074         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4075             final boolean doRestrict    = false;
4076             final boolean checkSecurity = true;
4077             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
4078         }
4079         /** Check access and get the requested method, eliding security manager checks. */
4080         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4081             final boolean doRestrict    = true;
4082             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4083             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4084         }
4085         /** Common code for all methods; do not call directly except from immediately above. */
4086         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
4087                                                    boolean checkSecurity,
4088                                                    boolean doRestrict,
4089                                                    Lookup boundCaller) throws IllegalAccessException {
4090             checkMethod(refKind, refc, method);
4091             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4092             if (checkSecurity)
4093                 checkSecurityManager(refc, method);
4094             assert(!method.isMethodHandleInvoke());
4095 
4096             if (refKind == REF_invokeSpecial &&
4097                 refc != lookupClass() &&
4098                 !refc.isInterface() && !lookupClass().isInterface() &&
4099                 refc != lookupClass().getSuperclass() &&
4100                 refc.isAssignableFrom(lookupClass())) {
4101                 assert(!method.getName().equals(ConstantDescs.INIT_NAME));  // not this code path
4102 
4103                 // Per JVMS 6.5, desc. of invokespecial instruction:
4104                 // If the method is in a superclass of the LC,
4105                 // and if our original search was above LC.super,
4106                 // repeat the search (symbolic lookup) from LC.super
4107                 // and continue with the direct superclass of that class,
4108                 // and so forth, until a match is found or no further superclasses exist.
4109                 // FIXME: MemberName.resolve should handle this instead.
4110                 Class<?> refcAsSuper = lookupClass();
4111                 MemberName m2;
4112                 do {
4113                     refcAsSuper = refcAsSuper.getSuperclass();
4114                     m2 = new MemberName(refcAsSuper,
4115                                         method.getName(),
4116                                         method.getMethodType(),
4117                                         REF_invokeSpecial);
4118                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
4119                 } while (m2 == null &&         // no method is found yet
4120                          refc != refcAsSuper); // search up to refc
4121                 if (m2 == null)  throw new InternalError(method.toString());
4122                 method = m2;
4123                 refc = refcAsSuper;
4124                 // redo basic checks
4125                 checkMethod(refKind, refc, method);
4126             }
4127             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
4128             MethodHandle mh = dmh;
4129             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
4130             if ((doRestrict && refKind == REF_invokeSpecial) ||
4131                     (MethodHandleNatives.refKindHasReceiver(refKind) &&
4132                             restrictProtectedReceiver(method) &&
4133                             // All arrays simply inherit the protected Object.clone method.
4134                             // The leading argument is already restricted to the requested
4135                             // array type (not the lookup class).
4136                             !isArrayClone(refKind, refc, method))) {
4137                 mh = restrictReceiver(method, dmh, lookupClass());
4138             }
4139             mh = maybeBindCaller(method, mh, boundCaller);
4140             mh = mh.setVarargs(method);
4141             return mh;
4142         }
4143         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
4144                                              throws IllegalAccessException {
4145             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
4146                 return mh;
4147 
4148             // boundCaller must have full privilege access.
4149             // It should have been checked by findBoundCallerLookup. Safe to check this again.
4150             if ((boundCaller.lookupModes() & ORIGINAL) == 0)
4151                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
4152 
4153             assert boundCaller.hasFullPrivilegeAccess();
4154 
4155             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
4156             // Note: caller will apply varargs after this step happens.
4157             return cbmh;
4158         }
4159 
4160         /** Check access and get the requested field. */
4161         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4162             final boolean checkSecurity = true;
4163             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4164         }
4165         /** Check access and get the requested field, eliding security manager checks. */
4166         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4167             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4168             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4169         }
4170         /** Common code for all fields; do not call directly except from immediately above. */
4171         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
4172                                                   boolean checkSecurity) throws IllegalAccessException {
4173             checkField(refKind, refc, field);
4174             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4175             if (checkSecurity)
4176                 checkSecurityManager(refc, field);
4177             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
4178             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
4179                                     restrictProtectedReceiver(field));
4180             if (doRestrict)
4181                 return restrictReceiver(field, dmh, lookupClass());
4182             return dmh;
4183         }
4184         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
4185                                             Class<?> refc, MemberName getField, MemberName putField)
4186                 throws IllegalAccessException {
4187             final boolean checkSecurity = true;
4188             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4189         }
4190         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
4191                                                              Class<?> refc, MemberName getField, MemberName putField)
4192                 throws IllegalAccessException {
4193             final boolean checkSecurity = false;
4194             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4195         }
4196         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
4197                                                   Class<?> refc, MemberName getField, MemberName putField,
4198                                                   boolean checkSecurity) throws IllegalAccessException {
4199             assert getField.isStatic() == putField.isStatic();
4200             assert getField.isGetter() && putField.isSetter();
4201             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
4202             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
4203 
4204             checkField(getRefKind, refc, getField);
4205             if (checkSecurity)
4206                 checkSecurityManager(refc, getField);
4207 
4208             if (!putField.isFinal()) {
4209                 // A VarHandle does not support updates to final fields, any
4210                 // such VarHandle to a final field will be read-only and
4211                 // therefore the following write-based accessibility checks are
4212                 // only required for non-final fields
4213                 checkField(putRefKind, refc, putField);
4214                 if (checkSecurity)
4215                     checkSecurityManager(refc, putField);
4216             }
4217 
4218             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
4219                                   restrictProtectedReceiver(getField));
4220             if (doRestrict) {
4221                 assert !getField.isStatic();
4222                 // receiver type of VarHandle is too wide; narrow to caller
4223                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
4224                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4225                 }
4226                 refc = lookupClass();
4227             }
4228             return VarHandles.makeFieldHandle(getField, refc,
4229                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4230         }
4231         /** Check access and get the requested constructor. */
4232         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4233             final boolean checkSecurity = true;
4234             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4235         }
4236         /** Check access and get the requested constructor, eliding security manager checks. */
4237         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4238             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4239             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4240         }
4241         /** Common code for all constructors; do not call directly except from immediately above. */
4242         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4243                                                   boolean checkSecurity) throws IllegalAccessException {
4244             assert(ctor.isConstructor());
4245             checkAccess(REF_newInvokeSpecial, refc, ctor);
4246             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4247             if (checkSecurity)
4248                 checkSecurityManager(refc, ctor);
4249             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4250             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4251         }
4252 
4253         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4254          */
4255         /*non-public*/
4256         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4257                 throws ReflectiveOperationException {
4258             if (!(type instanceof Class || type instanceof MethodType))
4259                 throw new InternalError("unresolved MemberName");
4260             MemberName member = new MemberName(refKind, defc, name, type);
4261             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4262             if (mh != null) {
4263                 checkSymbolicClass(defc);
4264                 return mh;
4265             }
4266             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
4267                 // Treat MethodHandle.invoke and invokeExact specially.
4268                 mh = findVirtualForMH(member.getName(), member.getMethodType());
4269                 if (mh != null) {
4270                     return mh;
4271                 }
4272             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4273                 // Treat signature-polymorphic methods on VarHandle specially.
4274                 mh = findVirtualForVH(member.getName(), member.getMethodType());
4275                 if (mh != null) {
4276                     return mh;
4277                 }
4278             }
4279             MemberName resolved = resolveOrFail(refKind, member);
4280             mh = getDirectMethodForConstant(refKind, defc, resolved);
4281             if (mh instanceof DirectMethodHandle dmh
4282                     && canBeCached(refKind, defc, resolved)) {
4283                 MemberName key = mh.internalMemberName();
4284                 if (key != null) {
4285                     key = key.asNormalOriginal();
4286                 }
4287                 if (member.equals(key)) {  // better safe than sorry
4288                     LOOKASIDE_TABLE.put(key, dmh);
4289                 }
4290             }
4291             return mh;
4292         }
4293         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4294             if (refKind == REF_invokeSpecial) {
4295                 return false;
4296             }
4297             if (!Modifier.isPublic(defc.getModifiers()) ||
4298                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4299                     !member.isPublic() ||
4300                     member.isCallerSensitive()) {
4301                 return false;
4302             }
4303             ClassLoader loader = defc.getClassLoader();
4304             if (loader != null) {
4305                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4306                 boolean found = false;
4307                 while (sysl != null) {
4308                     if (loader == sysl) { found = true; break; }
4309                     sysl = sysl.getParent();
4310                 }
4311                 if (!found) {
4312                     return false;
4313                 }
4314             }
4315             try {
4316                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4317                     new MemberName(refKind, defc, member.getName(), member.getType()));
4318                 if (resolved2 == null) {
4319                     return false;
4320                 }
4321                 checkSecurityManager(defc, resolved2);
4322             } catch (SecurityException ex) {
4323                 return false;
4324             }
4325             return true;
4326         }
4327         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4328                 throws ReflectiveOperationException {
4329             if (MethodHandleNatives.refKindIsField(refKind)) {
4330                 return getDirectFieldNoSecurityManager(refKind, defc, member);
4331             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4332                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
4333             } else if (refKind == REF_newInvokeSpecial) {
4334                 return getDirectConstructorNoSecurityManager(defc, member);
4335             }
4336             // oops
4337             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4338         }
4339 
4340         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4341     }
4342 
4343     /**
4344      * Produces a method handle constructing arrays of a desired type,
4345      * as if by the {@code anewarray} bytecode.
4346      * The return type of the method handle will be the array type.
4347      * The type of its sole argument will be {@code int}, which specifies the size of the array.
4348      *
4349      * <p> If the returned method handle is invoked with a negative
4350      * array size, a {@code NegativeArraySizeException} will be thrown.
4351      *
4352      * @param arrayClass an array type
4353      * @return a method handle which can create arrays of the given type
4354      * @throws NullPointerException if the argument is {@code null}
4355      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4356      * @see java.lang.reflect.Array#newInstance(Class, int)
4357      * @jvms 6.5 {@code anewarray} Instruction
4358      * @since 9
4359      */
4360     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4361         if (!arrayClass.isArray()) {
4362             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4363         }
4364         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4365                 bindTo(arrayClass.getComponentType());
4366         return ani.asType(ani.type().changeReturnType(arrayClass));
4367     }
4368 
4369     /**
4370      * Produces a method handle returning the length of an array,
4371      * as if by the {@code arraylength} bytecode.
4372      * The type of the method handle will have {@code int} as return type,
4373      * and its sole argument will be the array type.
4374      *
4375      * <p> If the returned method handle is invoked with a {@code null}
4376      * array reference, a {@code NullPointerException} will be thrown.
4377      *
4378      * @param arrayClass an array type
4379      * @return a method handle which can retrieve the length of an array of the given array type
4380      * @throws NullPointerException if the argument is {@code null}
4381      * @throws IllegalArgumentException if arrayClass is not an array type
4382      * @jvms 6.5 {@code arraylength} Instruction
4383      * @since 9
4384      */
4385     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4386         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4387     }
4388 
4389     /**
4390      * Produces a method handle giving read access to elements of an array,
4391      * as if by the {@code aaload} bytecode.
4392      * The type of the method handle will have a return type of the array's
4393      * element type.  Its first argument will be the array type,
4394      * and the second will be {@code int}.
4395      *
4396      * <p> When the returned method handle is invoked,
4397      * the array reference and array index are checked.
4398      * A {@code NullPointerException} will be thrown if the array reference
4399      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4400      * thrown if the index is negative or if it is greater than or equal to
4401      * the length of the array.
4402      *
4403      * @param arrayClass an array type
4404      * @return a method handle which can load values from the given array type
4405      * @throws NullPointerException if the argument is null
4406      * @throws  IllegalArgumentException if arrayClass is not an array type
4407      * @jvms 6.5 {@code aaload} Instruction
4408      */
4409     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4410         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4411     }
4412 
4413     /**
4414      * Produces a method handle giving write access to elements of an array,
4415      * as if by the {@code astore} bytecode.
4416      * The type of the method handle will have a void return type.
4417      * Its last argument will be the array's element type.
4418      * The first and second arguments will be the array type and int.
4419      *
4420      * <p> When the returned method handle is invoked,
4421      * the array reference and array index are checked.
4422      * A {@code NullPointerException} will be thrown if the array reference
4423      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4424      * thrown if the index is negative or if it is greater than or equal to
4425      * the length of the array.
4426      *
4427      * @param arrayClass the class of an array
4428      * @return a method handle which can store values into the array type
4429      * @throws NullPointerException if the argument is null
4430      * @throws IllegalArgumentException if arrayClass is not an array type
4431      * @jvms 6.5 {@code aastore} Instruction
4432      */
4433     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4434         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4435     }
4436 
4437     /**
4438      * Produces a VarHandle giving access to elements of an array of type
4439      * {@code arrayClass}.  The VarHandle's variable type is the component type
4440      * of {@code arrayClass} and the list of coordinate types is
4441      * {@code (arrayClass, int)}, where the {@code int} coordinate type
4442      * corresponds to an argument that is an index into an array.
4443      * <p>
4444      * Certain access modes of the returned VarHandle are unsupported under
4445      * the following conditions:
4446      * <ul>
4447      * <li>if the component type is anything other than {@code byte},
4448      *     {@code short}, {@code char}, {@code int}, {@code long},
4449      *     {@code float}, or {@code double} then numeric atomic update access
4450      *     modes are unsupported.
4451      * <li>if the component type is anything other than {@code boolean},
4452      *     {@code byte}, {@code short}, {@code char}, {@code int} or
4453      *     {@code long} then bitwise atomic update access modes are
4454      *     unsupported.
4455      * </ul>
4456      * <p>
4457      * If the component type is {@code float} or {@code double} then numeric
4458      * and atomic update access modes compare values using their bitwise
4459      * representation (see {@link Float#floatToRawIntBits} and
4460      * {@link Double#doubleToRawLongBits}, respectively).
4461      *
4462      * <p> When the returned {@code VarHandle} is invoked,
4463      * the array reference and array index are checked.
4464      * A {@code NullPointerException} will be thrown if the array reference
4465      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4466      * thrown if the index is negative or if it is greater than or equal to
4467      * the length of the array.
4468      *
4469      * @apiNote
4470      * Bitwise comparison of {@code float} values or {@code double} values,
4471      * as performed by the numeric and atomic update access modes, differ
4472      * from the primitive {@code ==} operator and the {@link Float#equals}
4473      * and {@link Double#equals} methods, specifically with respect to
4474      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4475      * Care should be taken when performing a compare and set or a compare
4476      * and exchange operation with such values since the operation may
4477      * unexpectedly fail.
4478      * There are many possible NaN values that are considered to be
4479      * {@code NaN} in Java, although no IEEE 754 floating-point operation
4480      * provided by Java can distinguish between them.  Operation failure can
4481      * occur if the expected or witness value is a NaN value and it is
4482      * transformed (perhaps in a platform specific manner) into another NaN
4483      * value, and thus has a different bitwise representation (see
4484      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4485      * details).
4486      * The values {@code -0.0} and {@code +0.0} have different bitwise
4487      * representations but are considered equal when using the primitive
4488      * {@code ==} operator.  Operation failure can occur if, for example, a
4489      * numeric algorithm computes an expected value to be say {@code -0.0}
4490      * and previously computed the witness value to be say {@code +0.0}.
4491      * @param arrayClass the class of an array, of type {@code T[]}
4492      * @return a VarHandle giving access to elements of an array
4493      * @throws NullPointerException if the arrayClass is null
4494      * @throws IllegalArgumentException if arrayClass is not an array type
4495      * @since 9
4496      */
4497     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4498         return VarHandles.makeArrayElementHandle(arrayClass);
4499     }
4500 
4501     /**
4502      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4503      * viewed as if it were a different primitive array type, such as
4504      * {@code int[]} or {@code long[]}.
4505      * The VarHandle's variable type is the component type of
4506      * {@code viewArrayClass} and the list of coordinate types is
4507      * {@code (byte[], int)}, where the {@code int} coordinate type
4508      * corresponds to an argument that is an index into a {@code byte[]} array.
4509      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4510      * array, composing bytes to or from a value of the component type of
4511      * {@code viewArrayClass} according to the given endianness.
4512      * <p>
4513      * The supported component types (variables types) are {@code short},
4514      * {@code char}, {@code int}, {@code long}, {@code float} and
4515      * {@code double}.
4516      * <p>
4517      * Access of bytes at a given index will result in an
4518      * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4519      * or greater than the {@code byte[]} array length minus the size (in bytes)
4520      * of {@code T}.
4521      * <p>
4522      * Access of bytes at an index may be aligned or misaligned for {@code T},
4523      * with respect to the underlying memory address, {@code A} say, associated
4524      * with the array and index.
4525      * If access is misaligned then access for anything other than the
4526      * {@code get} and {@code set} access modes will result in an
4527      * {@code IllegalStateException}.  In such cases atomic access is only
4528      * guaranteed with respect to the largest power of two that divides the GCD
4529      * of {@code A} and the size (in bytes) of {@code T}.
4530      * If access is aligned then following access modes are supported and are
4531      * guaranteed to support atomic access:
4532      * <ul>
4533      * <li>read write access modes for all {@code T}, with the exception of
4534      *     access modes {@code get} and {@code set} for {@code long} and
4535      *     {@code double} on 32-bit platforms.
4536      * <li>atomic update access modes for {@code int}, {@code long},
4537      *     {@code float} or {@code double}.
4538      *     (Future major platform releases of the JDK may support additional
4539      *     types for certain currently unsupported access modes.)
4540      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4541      *     (Future major platform releases of the JDK may support additional
4542      *     numeric types for certain currently unsupported access modes.)
4543      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4544      *     (Future major platform releases of the JDK may support additional
4545      *     numeric types for certain currently unsupported access modes.)
4546      * </ul>
4547      * <p>
4548      * Misaligned access, and therefore atomicity guarantees, may be determined
4549      * for {@code byte[]} arrays without operating on a specific array.  Given
4550      * an {@code index}, {@code T} and its corresponding boxed type,
4551      * {@code T_BOX}, misalignment may be determined as follows:
4552      * <pre>{@code
4553      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4554      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
4555      *     alignmentOffset(0, sizeOfT);
4556      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
4557      * boolean isMisaligned = misalignedAtIndex != 0;
4558      * }</pre>
4559      * <p>
4560      * If the variable type is {@code float} or {@code double} then atomic
4561      * update access modes compare values using their bitwise representation
4562      * (see {@link Float#floatToRawIntBits} and
4563      * {@link Double#doubleToRawLongBits}, respectively).
4564      * @param viewArrayClass the view array class, with a component type of
4565      * type {@code T}
4566      * @param byteOrder the endianness of the view array elements, as
4567      * stored in the underlying {@code byte} array
4568      * @return a VarHandle giving access to elements of a {@code byte[]} array
4569      * viewed as if elements corresponding to the components type of the view
4570      * array class
4571      * @throws NullPointerException if viewArrayClass or byteOrder is null
4572      * @throws IllegalArgumentException if viewArrayClass is not an array type
4573      * @throws UnsupportedOperationException if the component type of
4574      * viewArrayClass is not supported as a variable type
4575      * @since 9
4576      */
4577     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4578                                      ByteOrder byteOrder) throws IllegalArgumentException {
4579         Objects.requireNonNull(byteOrder);
4580         return VarHandles.byteArrayViewHandle(viewArrayClass,
4581                                               byteOrder == ByteOrder.BIG_ENDIAN);
4582     }
4583 
4584     /**
4585      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4586      * viewed as if it were an array of elements of a different primitive
4587      * component type to that of {@code byte}, such as {@code int[]} or
4588      * {@code long[]}.
4589      * The VarHandle's variable type is the component type of
4590      * {@code viewArrayClass} and the list of coordinate types is
4591      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4592      * corresponds to an argument that is an index into a {@code byte[]} array.
4593      * The returned VarHandle accesses bytes at an index in a
4594      * {@code ByteBuffer}, composing bytes to or from a value of the component
4595      * type of {@code viewArrayClass} according to the given endianness.
4596      * <p>
4597      * The supported component types (variables types) are {@code short},
4598      * {@code char}, {@code int}, {@code long}, {@code float} and
4599      * {@code double}.
4600      * <p>
4601      * Access will result in a {@code ReadOnlyBufferException} for anything
4602      * other than the read access modes if the {@code ByteBuffer} is read-only.
4603      * <p>
4604      * Access of bytes at a given index will result in an
4605      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4606      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4607      * {@code T}.
4608      * <p>
4609      * Access of bytes at an index may be aligned or misaligned for {@code T},
4610      * with respect to the underlying memory address, {@code A} say, associated
4611      * with the {@code ByteBuffer} and index.
4612      * If access is misaligned then access for anything other than the
4613      * {@code get} and {@code set} access modes will result in an
4614      * {@code IllegalStateException}.  In such cases atomic access is only
4615      * guaranteed with respect to the largest power of two that divides the GCD
4616      * of {@code A} and the size (in bytes) of {@code T}.
4617      * If access is aligned then following access modes are supported and are
4618      * guaranteed to support atomic access:
4619      * <ul>
4620      * <li>read write access modes for all {@code T}, with the exception of
4621      *     access modes {@code get} and {@code set} for {@code long} and
4622      *     {@code double} on 32-bit platforms.
4623      * <li>atomic update access modes for {@code int}, {@code long},
4624      *     {@code float} or {@code double}.
4625      *     (Future major platform releases of the JDK may support additional
4626      *     types for certain currently unsupported access modes.)
4627      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4628      *     (Future major platform releases of the JDK may support additional
4629      *     numeric types for certain currently unsupported access modes.)
4630      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4631      *     (Future major platform releases of the JDK may support additional
4632      *     numeric types for certain currently unsupported access modes.)
4633      * </ul>
4634      * <p>
4635      * Misaligned access, and therefore atomicity guarantees, may be determined
4636      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4637      * {@code index}, {@code T} and its corresponding boxed type,
4638      * {@code T_BOX}, as follows:
4639      * <pre>{@code
4640      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4641      * ByteBuffer bb = ...
4642      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4643      * boolean isMisaligned = misalignedAtIndex != 0;
4644      * }</pre>
4645      * <p>
4646      * If the variable type is {@code float} or {@code double} then atomic
4647      * update access modes compare values using their bitwise representation
4648      * (see {@link Float#floatToRawIntBits} and
4649      * {@link Double#doubleToRawLongBits}, respectively).
4650      * @param viewArrayClass the view array class, with a component type of
4651      * type {@code T}
4652      * @param byteOrder the endianness of the view array elements, as
4653      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4654      * endianness of a {@code ByteBuffer})
4655      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4656      * viewed as if elements corresponding to the components type of the view
4657      * array class
4658      * @throws NullPointerException if viewArrayClass or byteOrder is null
4659      * @throws IllegalArgumentException if viewArrayClass is not an array type
4660      * @throws UnsupportedOperationException if the component type of
4661      * viewArrayClass is not supported as a variable type
4662      * @since 9
4663      */
4664     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4665                                       ByteOrder byteOrder) throws IllegalArgumentException {
4666         Objects.requireNonNull(byteOrder);
4667         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4668                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4669     }
4670 
4671 
4672     /// method handle invocation (reflective style)
4673 
4674     /**
4675      * Produces a method handle which will invoke any method handle of the
4676      * given {@code type}, with a given number of trailing arguments replaced by
4677      * a single trailing {@code Object[]} array.
4678      * The resulting invoker will be a method handle with the following
4679      * arguments:
4680      * <ul>
4681      * <li>a single {@code MethodHandle} target
4682      * <li>zero or more leading values (counted by {@code leadingArgCount})
4683      * <li>an {@code Object[]} array containing trailing arguments
4684      * </ul>
4685      * <p>
4686      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4687      * the indicated {@code type}.
4688      * That is, if the target is exactly of the given {@code type}, it will behave
4689      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4690      * is used to convert the target to the required {@code type}.
4691      * <p>
4692      * The type of the returned invoker will not be the given {@code type}, but rather
4693      * will have all parameters except the first {@code leadingArgCount}
4694      * replaced by a single array of type {@code Object[]}, which will be
4695      * the final parameter.
4696      * <p>
4697      * Before invoking its target, the invoker will spread the final array, apply
4698      * reference casts as necessary, and unbox and widen primitive arguments.
4699      * If, when the invoker is called, the supplied array argument does
4700      * not have the correct number of elements, the invoker will throw
4701      * an {@link IllegalArgumentException} instead of invoking the target.
4702      * <p>
4703      * This method is equivalent to the following code (though it may be more efficient):
4704      * {@snippet lang="java" :
4705 MethodHandle invoker = MethodHandles.invoker(type);
4706 int spreadArgCount = type.parameterCount() - leadingArgCount;
4707 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4708 return invoker;
4709      * }
4710      * This method throws no reflective or security exceptions.
4711      * @param type the desired target type
4712      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4713      * @return a method handle suitable for invoking any method handle of the given type
4714      * @throws NullPointerException if {@code type} is null
4715      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4716      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4717      *                  or if the resulting method handle's type would have
4718      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4719      */
4720     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4721         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4722             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4723         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4724         return type.invokers().spreadInvoker(leadingArgCount);
4725     }
4726 
4727     /**
4728      * Produces a special <em>invoker method handle</em> which can be used to
4729      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4730      * The resulting invoker will have a type which is
4731      * exactly equal to the desired type, except that it will accept
4732      * an additional leading argument of type {@code MethodHandle}.
4733      * <p>
4734      * This method is equivalent to the following code (though it may be more efficient):
4735      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4736      *
4737      * <p style="font-size:smaller;">
4738      * <em>Discussion:</em>
4739      * Invoker method handles can be useful when working with variable method handles
4740      * of unknown types.
4741      * For example, to emulate an {@code invokeExact} call to a variable method
4742      * handle {@code M}, extract its type {@code T},
4743      * look up the invoker method {@code X} for {@code T},
4744      * and call the invoker method, as {@code X.invoke(T, A...)}.
4745      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4746      * is unknown.)
4747      * If spreading, collecting, or other argument transformations are required,
4748      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4749      * method handle values, as long as they are compatible with the type of {@code X}.
4750      * <p style="font-size:smaller;">
4751      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4752      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4753      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4754      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4755      * <p>
4756      * This method throws no reflective or security exceptions.
4757      * @param type the desired target type
4758      * @return a method handle suitable for invoking any method handle of the given type
4759      * @throws IllegalArgumentException if the resulting method handle's type would have
4760      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4761      */
4762     public static MethodHandle exactInvoker(MethodType type) {
4763         return type.invokers().exactInvoker();
4764     }
4765 
4766     /**
4767      * Produces a special <em>invoker method handle</em> which can be used to
4768      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4769      * The resulting invoker will have a type which is
4770      * exactly equal to the desired type, except that it will accept
4771      * an additional leading argument of type {@code MethodHandle}.
4772      * <p>
4773      * Before invoking its target, if the target differs from the expected type,
4774      * the invoker will apply reference casts as
4775      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4776      * Similarly, the return value will be converted as necessary.
4777      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4778      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4779      * <p>
4780      * This method is equivalent to the following code (though it may be more efficient):
4781      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4782      * <p style="font-size:smaller;">
4783      * <em>Discussion:</em>
4784      * A {@linkplain MethodType#genericMethodType general method type} is one which
4785      * mentions only {@code Object} arguments and return values.
4786      * An invoker for such a type is capable of calling any method handle
4787      * of the same arity as the general type.
4788      * <p style="font-size:smaller;">
4789      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4790      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4791      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4792      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4793      * <p>
4794      * This method throws no reflective or security exceptions.
4795      * @param type the desired target type
4796      * @return a method handle suitable for invoking any method handle convertible to the given type
4797      * @throws IllegalArgumentException if the resulting method handle's type would have
4798      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4799      */
4800     public static MethodHandle invoker(MethodType type) {
4801         return type.invokers().genericInvoker();
4802     }
4803 
4804     /**
4805      * Produces a special <em>invoker method handle</em> which can be used to
4806      * invoke a signature-polymorphic access mode method on any VarHandle whose
4807      * associated access mode type is compatible with the given type.
4808      * The resulting invoker will have a type which is exactly equal to the
4809      * desired given type, except that it will accept an additional leading
4810      * argument of type {@code VarHandle}.
4811      *
4812      * @param accessMode the VarHandle access mode
4813      * @param type the desired target type
4814      * @return a method handle suitable for invoking an access mode method of
4815      *         any VarHandle whose access mode type is of the given type.
4816      * @since 9
4817      */
4818     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4819         return type.invokers().varHandleMethodExactInvoker(accessMode);
4820     }
4821 
4822     /**
4823      * Produces a special <em>invoker method handle</em> which can be used to
4824      * invoke a signature-polymorphic access mode method on any VarHandle whose
4825      * associated access mode type is compatible with the given type.
4826      * The resulting invoker will have a type which is exactly equal to the
4827      * desired given type, except that it will accept an additional leading
4828      * argument of type {@code VarHandle}.
4829      * <p>
4830      * Before invoking its target, if the access mode type differs from the
4831      * desired given type, the invoker will apply reference casts as necessary
4832      * and box, unbox, or widen primitive values, as if by
4833      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4834      * converted as necessary.
4835      * <p>
4836      * This method is equivalent to the following code (though it may be more
4837      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4838      *
4839      * @param accessMode the VarHandle access mode
4840      * @param type the desired target type
4841      * @return a method handle suitable for invoking an access mode method of
4842      *         any VarHandle whose access mode type is convertible to the given
4843      *         type.
4844      * @since 9
4845      */
4846     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4847         return type.invokers().varHandleMethodInvoker(accessMode);
4848     }
4849 
4850     /*non-public*/
4851     static MethodHandle basicInvoker(MethodType type) {
4852         return type.invokers().basicInvoker();
4853     }
4854 
4855      /// method handle modification (creation from other method handles)
4856 
4857     /**
4858      * Produces a method handle which adapts the type of the
4859      * given method handle to a new type by pairwise argument and return type conversion.
4860      * The original type and new type must have the same number of arguments.
4861      * The resulting method handle is guaranteed to report a type
4862      * which is equal to the desired new type.
4863      * <p>
4864      * If the original type and new type are equal, returns target.
4865      * <p>
4866      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4867      * and some additional conversions are also applied if those conversions fail.
4868      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4869      * if possible, before or instead of any conversions done by {@code asType}:
4870      * <ul>
4871      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4872      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4873      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4874      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4875      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4876      *     (This treatment follows the usage of the bytecode verifier.)
4877      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4878      *     <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}),
4879      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4880      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4881      *     then a Java casting conversion (JLS {@jls 5.5}) is applied.
4882      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4883      *     widening and/or narrowing.)
4884      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4885      *     conversion will be applied at runtime, possibly followed
4886      *     by a Java casting conversion (JLS {@jls 5.5}) on the primitive value,
4887      *     possibly followed by a conversion from byte to boolean by testing
4888      *     the low-order bit.
4889      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4890      *     and if the reference is null at runtime, a zero value is introduced.
4891      * </ul>
4892      * @param target the method handle to invoke after arguments are retyped
4893      * @param newType the expected type of the new method handle
4894      * @return a method handle which delegates to the target after performing
4895      *           any necessary argument conversions, and arranges for any
4896      *           necessary return value conversions
4897      * @throws NullPointerException if either argument is null
4898      * @throws WrongMethodTypeException if the conversion cannot be made
4899      * @see MethodHandle#asType
4900      */
4901     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4902         explicitCastArgumentsChecks(target, newType);
4903         // use the asTypeCache when possible:
4904         MethodType oldType = target.type();
4905         if (oldType == newType)  return target;
4906         if (oldType.explicitCastEquivalentToAsType(newType)) {
4907             return target.asFixedArity().asType(newType);
4908         }
4909         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4910     }
4911 
4912     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4913         if (target.type().parameterCount() != newType.parameterCount()) {
4914             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4915         }
4916     }
4917 
4918     /**
4919      * Produces a method handle which adapts the calling sequence of the
4920      * given method handle to a new type, by reordering the arguments.
4921      * The resulting method handle is guaranteed to report a type
4922      * which is equal to the desired new type.
4923      * <p>
4924      * The given array controls the reordering.
4925      * Call {@code #I} the number of incoming parameters (the value
4926      * {@code newType.parameterCount()}, and call {@code #O} the number
4927      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4928      * Then the length of the reordering array must be {@code #O},
4929      * and each element must be a non-negative number less than {@code #I}.
4930      * For every {@code N} less than {@code #O}, the {@code N}-th
4931      * outgoing argument will be taken from the {@code I}-th incoming
4932      * argument, where {@code I} is {@code reorder[N]}.
4933      * <p>
4934      * No argument or return value conversions are applied.
4935      * The type of each incoming argument, as determined by {@code newType},
4936      * must be identical to the type of the corresponding outgoing parameter
4937      * or parameters in the target method handle.
4938      * The return type of {@code newType} must be identical to the return
4939      * type of the original target.
4940      * <p>
4941      * The reordering array need not specify an actual permutation.
4942      * An incoming argument will be duplicated if its index appears
4943      * more than once in the array, and an incoming argument will be dropped
4944      * if its index does not appear in the array.
4945      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4946      * incoming arguments which are not mentioned in the reordering array
4947      * may be of any type, as determined only by {@code newType}.
4948      * {@snippet lang="java" :
4949 import static java.lang.invoke.MethodHandles.*;
4950 import static java.lang.invoke.MethodType.*;
4951 ...
4952 MethodType intfn1 = methodType(int.class, int.class);
4953 MethodType intfn2 = methodType(int.class, int.class, int.class);
4954 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4955 assert(sub.type().equals(intfn2));
4956 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4957 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4958 assert((int)rsub.invokeExact(1, 100) == 99);
4959 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4960 assert(add.type().equals(intfn2));
4961 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4962 assert(twice.type().equals(intfn1));
4963 assert((int)twice.invokeExact(21) == 42);
4964      * }
4965      * <p>
4966      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4967      * variable-arity method handle}, even if the original target method handle was.
4968      * @param target the method handle to invoke after arguments are reordered
4969      * @param newType the expected type of the new method handle
4970      * @param reorder an index array which controls the reordering
4971      * @return a method handle which delegates to the target after it
4972      *           drops unused arguments and moves and/or duplicates the other arguments
4973      * @throws NullPointerException if any argument is null
4974      * @throws IllegalArgumentException if the index array length is not equal to
4975      *                  the arity of the target, or if any index array element
4976      *                  not a valid index for a parameter of {@code newType},
4977      *                  or if two corresponding parameter types in
4978      *                  {@code target.type()} and {@code newType} are not identical,
4979      */
4980     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4981         reorder = reorder.clone();  // get a private copy
4982         MethodType oldType = target.type();
4983         permuteArgumentChecks(reorder, newType, oldType);
4984         // first detect dropped arguments and handle them separately
4985         int[] originalReorder = reorder;
4986         BoundMethodHandle result = target.rebind();
4987         LambdaForm form = result.form;
4988         int newArity = newType.parameterCount();
4989         // Normalize the reordering into a real permutation,
4990         // by removing duplicates and adding dropped elements.
4991         // This somewhat improves lambda form caching, as well
4992         // as simplifying the transform by breaking it up into steps.
4993         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4994             if (ddIdx > 0) {
4995                 // We found a duplicated entry at reorder[ddIdx].
4996                 // Example:  (x,y,z)->asList(x,y,z)
4997                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4998                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4999                 // The starred element corresponds to the argument
5000                 // deleted by the dupArgumentForm transform.
5001                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
5002                 boolean killFirst = false;
5003                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
5004                     // Set killFirst if the dup is larger than an intervening position.
5005                     // This will remove at least one inversion from the permutation.
5006                     if (dupVal > val) killFirst = true;
5007                 }
5008                 if (!killFirst) {
5009                     srcPos = dstPos;
5010                     dstPos = ddIdx;
5011                 }
5012                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
5013                 assert (reorder[srcPos] == reorder[dstPos]);
5014                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
5015                 // contract the reordering by removing the element at dstPos
5016                 int tailPos = dstPos + 1;
5017                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
5018                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
5019             } else {
5020                 int dropVal = ~ddIdx, insPos = 0;
5021                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
5022                     // Find first element of reorder larger than dropVal.
5023                     // This is where we will insert the dropVal.
5024                     insPos += 1;
5025                 }
5026                 Class<?> ptype = newType.parameterType(dropVal);
5027                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
5028                 oldType = oldType.insertParameterTypes(insPos, ptype);
5029                 // expand the reordering by inserting an element at insPos
5030                 int tailPos = insPos + 1;
5031                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
5032                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
5033                 reorder[insPos] = dropVal;
5034             }
5035             assert (permuteArgumentChecks(reorder, newType, oldType));
5036         }
5037         assert (reorder.length == newArity);  // a perfect permutation
5038         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
5039         form = form.editor().permuteArgumentsForm(1, reorder);
5040         if (newType == result.type() && form == result.internalForm())
5041             return result;
5042         return result.copyWith(newType, form);
5043     }
5044 
5045     /**
5046      * Return an indication of any duplicate or omission in reorder.
5047      * If the reorder contains a duplicate entry, return the index of the second occurrence.
5048      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
5049      * Otherwise, return zero.
5050      * If an element not in [0..newArity-1] is encountered, return reorder.length.
5051      */
5052     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
5053         final int BIT_LIMIT = 63;  // max number of bits in bit mask
5054         if (newArity < BIT_LIMIT) {
5055             long mask = 0;
5056             for (int i = 0; i < reorder.length; i++) {
5057                 int arg = reorder[i];
5058                 if (arg >= newArity) {
5059                     return reorder.length;
5060                 }
5061                 long bit = 1L << arg;
5062                 if ((mask & bit) != 0) {
5063                     return i;  // >0 indicates a dup
5064                 }
5065                 mask |= bit;
5066             }
5067             if (mask == (1L << newArity) - 1) {
5068                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
5069                 return 0;
5070             }
5071             // find first zero
5072             long zeroBit = Long.lowestOneBit(~mask);
5073             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
5074             assert(zeroPos <= newArity);
5075             if (zeroPos == newArity) {
5076                 return 0;
5077             }
5078             return ~zeroPos;
5079         } else {
5080             // same algorithm, different bit set
5081             BitSet mask = new BitSet(newArity);
5082             for (int i = 0; i < reorder.length; i++) {
5083                 int arg = reorder[i];
5084                 if (arg >= newArity) {
5085                     return reorder.length;
5086                 }
5087                 if (mask.get(arg)) {
5088                     return i;  // >0 indicates a dup
5089                 }
5090                 mask.set(arg);
5091             }
5092             int zeroPos = mask.nextClearBit(0);
5093             assert(zeroPos <= newArity);
5094             if (zeroPos == newArity) {
5095                 return 0;
5096             }
5097             return ~zeroPos;
5098         }
5099     }
5100 
5101     static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
5102         if (newType.returnType() != oldType.returnType())
5103             throw newIllegalArgumentException("return types do not match",
5104                     oldType, newType);
5105         if (reorder.length != oldType.parameterCount())
5106             throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
5107                     oldType, Arrays.toString(reorder));
5108 
5109         int limit = newType.parameterCount();
5110         for (int j = 0; j < reorder.length; j++) {
5111             int i = reorder[j];
5112             if (i < 0 || i >= limit) {
5113                 throw newIllegalArgumentException("index is out of bounds for new type",
5114                         i, newType);
5115             }
5116             Class<?> src = newType.parameterType(i);
5117             Class<?> dst = oldType.parameterType(j);
5118             if (src != dst)
5119                 throw newIllegalArgumentException("parameter types do not match after reorder",
5120                         oldType, newType);
5121         }
5122         return true;
5123     }
5124 
5125     /**
5126      * Produces a method handle of the requested return type which returns the given
5127      * constant value every time it is invoked.
5128      * <p>
5129      * Before the method handle is returned, the passed-in value is converted to the requested type.
5130      * If the requested type is primitive, widening primitive conversions are attempted,
5131      * else reference conversions are attempted.
5132      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5133      * @param type the return type of the desired method handle
5134      * @param value the value to return
5135      * @return a method handle of the given return type and no arguments, which always returns the given value
5136      * @throws NullPointerException if the {@code type} argument is null
5137      * @throws ClassCastException if the value cannot be converted to the required return type
5138      * @throws IllegalArgumentException if the given type is {@code void.class}
5139      */
5140     public static MethodHandle constant(Class<?> type, Object value) {
5141         if (type.isPrimitive()) {
5142             if (type == void.class)
5143                 throw newIllegalArgumentException("void type");
5144             Wrapper w = Wrapper.forPrimitiveType(type);
5145             value = w.convert(value, type);
5146             if (w.zero().equals(value))
5147                 return zero(w, type);
5148             return insertArguments(identity(type), 0, value);
5149         } else {
5150             if (value == null)
5151                 return zero(Wrapper.OBJECT, type);
5152             return identity(type).bindTo(value);
5153         }
5154     }
5155 
5156     /**
5157      * Produces a method handle which returns its sole argument when invoked.
5158      * @param type the type of the sole parameter and return value of the desired method handle
5159      * @return a unary method handle which accepts and returns the given type
5160      * @throws NullPointerException if the argument is null
5161      * @throws IllegalArgumentException if the given type is {@code void.class}
5162      */
5163     public static MethodHandle identity(Class<?> type) {
5164         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5165         int pos = btw.ordinal();
5166         MethodHandle ident = IDENTITY_MHS[pos];
5167         if (ident == null) {
5168             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5169         }
5170         if (ident.type().returnType() == type)
5171             return ident;
5172         // something like identity(Foo.class); do not bother to intern these
5173         assert (btw == Wrapper.OBJECT);
5174         return makeIdentity(type);
5175     }
5176 
5177     /**
5178      * Produces a constant method handle of the requested return type which
5179      * returns the default value for that type every time it is invoked.
5180      * The resulting constant method handle will have no side effects.
5181      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5182      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5183      * since {@code explicitCastArguments} converts {@code null} to default values.
5184      * @param type the expected return type of the desired method handle
5185      * @return a constant method handle that takes no arguments
5186      *         and returns the default value of the given type (or void, if the type is void)
5187      * @throws NullPointerException if the argument is null
5188      * @see MethodHandles#constant
5189      * @see MethodHandles#empty
5190      * @see MethodHandles#explicitCastArguments
5191      * @since 9
5192      */
5193     public static MethodHandle zero(Class<?> type) {
5194         Objects.requireNonNull(type);
5195         return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
5196     }
5197 
5198     private static MethodHandle identityOrVoid(Class<?> type) {
5199         return type == void.class ? zero(type) : identity(type);
5200     }
5201 
5202     /**
5203      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5204      * and returns a suitable default depending on the return type.
5205      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
5206      * <p>The returned method handle is equivalent to
5207      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5208      *
5209      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5210      * {@code guardWithTest(pred, target, empty(target.type())}.
5211      * @param type the type of the desired method handle
5212      * @return a constant method handle of the given type, which returns a default value of the given return type
5213      * @throws NullPointerException if the argument is null
5214      * @see MethodHandles#zero
5215      * @see MethodHandles#constant
5216      * @since 9
5217      */
5218     public static  MethodHandle empty(MethodType type) {
5219         Objects.requireNonNull(type);
5220         return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes());
5221     }
5222 
5223     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5224     private static MethodHandle makeIdentity(Class<?> ptype) {
5225         MethodType mtype = methodType(ptype, ptype);
5226         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5227         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5228     }
5229 
5230     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5231         int pos = btw.ordinal();
5232         MethodHandle zero = ZERO_MHS[pos];
5233         if (zero == null) {
5234             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5235         }
5236         if (zero.type().returnType() == rtype)
5237             return zero;
5238         assert(btw == Wrapper.OBJECT);
5239         return makeZero(rtype);
5240     }
5241     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5242     private static MethodHandle makeZero(Class<?> rtype) {
5243         MethodType mtype = methodType(rtype);
5244         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5245         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
5246     }
5247 
5248     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
5249         // Simulate a CAS, to avoid racy duplication of results.
5250         MethodHandle prev = cache[pos];
5251         if (prev != null) return prev;
5252         return cache[pos] = value;
5253     }
5254 
5255     /**
5256      * Provides a target method handle with one or more <em>bound arguments</em>
5257      * in advance of the method handle's invocation.
5258      * The formal parameters to the target corresponding to the bound
5259      * arguments are called <em>bound parameters</em>.
5260      * Returns a new method handle which saves away the bound arguments.
5261      * When it is invoked, it receives arguments for any non-bound parameters,
5262      * binds the saved arguments to their corresponding parameters,
5263      * and calls the original target.
5264      * <p>
5265      * The type of the new method handle will drop the types for the bound
5266      * parameters from the original target type, since the new method handle
5267      * will no longer require those arguments to be supplied by its callers.
5268      * <p>
5269      * Each given argument object must match the corresponding bound parameter type.
5270      * If a bound parameter type is a primitive, the argument object
5271      * must be a wrapper, and will be unboxed to produce the primitive value.
5272      * <p>
5273      * The {@code pos} argument selects which parameters are to be bound.
5274      * It may range between zero and <i>N-L</i> (inclusively),
5275      * where <i>N</i> is the arity of the target method handle
5276      * and <i>L</i> is the length of the values array.
5277      * <p>
5278      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5279      * variable-arity method handle}, even if the original target method handle was.
5280      * @param target the method handle to invoke after the argument is inserted
5281      * @param pos where to insert the argument (zero for the first)
5282      * @param values the series of arguments to insert
5283      * @return a method handle which inserts an additional argument,
5284      *         before calling the original method handle
5285      * @throws NullPointerException if the target or the {@code values} array is null
5286      * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than
5287      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
5288      *         is the length of the values array.
5289      * @throws ClassCastException if an argument does not match the corresponding bound parameter
5290      *         type.
5291      * @see MethodHandle#bindTo
5292      */
5293     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
5294         int insCount = values.length;
5295         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
5296         if (insCount == 0)  return target;
5297         BoundMethodHandle result = target.rebind();
5298         for (int i = 0; i < insCount; i++) {
5299             Object value = values[i];
5300             Class<?> ptype = ptypes[pos+i];
5301             if (ptype.isPrimitive()) {
5302                 result = insertArgumentPrimitive(result, pos, ptype, value);
5303             } else {
5304                 value = ptype.cast(value);  // throw CCE if needed
5305                 result = result.bindArgumentL(pos, value);
5306             }
5307         }
5308         return result;
5309     }
5310 
5311     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5312                                                              Class<?> ptype, Object value) {
5313         Wrapper w = Wrapper.forPrimitiveType(ptype);
5314         // perform unboxing and/or primitive conversion
5315         value = w.convert(value, ptype);
5316         return switch (w) {
5317             case INT    -> result.bindArgumentI(pos, (int) value);
5318             case LONG   -> result.bindArgumentJ(pos, (long) value);
5319             case FLOAT  -> result.bindArgumentF(pos, (float) value);
5320             case DOUBLE -> result.bindArgumentD(pos, (double) value);
5321             default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5322         };
5323     }
5324 
5325     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5326         MethodType oldType = target.type();
5327         int outargs = oldType.parameterCount();
5328         int inargs  = outargs - insCount;
5329         if (inargs < 0)
5330             throw newIllegalArgumentException("too many values to insert");
5331         if (pos < 0 || pos > inargs)
5332             throw newIllegalArgumentException("no argument type to append");
5333         return oldType.ptypes();
5334     }
5335 
5336     /**
5337      * Produces a method handle which will discard some dummy arguments
5338      * before calling some other specified <i>target</i> method handle.
5339      * The type of the new method handle will be the same as the target's type,
5340      * except it will also include the dummy argument types,
5341      * at some given position.
5342      * <p>
5343      * The {@code pos} argument may range between zero and <i>N</i>,
5344      * where <i>N</i> is the arity of the target.
5345      * If {@code pos} is zero, the dummy arguments will precede
5346      * the target's real arguments; if {@code pos} is <i>N</i>
5347      * they will come after.
5348      * <p>
5349      * <b>Example:</b>
5350      * {@snippet lang="java" :
5351 import static java.lang.invoke.MethodHandles.*;
5352 import static java.lang.invoke.MethodType.*;
5353 ...
5354 MethodHandle cat = lookup().findVirtual(String.class,
5355   "concat", methodType(String.class, String.class));
5356 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5357 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5358 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5359 assertEquals(bigType, d0.type());
5360 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5361      * }
5362      * <p>
5363      * This method is also equivalent to the following code:
5364      * <blockquote><pre>
5365      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5366      * </pre></blockquote>
5367      * @param target the method handle to invoke after the arguments are dropped
5368      * @param pos position of first argument to drop (zero for the leftmost)
5369      * @param valueTypes the type(s) of the argument(s) to drop
5370      * @return a method handle which drops arguments of the given types,
5371      *         before calling the original method handle
5372      * @throws NullPointerException if the target is null,
5373      *                              or if the {@code valueTypes} list or any of its elements is null
5374      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5375      *                  or if {@code pos} is negative or greater than the arity of the target,
5376      *                  or if the new method handle's type would have too many parameters
5377      */
5378     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5379         return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone());
5380     }
5381 
5382     static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) {
5383         MethodType oldType = target.type();  // get NPE
5384         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5385         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5386         if (dropped == 0)  return target;
5387         BoundMethodHandle result = target.rebind();
5388         LambdaForm lform = result.form;
5389         int insertFormArg = 1 + pos;
5390         for (Class<?> ptype : valueTypes) {
5391             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5392         }
5393         result = result.copyWith(newType, lform);
5394         return result;
5395     }
5396 
5397     private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) {
5398         int dropped = valueTypes.length;
5399         MethodType.checkSlotCount(dropped);
5400         int outargs = oldType.parameterCount();
5401         int inargs  = outargs + dropped;
5402         if (pos < 0 || pos > outargs)
5403             throw newIllegalArgumentException("no argument type to remove"
5404                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5405                     );
5406         return dropped;
5407     }
5408 
5409     /**
5410      * Produces a method handle which will discard some dummy arguments
5411      * before calling some other specified <i>target</i> method handle.
5412      * The type of the new method handle will be the same as the target's type,
5413      * except it will also include the dummy argument types,
5414      * at some given position.
5415      * <p>
5416      * The {@code pos} argument may range between zero and <i>N</i>,
5417      * where <i>N</i> is the arity of the target.
5418      * If {@code pos} is zero, the dummy arguments will precede
5419      * the target's real arguments; if {@code pos} is <i>N</i>
5420      * they will come after.
5421      * @apiNote
5422      * {@snippet lang="java" :
5423 import static java.lang.invoke.MethodHandles.*;
5424 import static java.lang.invoke.MethodType.*;
5425 ...
5426 MethodHandle cat = lookup().findVirtual(String.class,
5427   "concat", methodType(String.class, String.class));
5428 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5429 MethodHandle d0 = dropArguments(cat, 0, String.class);
5430 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5431 MethodHandle d1 = dropArguments(cat, 1, String.class);
5432 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5433 MethodHandle d2 = dropArguments(cat, 2, String.class);
5434 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5435 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5436 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5437      * }
5438      * <p>
5439      * This method is also equivalent to the following code:
5440      * <blockquote><pre>
5441      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5442      * </pre></blockquote>
5443      * @param target the method handle to invoke after the arguments are dropped
5444      * @param pos position of first argument to drop (zero for the leftmost)
5445      * @param valueTypes the type(s) of the argument(s) to drop
5446      * @return a method handle which drops arguments of the given types,
5447      *         before calling the original method handle
5448      * @throws NullPointerException if the target is null,
5449      *                              or if the {@code valueTypes} array or any of its elements is null
5450      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5451      *                  or if {@code pos} is negative or greater than the arity of the target,
5452      *                  or if the new method handle's type would have
5453      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
5454      */
5455     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5456         return dropArgumentsTrusted(target, pos, valueTypes.clone());
5457     }
5458 
5459     /* Convenience overloads for trusting internal low-arity call-sites */
5460     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) {
5461         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 });
5462     }
5463     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) {
5464         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 });
5465     }
5466 
5467     // private version which allows caller some freedom with error handling
5468     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos,
5469                                       boolean nullOnFailure) {
5470         Class<?>[] oldTypes = target.type().ptypes();
5471         int match = oldTypes.length;
5472         if (skip != 0) {
5473             if (skip < 0 || skip > match) {
5474                 throw newIllegalArgumentException("illegal skip", skip, target);
5475             }
5476             oldTypes = Arrays.copyOfRange(oldTypes, skip, match);
5477             match -= skip;
5478         }
5479         Class<?>[] addTypes = newTypes;
5480         int add = addTypes.length;
5481         if (pos != 0) {
5482             if (pos < 0 || pos > add) {
5483                 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes));
5484             }
5485             addTypes = Arrays.copyOfRange(addTypes, pos, add);
5486             add -= pos;
5487             assert(addTypes.length == add);
5488         }
5489         // Do not add types which already match the existing arguments.
5490         if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) {
5491             if (nullOnFailure) {
5492                 return null;
5493             }
5494             throw newIllegalArgumentException("argument lists do not match",
5495                 Arrays.toString(oldTypes), Arrays.toString(newTypes));
5496         }
5497         addTypes = Arrays.copyOfRange(addTypes, match, add);
5498         add -= match;
5499         assert(addTypes.length == add);
5500         // newTypes:     (   P*[pos], M*[match], A*[add] )
5501         // target: ( S*[skip],        M*[match]  )
5502         MethodHandle adapter = target;
5503         if (add > 0) {
5504             adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes);
5505         }
5506         // adapter: (S*[skip],        M*[match], A*[add] )
5507         if (pos > 0) {
5508             adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos));
5509         }
5510         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5511         return adapter;
5512     }
5513 
5514     /**
5515      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5516      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5517      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5518      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5519      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5520      * {@link #dropArguments(MethodHandle, int, Class[])}.
5521      * <p>
5522      * The resulting handle will have the same return type as the target handle.
5523      * <p>
5524      * In more formal terms, assume these two type lists:<ul>
5525      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5526      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5527      * {@code newTypes}.
5528      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5529      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5530      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5531      * sub-list.
5532      * </ul>
5533      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5534      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5535      * {@link #dropArguments(MethodHandle, int, Class[])}.
5536      *
5537      * @apiNote
5538      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5539      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5540      * {@snippet lang="java" :
5541 import static java.lang.invoke.MethodHandles.*;
5542 import static java.lang.invoke.MethodType.*;
5543 ...
5544 ...
5545 MethodHandle h0 = constant(boolean.class, true);
5546 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5547 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5548 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5549 if (h1.type().parameterCount() < h2.type().parameterCount())
5550     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5551 else
5552     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5553 MethodHandle h3 = guardWithTest(h0, h1, h2);
5554 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5555      * }
5556      * @param target the method handle to adapt
5557      * @param skip number of targets parameters to disregard (they will be unchanged)
5558      * @param newTypes the list of types to match {@code target}'s parameter type list to
5559      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5560      * @return a possibly adapted method handle
5561      * @throws NullPointerException if either argument is null
5562      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5563      *         or if {@code skip} is negative or greater than the arity of the target,
5564      *         or if {@code pos} is negative or greater than the newTypes list size,
5565      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5566      *         {@code pos}.
5567      * @since 9
5568      */
5569     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5570         Objects.requireNonNull(target);
5571         Objects.requireNonNull(newTypes);
5572         return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false);
5573     }
5574 
5575     /**
5576      * Drop the return value of the target handle (if any).
5577      * The returned method handle will have a {@code void} return type.
5578      *
5579      * @param target the method handle to adapt
5580      * @return a possibly adapted method handle
5581      * @throws NullPointerException if {@code target} is null
5582      * @since 16
5583      */
5584     public static MethodHandle dropReturn(MethodHandle target) {
5585         Objects.requireNonNull(target);
5586         MethodType oldType = target.type();
5587         Class<?> oldReturnType = oldType.returnType();
5588         if (oldReturnType == void.class)
5589             return target;
5590         MethodType newType = oldType.changeReturnType(void.class);
5591         BoundMethodHandle result = target.rebind();
5592         LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5593         result = result.copyWith(newType, lform);
5594         return result;
5595     }
5596 
5597     /**
5598      * Adapts a target method handle by pre-processing
5599      * one or more of its arguments, each with its own unary filter function,
5600      * and then calling the target with each pre-processed argument
5601      * replaced by the result of its corresponding filter function.
5602      * <p>
5603      * The pre-processing is performed by one or more method handles,
5604      * specified in the elements of the {@code filters} array.
5605      * The first element of the filter array corresponds to the {@code pos}
5606      * argument of the target, and so on in sequence.
5607      * The filter functions are invoked in left to right order.
5608      * <p>
5609      * Null arguments in the array are treated as identity functions,
5610      * and the corresponding arguments left unchanged.
5611      * (If there are no non-null elements in the array, the original target is returned.)
5612      * Each filter is applied to the corresponding argument of the adapter.
5613      * <p>
5614      * If a filter {@code F} applies to the {@code N}th argument of
5615      * the target, then {@code F} must be a method handle which
5616      * takes exactly one argument.  The type of {@code F}'s sole argument
5617      * replaces the corresponding argument type of the target
5618      * in the resulting adapted method handle.
5619      * The return type of {@code F} must be identical to the corresponding
5620      * parameter type of the target.
5621      * <p>
5622      * It is an error if there are elements of {@code filters}
5623      * (null or not)
5624      * which do not correspond to argument positions in the target.
5625      * <p><b>Example:</b>
5626      * {@snippet lang="java" :
5627 import static java.lang.invoke.MethodHandles.*;
5628 import static java.lang.invoke.MethodType.*;
5629 ...
5630 MethodHandle cat = lookup().findVirtual(String.class,
5631   "concat", methodType(String.class, String.class));
5632 MethodHandle upcase = lookup().findVirtual(String.class,
5633   "toUpperCase", methodType(String.class));
5634 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5635 MethodHandle f0 = filterArguments(cat, 0, upcase);
5636 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5637 MethodHandle f1 = filterArguments(cat, 1, upcase);
5638 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5639 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5640 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5641      * }
5642      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5643      * denotes the return type of both the {@code target} and resulting adapter.
5644      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5645      * of the parameters and arguments that precede and follow the filter position
5646      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5647      * values of the filtered parameters and arguments; they also represent the
5648      * return types of the {@code filter[i]} handles. The latter accept arguments
5649      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5650      * the resulting adapter.
5651      * {@snippet lang="java" :
5652      * T target(P... p, A[i]... a[i], B... b);
5653      * A[i] filter[i](V[i]);
5654      * T adapter(P... p, V[i]... v[i], B... b) {
5655      *   return target(p..., filter[i](v[i])..., b...);
5656      * }
5657      * }
5658      * <p>
5659      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5660      * variable-arity method handle}, even if the original target method handle was.
5661      *
5662      * @param target the method handle to invoke after arguments are filtered
5663      * @param pos the position of the first argument to filter
5664      * @param filters method handles to call initially on filtered arguments
5665      * @return method handle which incorporates the specified argument filtering logic
5666      * @throws NullPointerException if the target is null
5667      *                              or if the {@code filters} array is null
5668      * @throws IllegalArgumentException if a non-null element of {@code filters}
5669      *          does not match a corresponding argument type of target as described above,
5670      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5671      *          or if the resulting method handle's type would have
5672      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5673      */
5674     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5675         // In method types arguments start at index 0, while the LF
5676         // editor have the MH receiver at position 0 - adjust appropriately.
5677         final int MH_RECEIVER_OFFSET = 1;
5678         filterArgumentsCheckArity(target, pos, filters);
5679         MethodHandle adapter = target;
5680 
5681         // keep track of currently matched filters, as to optimize repeated filters
5682         int index = 0;
5683         int[] positions = new int[filters.length];
5684         MethodHandle filter = null;
5685 
5686         // process filters in reverse order so that the invocation of
5687         // the resulting adapter will invoke the filters in left-to-right order
5688         for (int i = filters.length - 1; i >= 0; --i) {
5689             MethodHandle newFilter = filters[i];
5690             if (newFilter == null) continue;  // ignore null elements of filters
5691 
5692             // flush changes on update
5693             if (filter != newFilter) {
5694                 if (filter != null) {
5695                     if (index > 1) {
5696                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5697                     } else {
5698                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5699                     }
5700                 }
5701                 filter = newFilter;
5702                 index = 0;
5703             }
5704 
5705             filterArgumentChecks(target, pos + i, newFilter);
5706             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5707         }
5708         if (index > 1) {
5709             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5710         } else if (index == 1) {
5711             adapter = filterArgument(adapter, positions[0] - 1, filter);
5712         }
5713         return adapter;
5714     }
5715 
5716     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5717         MethodType targetType = adapter.type();
5718         MethodType filterType = filter.type();
5719         BoundMethodHandle result = adapter.rebind();
5720         Class<?> newParamType = filterType.parameterType(0);
5721 
5722         Class<?>[] ptypes = targetType.ptypes().clone();
5723         for (int pos : positions) {
5724             ptypes[pos - 1] = newParamType;
5725         }
5726         MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true);
5727 
5728         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5729         return result.copyWithExtendL(newType, lform, filter);
5730     }
5731 
5732     /*non-public*/
5733     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5734         filterArgumentChecks(target, pos, filter);
5735         MethodType targetType = target.type();
5736         MethodType filterType = filter.type();
5737         BoundMethodHandle result = target.rebind();
5738         Class<?> newParamType = filterType.parameterType(0);
5739         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5740         MethodType newType = targetType.changeParameterType(pos, newParamType);
5741         result = result.copyWithExtendL(newType, lform, filter);
5742         return result;
5743     }
5744 
5745     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5746         MethodType targetType = target.type();
5747         int maxPos = targetType.parameterCount();
5748         if (pos + filters.length > maxPos)
5749             throw newIllegalArgumentException("too many filters");
5750     }
5751 
5752     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5753         MethodType targetType = target.type();
5754         MethodType filterType = filter.type();
5755         if (filterType.parameterCount() != 1
5756             || filterType.returnType() != targetType.parameterType(pos))
5757             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5758     }
5759 
5760     /**
5761      * Adapts a target method handle by pre-processing
5762      * a sub-sequence of its arguments with a filter (another method handle).
5763      * The pre-processed arguments are replaced by the result (if any) of the
5764      * filter function.
5765      * The target is then called on the modified (usually shortened) argument list.
5766      * <p>
5767      * If the filter returns a value, the target must accept that value as
5768      * its argument in position {@code pos}, preceded and/or followed by
5769      * any arguments not passed to the filter.
5770      * If the filter returns void, the target must accept all arguments
5771      * not passed to the filter.
5772      * No arguments are reordered, and a result returned from the filter
5773      * replaces (in order) the whole subsequence of arguments originally
5774      * passed to the adapter.
5775      * <p>
5776      * The argument types (if any) of the filter
5777      * replace zero or one argument types of the target, at position {@code pos},
5778      * in the resulting adapted method handle.
5779      * The return type of the filter (if any) must be identical to the
5780      * argument type of the target at position {@code pos}, and that target argument
5781      * is supplied by the return value of the filter.
5782      * <p>
5783      * In all cases, {@code pos} must be greater than or equal to zero, and
5784      * {@code pos} must also be less than or equal to the target's arity.
5785      * <p><b>Example:</b>
5786      * {@snippet lang="java" :
5787 import static java.lang.invoke.MethodHandles.*;
5788 import static java.lang.invoke.MethodType.*;
5789 ...
5790 MethodHandle deepToString = publicLookup()
5791   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5792 
5793 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5794 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5795 
5796 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5797 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5798 
5799 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5800 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5801 assertEquals("[top, [up, down], strange]",
5802              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5803 
5804 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5805 assertEquals("[top, [up, down], [strange]]",
5806              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5807 
5808 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5809 assertEquals("[top, [[up, down, strange], charm], bottom]",
5810              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5811      * }
5812      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5813      * represents the return type of the {@code target} and resulting adapter.
5814      * {@code V}/{@code v} stand for the return type and value of the
5815      * {@code filter}, which are also found in the signature and arguments of
5816      * the {@code target}, respectively, unless {@code V} is {@code void}.
5817      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5818      * and values preceding and following the collection position, {@code pos},
5819      * in the {@code target}'s signature. They also turn up in the resulting
5820      * adapter's signature and arguments, where they surround
5821      * {@code B}/{@code b}, which represent the parameter types and arguments
5822      * to the {@code filter} (if any).
5823      * {@snippet lang="java" :
5824      * T target(A...,V,C...);
5825      * V filter(B...);
5826      * T adapter(A... a,B... b,C... c) {
5827      *   V v = filter(b...);
5828      *   return target(a...,v,c...);
5829      * }
5830      * // and if the filter has no arguments:
5831      * T target2(A...,V,C...);
5832      * V filter2();
5833      * T adapter2(A... a,C... c) {
5834      *   V v = filter2();
5835      *   return target2(a...,v,c...);
5836      * }
5837      * // and if the filter has a void return:
5838      * T target3(A...,C...);
5839      * void filter3(B...);
5840      * T adapter3(A... a,B... b,C... c) {
5841      *   filter3(b...);
5842      *   return target3(a...,c...);
5843      * }
5844      * }
5845      * <p>
5846      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5847      * one which first "folds" the affected arguments, and then drops them, in separate
5848      * steps as follows:
5849      * {@snippet lang="java" :
5850      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5851      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5852      * }
5853      * If the target method handle consumes no arguments besides than the result
5854      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5855      * is equivalent to {@code filterReturnValue(coll, mh)}.
5856      * If the filter method handle {@code coll} consumes one argument and produces
5857      * a non-void result, then {@code collectArguments(mh, N, coll)}
5858      * is equivalent to {@code filterArguments(mh, N, coll)}.
5859      * Other equivalences are possible but would require argument permutation.
5860      * <p>
5861      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5862      * variable-arity method handle}, even if the original target method handle was.
5863      *
5864      * @param target the method handle to invoke after filtering the subsequence of arguments
5865      * @param pos the position of the first adapter argument to pass to the filter,
5866      *            and/or the target argument which receives the result of the filter
5867      * @param filter method handle to call on the subsequence of arguments
5868      * @return method handle which incorporates the specified argument subsequence filtering logic
5869      * @throws NullPointerException if either argument is null
5870      * @throws IllegalArgumentException if the return type of {@code filter}
5871      *          is non-void and is not the same as the {@code pos} argument of the target,
5872      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5873      *          or if the resulting method handle's type would have
5874      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5875      * @see MethodHandles#foldArguments
5876      * @see MethodHandles#filterArguments
5877      * @see MethodHandles#filterReturnValue
5878      */
5879     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5880         MethodType newType = collectArgumentsChecks(target, pos, filter);
5881         MethodType collectorType = filter.type();
5882         BoundMethodHandle result = target.rebind();
5883         LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5884         return result.copyWithExtendL(newType, lform, filter);
5885     }
5886 
5887     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5888         MethodType targetType = target.type();
5889         MethodType filterType = filter.type();
5890         Class<?> rtype = filterType.returnType();
5891         Class<?>[] filterArgs = filterType.ptypes();
5892         if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5893                        (rtype != void.class && pos >= targetType.parameterCount())) {
5894             throw newIllegalArgumentException("position is out of range for target", target, pos);
5895         }
5896         if (rtype == void.class) {
5897             return targetType.insertParameterTypes(pos, filterArgs);
5898         }
5899         if (rtype != targetType.parameterType(pos)) {
5900             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5901         }
5902         return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs);
5903     }
5904 
5905     /**
5906      * Adapts a target method handle by post-processing
5907      * its return value (if any) with a filter (another method handle).
5908      * The result of the filter is returned from the adapter.
5909      * <p>
5910      * If the target returns a value, the filter must accept that value as
5911      * its only argument.
5912      * If the target returns void, the filter must accept no arguments.
5913      * <p>
5914      * The return type of the filter
5915      * replaces the return type of the target
5916      * in the resulting adapted method handle.
5917      * The argument type of the filter (if any) must be identical to the
5918      * return type of the target.
5919      * <p><b>Example:</b>
5920      * {@snippet lang="java" :
5921 import static java.lang.invoke.MethodHandles.*;
5922 import static java.lang.invoke.MethodType.*;
5923 ...
5924 MethodHandle cat = lookup().findVirtual(String.class,
5925   "concat", methodType(String.class, String.class));
5926 MethodHandle length = lookup().findVirtual(String.class,
5927   "length", methodType(int.class));
5928 System.out.println((String) cat.invokeExact("x", "y")); // xy
5929 MethodHandle f0 = filterReturnValue(cat, length);
5930 System.out.println((int) f0.invokeExact("x", "y")); // 2
5931      * }
5932      * <p>Here is pseudocode for the resulting adapter. In the code,
5933      * {@code T}/{@code t} represent the result type and value of the
5934      * {@code target}; {@code V}, the result type of the {@code filter}; and
5935      * {@code A}/{@code a}, the types and values of the parameters and arguments
5936      * of the {@code target} as well as the resulting adapter.
5937      * {@snippet lang="java" :
5938      * T target(A...);
5939      * V filter(T);
5940      * V adapter(A... a) {
5941      *   T t = target(a...);
5942      *   return filter(t);
5943      * }
5944      * // and if the target has a void return:
5945      * void target2(A...);
5946      * V filter2();
5947      * V adapter2(A... a) {
5948      *   target2(a...);
5949      *   return filter2();
5950      * }
5951      * // and if the filter has a void return:
5952      * T target3(A...);
5953      * void filter3(V);
5954      * void adapter3(A... a) {
5955      *   T t = target3(a...);
5956      *   filter3(t);
5957      * }
5958      * }
5959      * <p>
5960      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5961      * variable-arity method handle}, even if the original target method handle was.
5962      * @param target the method handle to invoke before filtering the return value
5963      * @param filter method handle to call on the return value
5964      * @return method handle which incorporates the specified return value filtering logic
5965      * @throws NullPointerException if either argument is null
5966      * @throws IllegalArgumentException if the argument list of {@code filter}
5967      *          does not match the return type of target as described above
5968      */
5969     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5970         MethodType targetType = target.type();
5971         MethodType filterType = filter.type();
5972         filterReturnValueChecks(targetType, filterType);
5973         BoundMethodHandle result = target.rebind();
5974         BasicType rtype = BasicType.basicType(filterType.returnType());
5975         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5976         MethodType newType = targetType.changeReturnType(filterType.returnType());
5977         result = result.copyWithExtendL(newType, lform, filter);
5978         return result;
5979     }
5980 
5981     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5982         Class<?> rtype = targetType.returnType();
5983         int filterValues = filterType.parameterCount();
5984         if (filterValues == 0
5985                 ? (rtype != void.class)
5986                 : (rtype != filterType.parameterType(0) || filterValues != 1))
5987             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5988     }
5989 
5990     /**
5991      * Filter the return value of a target method handle with a filter function. The filter function is
5992      * applied to the return value of the original handle; if the filter specifies more than one parameters,
5993      * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5994      * as follows:
5995      * {@snippet lang="java" :
5996      * T target(A...)
5997      * V filter(B... , T)
5998      * V adapter(A... a, B... b) {
5999      *     T t = target(a...);
6000      *     return filter(b..., t);
6001      * }
6002      * }
6003      * <p>
6004      * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
6005      *
6006      * @param target the target method handle
6007      * @param filter the filter method handle
6008      * @return the adapter method handle
6009      */
6010     /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
6011         MethodType targetType = target.type();
6012         MethodType filterType = filter.type();
6013         BoundMethodHandle result = target.rebind();
6014         LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
6015         MethodType newType = targetType.changeReturnType(filterType.returnType());
6016         if (filterType.parameterCount() > 1) {
6017             for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
6018                 newType = newType.appendParameterTypes(filterType.parameterType(i));
6019             }
6020         }
6021         result = result.copyWithExtendL(newType, lform, filter);
6022         return result;
6023     }
6024 
6025     /**
6026      * Adapts a target method handle by pre-processing
6027      * some of its arguments, and then calling the target with
6028      * the result of the pre-processing, inserted into the original
6029      * sequence of arguments.
6030      * <p>
6031      * The pre-processing is performed by {@code combiner}, a second method handle.
6032      * Of the arguments passed to the adapter, the first {@code N} arguments
6033      * are copied to the combiner, which is then called.
6034      * (Here, {@code N} is defined as the parameter count of the combiner.)
6035      * After this, control passes to the target, with any result
6036      * from the combiner inserted before the original {@code N} incoming
6037      * arguments.
6038      * <p>
6039      * If the combiner returns a value, the first parameter type of the target
6040      * must be identical with the return type of the combiner, and the next
6041      * {@code N} parameter types of the target must exactly match the parameters
6042      * of the combiner.
6043      * <p>
6044      * If the combiner has a void return, no result will be inserted,
6045      * and the first {@code N} parameter types of the target
6046      * must exactly match the parameters of the combiner.
6047      * <p>
6048      * The resulting adapter is the same type as the target, except that the
6049      * first parameter type is dropped,
6050      * if it corresponds to the result of the combiner.
6051      * <p>
6052      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
6053      * that either the combiner or the target does not wish to receive.
6054      * If some of the incoming arguments are destined only for the combiner,
6055      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
6056      * arguments will not need to be live on the stack on entry to the
6057      * target.)
6058      * <p><b>Example:</b>
6059      * {@snippet lang="java" :
6060 import static java.lang.invoke.MethodHandles.*;
6061 import static java.lang.invoke.MethodType.*;
6062 ...
6063 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6064   "println", methodType(void.class, String.class))
6065     .bindTo(System.out);
6066 MethodHandle cat = lookup().findVirtual(String.class,
6067   "concat", methodType(String.class, String.class));
6068 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6069 MethodHandle catTrace = foldArguments(cat, trace);
6070 // also prints "boo":
6071 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6072      * }
6073      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6074      * represents the result type of the {@code target} and resulting adapter.
6075      * {@code V}/{@code v} represent the type and value of the parameter and argument
6076      * of {@code target} that precedes the folding position; {@code V} also is
6077      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6078      * types and values of the {@code N} parameters and arguments at the folding
6079      * position. {@code B}/{@code b} represent the types and values of the
6080      * {@code target} parameters and arguments that follow the folded parameters
6081      * and arguments.
6082      * {@snippet lang="java" :
6083      * // there are N arguments in A...
6084      * T target(V, A[N]..., B...);
6085      * V combiner(A...);
6086      * T adapter(A... a, B... b) {
6087      *   V v = combiner(a...);
6088      *   return target(v, a..., b...);
6089      * }
6090      * // and if the combiner has a void return:
6091      * T target2(A[N]..., B...);
6092      * void combiner2(A...);
6093      * T adapter2(A... a, B... b) {
6094      *   combiner2(a...);
6095      *   return target2(a..., b...);
6096      * }
6097      * }
6098      * <p>
6099      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6100      * variable-arity method handle}, even if the original target method handle was.
6101      * @param target the method handle to invoke after arguments are combined
6102      * @param combiner method handle to call initially on the incoming arguments
6103      * @return method handle which incorporates the specified argument folding logic
6104      * @throws NullPointerException if either argument is null
6105      * @throws IllegalArgumentException if {@code combiner}'s return type
6106      *          is non-void and not the same as the first argument type of
6107      *          the target, or if the initial {@code N} argument types
6108      *          of the target
6109      *          (skipping one matching the {@code combiner}'s return type)
6110      *          are not identical with the argument types of {@code combiner}
6111      */
6112     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
6113         return foldArguments(target, 0, combiner);
6114     }
6115 
6116     /**
6117      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
6118      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
6119      * before the folded arguments.
6120      * <p>
6121      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
6122      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
6123      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
6124      * 0.
6125      *
6126      * @apiNote Example:
6127      * {@snippet lang="java" :
6128     import static java.lang.invoke.MethodHandles.*;
6129     import static java.lang.invoke.MethodType.*;
6130     ...
6131     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6132     "println", methodType(void.class, String.class))
6133     .bindTo(System.out);
6134     MethodHandle cat = lookup().findVirtual(String.class,
6135     "concat", methodType(String.class, String.class));
6136     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6137     MethodHandle catTrace = foldArguments(cat, 1, trace);
6138     // also prints "jum":
6139     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6140      * }
6141      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6142      * represents the result type of the {@code target} and resulting adapter.
6143      * {@code V}/{@code v} represent the type and value of the parameter and argument
6144      * of {@code target} that precedes the folding position; {@code V} also is
6145      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6146      * types and values of the {@code N} parameters and arguments at the folding
6147      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
6148      * and values of the {@code target} parameters and arguments that precede and
6149      * follow the folded parameters and arguments starting at {@code pos},
6150      * respectively.
6151      * {@snippet lang="java" :
6152      * // there are N arguments in A...
6153      * T target(Z..., V, A[N]..., B...);
6154      * V combiner(A...);
6155      * T adapter(Z... z, A... a, B... b) {
6156      *   V v = combiner(a...);
6157      *   return target(z..., v, a..., b...);
6158      * }
6159      * // and if the combiner has a void return:
6160      * T target2(Z..., A[N]..., B...);
6161      * void combiner2(A...);
6162      * T adapter2(Z... z, A... a, B... b) {
6163      *   combiner2(a...);
6164      *   return target2(z..., a..., b...);
6165      * }
6166      * }
6167      * <p>
6168      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6169      * variable-arity method handle}, even if the original target method handle was.
6170      *
6171      * @param target the method handle to invoke after arguments are combined
6172      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
6173      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6174      * @param combiner method handle to call initially on the incoming arguments
6175      * @return method handle which incorporates the specified argument folding logic
6176      * @throws NullPointerException if either argument is null
6177      * @throws IllegalArgumentException if either of the following two conditions holds:
6178      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6179      *              {@code pos} of the target signature;
6180      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
6181      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
6182      *
6183      * @see #foldArguments(MethodHandle, MethodHandle)
6184      * @since 9
6185      */
6186     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
6187         MethodType targetType = target.type();
6188         MethodType combinerType = combiner.type();
6189         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
6190         BoundMethodHandle result = target.rebind();
6191         boolean dropResult = rtype == void.class;
6192         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
6193         MethodType newType = targetType;
6194         if (!dropResult) {
6195             newType = newType.dropParameterTypes(pos, pos + 1);
6196         }
6197         result = result.copyWithExtendL(newType, lform, combiner);
6198         return result;
6199     }
6200 
6201     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
6202         int foldArgs   = combinerType.parameterCount();
6203         Class<?> rtype = combinerType.returnType();
6204         int foldVals = rtype == void.class ? 0 : 1;
6205         int afterInsertPos = foldPos + foldVals;
6206         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
6207         if (ok) {
6208             for (int i = 0; i < foldArgs; i++) {
6209                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
6210                     ok = false;
6211                     break;
6212                 }
6213             }
6214         }
6215         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
6216             ok = false;
6217         if (!ok)
6218             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6219         return rtype;
6220     }
6221 
6222     /**
6223      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
6224      * of the pre-processing replacing the argument at the given position.
6225      *
6226      * @param target the method handle to invoke after arguments are combined
6227      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6228      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6229      * @param combiner method handle to call initially on the incoming arguments
6230      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6231      * @return method handle which incorporates the specified argument folding logic
6232      * @throws NullPointerException if either argument is null
6233      * @throws IllegalArgumentException if either of the following two conditions holds:
6234      *          (1) {@code combiner}'s return type is not the same as the argument type at position
6235      *              {@code pos} of the target signature;
6236      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
6237      *              not identical with the argument types of {@code combiner}.
6238      */
6239     /*non-public*/
6240     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6241         return argumentsWithCombiner(true, target, position, combiner, argPositions);
6242     }
6243 
6244     /**
6245      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
6246      * the pre-processing inserted into the original sequence of arguments at the given position.
6247      *
6248      * @param target the method handle to invoke after arguments are combined
6249      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6250      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6251      * @param combiner method handle to call initially on the incoming arguments
6252      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6253      * @return method handle which incorporates the specified argument folding logic
6254      * @throws NullPointerException if either argument is null
6255      * @throws IllegalArgumentException if either of the following two conditions holds:
6256      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6257      *              {@code pos} of the target signature;
6258      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
6259      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
6260      *              with the argument types of {@code combiner}.
6261      */
6262     /*non-public*/
6263     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6264         return argumentsWithCombiner(false, target, position, combiner, argPositions);
6265     }
6266 
6267     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6268         MethodType targetType = target.type();
6269         MethodType combinerType = combiner.type();
6270         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
6271         BoundMethodHandle result = target.rebind();
6272 
6273         MethodType newType = targetType;
6274         LambdaForm lform;
6275         if (filter) {
6276             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
6277         } else {
6278             boolean dropResult = rtype == void.class;
6279             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
6280             if (!dropResult) {
6281                 newType = newType.dropParameterTypes(position, position + 1);
6282             }
6283         }
6284         result = result.copyWithExtendL(newType, lform, combiner);
6285         return result;
6286     }
6287 
6288     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
6289         int combinerArgs = combinerType.parameterCount();
6290         if (argPos.length != combinerArgs) {
6291             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
6292         }
6293         Class<?> rtype = combinerType.returnType();
6294 
6295         for (int i = 0; i < combinerArgs; i++) {
6296             int arg = argPos[i];
6297             if (arg < 0 || arg > targetType.parameterCount()) {
6298                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
6299             }
6300             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
6301                 throw newIllegalArgumentException("target argument type at position " + arg
6302                         + " must match combiner argument type at index " + i + ": " + targetType
6303                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6304             }
6305         }
6306         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6307             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6308         }
6309         return rtype;
6310     }
6311 
6312     /**
6313      * Makes a method handle which adapts a target method handle,
6314      * by guarding it with a test, a boolean-valued method handle.
6315      * If the guard fails, a fallback handle is called instead.
6316      * All three method handles must have the same corresponding
6317      * argument and return types, except that the return type
6318      * of the test must be boolean, and the test is allowed
6319      * to have fewer arguments than the other two method handles.
6320      * <p>
6321      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6322      * represents the uniform result type of the three involved handles;
6323      * {@code A}/{@code a}, the types and values of the {@code target}
6324      * parameters and arguments that are consumed by the {@code test}; and
6325      * {@code B}/{@code b}, those types and values of the {@code target}
6326      * parameters and arguments that are not consumed by the {@code test}.
6327      * {@snippet lang="java" :
6328      * boolean test(A...);
6329      * T target(A...,B...);
6330      * T fallback(A...,B...);
6331      * T adapter(A... a,B... b) {
6332      *   if (test(a...))
6333      *     return target(a..., b...);
6334      *   else
6335      *     return fallback(a..., b...);
6336      * }
6337      * }
6338      * Note that the test arguments ({@code a...} in the pseudocode) cannot
6339      * be modified by execution of the test, and so are passed unchanged
6340      * from the caller to the target or fallback as appropriate.
6341      * @param test method handle used for test, must return boolean
6342      * @param target method handle to call if test passes
6343      * @param fallback method handle to call if test fails
6344      * @return method handle which incorporates the specified if/then/else logic
6345      * @throws NullPointerException if any argument is null
6346      * @throws IllegalArgumentException if {@code test} does not return boolean,
6347      *          or if all three method types do not match (with the return
6348      *          type of {@code test} changed to match that of the target).
6349      */
6350     public static MethodHandle guardWithTest(MethodHandle test,
6351                                MethodHandle target,
6352                                MethodHandle fallback) {
6353         MethodType gtype = test.type();
6354         MethodType ttype = target.type();
6355         MethodType ftype = fallback.type();
6356         if (!ttype.equals(ftype))
6357             throw misMatchedTypes("target and fallback types", ttype, ftype);
6358         if (gtype.returnType() != boolean.class)
6359             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6360 
6361         test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true);
6362         if (test == null) {
6363             throw misMatchedTypes("target and test types", ttype, gtype);
6364         }
6365         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6366     }
6367 
6368     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6369         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6370     }
6371 
6372     /**
6373      * Makes a method handle which adapts a target method handle,
6374      * by running it inside an exception handler.
6375      * If the target returns normally, the adapter returns that value.
6376      * If an exception matching the specified type is thrown, the fallback
6377      * handle is called instead on the exception, plus the original arguments.
6378      * <p>
6379      * The target and handler must have the same corresponding
6380      * argument and return types, except that handler may omit trailing arguments
6381      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6382      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6383      * <p>
6384      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6385      * represents the return type of the {@code target} and {@code handler},
6386      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6387      * the types and values of arguments to the resulting handle consumed by
6388      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6389      * resulting handle discarded by {@code handler}.
6390      * {@snippet lang="java" :
6391      * T target(A..., B...);
6392      * T handler(ExType, A...);
6393      * T adapter(A... a, B... b) {
6394      *   try {
6395      *     return target(a..., b...);
6396      *   } catch (ExType ex) {
6397      *     return handler(ex, a...);
6398      *   }
6399      * }
6400      * }
6401      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6402      * be modified by execution of the target, and so are passed unchanged
6403      * from the caller to the handler, if the handler is invoked.
6404      * <p>
6405      * The target and handler must return the same type, even if the handler
6406      * always throws.  (This might happen, for instance, because the handler
6407      * is simulating a {@code finally} clause).
6408      * To create such a throwing handler, compose the handler creation logic
6409      * with {@link #throwException throwException},
6410      * in order to create a method handle of the correct return type.
6411      * @param target method handle to call
6412      * @param exType the type of exception which the handler will catch
6413      * @param handler method handle to call if a matching exception is thrown
6414      * @return method handle which incorporates the specified try/catch logic
6415      * @throws NullPointerException if any argument is null
6416      * @throws IllegalArgumentException if {@code handler} does not accept
6417      *          the given exception type, or if the method handle types do
6418      *          not match in their return types and their
6419      *          corresponding parameters
6420      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6421      */
6422     public static MethodHandle catchException(MethodHandle target,
6423                                 Class<? extends Throwable> exType,
6424                                 MethodHandle handler) {
6425         MethodType ttype = target.type();
6426         MethodType htype = handler.type();
6427         if (!Throwable.class.isAssignableFrom(exType))
6428             throw new ClassCastException(exType.getName());
6429         if (htype.parameterCount() < 1 ||
6430             !htype.parameterType(0).isAssignableFrom(exType))
6431             throw newIllegalArgumentException("handler does not accept exception type "+exType);
6432         if (htype.returnType() != ttype.returnType())
6433             throw misMatchedTypes("target and handler return types", ttype, htype);
6434         handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true);
6435         if (handler == null) {
6436             throw misMatchedTypes("target and handler types", ttype, htype);
6437         }
6438         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6439     }
6440 
6441     /**
6442      * Produces a method handle which will throw exceptions of the given {@code exType}.
6443      * The method handle will accept a single argument of {@code exType},
6444      * and immediately throw it as an exception.
6445      * The method type will nominally specify a return of {@code returnType}.
6446      * The return type may be anything convenient:  It doesn't matter to the
6447      * method handle's behavior, since it will never return normally.
6448      * @param returnType the return type of the desired method handle
6449      * @param exType the parameter type of the desired method handle
6450      * @return method handle which can throw the given exceptions
6451      * @throws NullPointerException if either argument is null
6452      */
6453     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6454         if (!Throwable.class.isAssignableFrom(exType))
6455             throw new ClassCastException(exType.getName());
6456         return MethodHandleImpl.throwException(methodType(returnType, exType));
6457     }
6458 
6459     /**
6460      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6461      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6462      * delivers the loop's result, which is the return value of the resulting handle.
6463      * <p>
6464      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6465      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6466      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6467      * terms of method handles, each clause will specify up to four independent actions:<ul>
6468      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6469      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6470      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6471      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6472      * </ul>
6473      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6474      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
6475      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6476      * <p>
6477      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6478      * this case. See below for a detailed description.
6479      * <p>
6480      * <em>Parameters optional everywhere:</em>
6481      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6482      * As an exception, the init functions cannot take any {@code v} parameters,
6483      * because those values are not yet computed when the init functions are executed.
6484      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6485      * In fact, any clause function may take no arguments at all.
6486      * <p>
6487      * <em>Loop parameters:</em>
6488      * A clause function may take all the iteration variable values it is entitled to, in which case
6489      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6490      * with their types and values notated as {@code (A...)} and {@code (a...)}.
6491      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6492      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6493      * init function is automatically a loop parameter {@code a}.)
6494      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6495      * These loop parameters act as loop-invariant values visible across the whole loop.
6496      * <p>
6497      * <em>Parameters visible everywhere:</em>
6498      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6499      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6500      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6501      * Most clause functions will not need all of this information, but they will be formally connected to it
6502      * as if by {@link #dropArguments}.
6503      * <a id="astar"></a>
6504      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6505      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6506      * In that notation, the general form of an init function parameter list
6507      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6508      * <p>
6509      * <em>Checking clause structure:</em>
6510      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6511      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6512      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6513      * met by the inputs to the loop combinator.
6514      * <p>
6515      * <em>Effectively identical sequences:</em>
6516      * <a id="effid"></a>
6517      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6518      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6519      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6520      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6521      * that longest list.
6522      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6523      * and the same is true if more sequences of the form {@code (V... A*)} are added.
6524      * <p>
6525      * <em>Step 0: Determine clause structure.</em><ol type="a">
6526      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6527      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6528      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6529      * four. Padding takes place by appending elements to the array.
6530      * <li>Clauses with all {@code null}s are disregarded.
6531      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6532      * </ol>
6533      * <p>
6534      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6535      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6536      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6537      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6538      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6539      * iteration variable type.
6540      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6541      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6542      * </ol>
6543      * <p>
6544      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6545      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6546      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6547      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6548      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6549      * (These types will be checked in step 2, along with all the clause function types.)
6550      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6551      * <li>All of the collected parameter lists must be effectively identical.
6552      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6553      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6554      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6555      * the "internal parameter list".
6556      * </ul>
6557      * <p>
6558      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6559      * <li>Examine fini function return types, disregarding omitted fini functions.
6560      * <li>If there are no fini functions, the loop return type is {@code void}.
6561      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6562      * type.
6563      * </ol>
6564      * <p>
6565      * <em>Step 1D: Check other types.</em><ol type="a">
6566      * <li>There must be at least one non-omitted pred function.
6567      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6568      * </ol>
6569      * <p>
6570      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6571      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6572      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6573      * (Note that their parameter lists are already effectively identical to this list.)
6574      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6575      * effectively identical to the internal parameter list {@code (V... A...)}.
6576      * </ol>
6577      * <p>
6578      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6579      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6580      * type.
6581      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6582      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6583      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6584      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6585      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6586      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6587      * loop return type.
6588      * </ol>
6589      * <p>
6590      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6591      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6592      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6593      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6594      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6595      * pad out the end of the list.
6596      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6597      * </ol>
6598      * <p>
6599      * <em>Final observations.</em><ol type="a">
6600      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6601      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6602      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6603      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6604      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6605      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6606      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6607      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6608      * </ol>
6609      * <p>
6610      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6611      * <ul>
6612      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6613      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6614      * (Only one {@code Pn} has to be non-{@code null}.)
6615      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6616      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6617      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6618      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6619      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6620      * the resulting loop handle's parameter types {@code (A...)}.
6621      * </ul>
6622      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6623      * which is natural if most of the loop computation happens in the steps.  For some loops,
6624      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6625      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6626      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6627      * where the init functions will need the extra parameters.  For such reasons, the rules for
6628      * determining these parameters are as symmetric as possible, across all clause parts.
6629      * In general, the loop parameters function as common invariant values across the whole
6630      * loop, while the iteration variables function as common variant values, or (if there is
6631      * no step function) as internal loop invariant temporaries.
6632      * <p>
6633      * <em>Loop execution.</em><ol type="a">
6634      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6635      * every clause function. These locals are loop invariant.
6636      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6637      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6638      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6639      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6640      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6641      * (in argument order).
6642      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6643      * returns {@code false}.
6644      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6645      * sequence {@code (v...)} of loop variables.
6646      * The updated value is immediately visible to all subsequent function calls.
6647      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6648      * (of type {@code R}) is returned from the loop as a whole.
6649      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6650      * except by throwing an exception.
6651      * </ol>
6652      * <p>
6653      * <em>Usage tips.</em>
6654      * <ul>
6655      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6656      * sometimes a step function only needs to observe the current value of its own variable.
6657      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6658      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6659      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6660      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6661      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6662      * <li>If some of the clause functions are virtual methods on an instance, the instance
6663      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6664      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6665      * will be the first iteration variable value, and it will be easy to use virtual
6666      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6667      * </ul>
6668      * <p>
6669      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6670      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6671      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6672      * {@snippet lang="java" :
6673      * V... init...(A...);
6674      * boolean pred...(V..., A...);
6675      * V... step...(V..., A...);
6676      * R fini...(V..., A...);
6677      * R loop(A... a) {
6678      *   V... v... = init...(a...);
6679      *   for (;;) {
6680      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6681      *       v = s(v..., a...);
6682      *       if (!p(v..., a...)) {
6683      *         return f(v..., a...);
6684      *       }
6685      *     }
6686      *   }
6687      * }
6688      * }
6689      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6690      * to their full length, even though individual clause functions may neglect to take them all.
6691      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6692      *
6693      * @apiNote Example:
6694      * {@snippet lang="java" :
6695      * // iterative implementation of the factorial function as a loop handle
6696      * static int one(int k) { return 1; }
6697      * static int inc(int i, int acc, int k) { return i + 1; }
6698      * static int mult(int i, int acc, int k) { return i * acc; }
6699      * static boolean pred(int i, int acc, int k) { return i < k; }
6700      * static int fin(int i, int acc, int k) { return acc; }
6701      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6702      * // null initializer for counter, should initialize to 0
6703      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6704      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6705      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6706      * assertEquals(120, loop.invoke(5));
6707      * }
6708      * The same example, dropping arguments and using combinators:
6709      * {@snippet lang="java" :
6710      * // simplified implementation of the factorial function as a loop handle
6711      * static int inc(int i) { return i + 1; } // drop acc, k
6712      * static int mult(int i, int acc) { return i * acc; } //drop k
6713      * static boolean cmp(int i, int k) { return i < k; }
6714      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6715      * // null initializer for counter, should initialize to 0
6716      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6717      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6718      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6719      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6720      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6721      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6722      * assertEquals(720, loop.invoke(6));
6723      * }
6724      * A similar example, using a helper object to hold a loop parameter:
6725      * {@snippet lang="java" :
6726      * // instance-based implementation of the factorial function as a loop handle
6727      * static class FacLoop {
6728      *   final int k;
6729      *   FacLoop(int k) { this.k = k; }
6730      *   int inc(int i) { return i + 1; }
6731      *   int mult(int i, int acc) { return i * acc; }
6732      *   boolean pred(int i) { return i < k; }
6733      *   int fin(int i, int acc) { return acc; }
6734      * }
6735      * // assume MH_FacLoop is a handle to the constructor
6736      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6737      * // null initializer for counter, should initialize to 0
6738      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6739      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6740      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6741      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6742      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6743      * assertEquals(5040, loop.invoke(7));
6744      * }
6745      *
6746      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6747      *
6748      * @return a method handle embodying the looping behavior as defined by the arguments.
6749      *
6750      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6751      *
6752      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6753      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6754      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6755      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6756      * @since 9
6757      */
6758     public static MethodHandle loop(MethodHandle[]... clauses) {
6759         // Step 0: determine clause structure.
6760         loopChecks0(clauses);
6761 
6762         List<MethodHandle> init = new ArrayList<>();
6763         List<MethodHandle> step = new ArrayList<>();
6764         List<MethodHandle> pred = new ArrayList<>();
6765         List<MethodHandle> fini = new ArrayList<>();
6766 
6767         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6768             init.add(clause[0]); // all clauses have at least length 1
6769             step.add(clause.length <= 1 ? null : clause[1]);
6770             pred.add(clause.length <= 2 ? null : clause[2]);
6771             fini.add(clause.length <= 3 ? null : clause[3]);
6772         });
6773 
6774         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6775         final int nclauses = init.size();
6776 
6777         // Step 1A: determine iteration variables (V...).
6778         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6779         for (int i = 0; i < nclauses; ++i) {
6780             MethodHandle in = init.get(i);
6781             MethodHandle st = step.get(i);
6782             if (in == null && st == null) {
6783                 iterationVariableTypes.add(void.class);
6784             } else if (in != null && st != null) {
6785                 loopChecks1a(i, in, st);
6786                 iterationVariableTypes.add(in.type().returnType());
6787             } else {
6788                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6789             }
6790         }
6791         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6792 
6793         // Step 1B: determine loop parameters (A...).
6794         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6795         loopChecks1b(init, commonSuffix);
6796 
6797         // Step 1C: determine loop return type.
6798         // Step 1D: check other types.
6799         // local variable required here; see JDK-8223553
6800         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6801                 .map(MethodType::returnType);
6802         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6803         loopChecks1cd(pred, fini, loopReturnType);
6804 
6805         // Step 2: determine parameter lists.
6806         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6807         commonParameterSequence.addAll(commonSuffix);
6808         loopChecks2(step, pred, fini, commonParameterSequence);
6809         // Step 3: fill in omitted functions.
6810         for (int i = 0; i < nclauses; ++i) {
6811             Class<?> t = iterationVariableTypes.get(i);
6812             if (init.get(i) == null) {
6813                 init.set(i, empty(methodType(t, commonSuffix)));
6814             }
6815             if (step.get(i) == null) {
6816                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6817             }
6818             if (pred.get(i) == null) {
6819                 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
6820             }
6821             if (fini.get(i) == null) {
6822                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6823             }
6824         }
6825 
6826         // Step 4: fill in missing parameter types.
6827         // Also convert all handles to fixed-arity handles.
6828         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6829         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6830         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6831         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6832 
6833         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6834                 allMatch(pl -> pl.equals(commonSuffix));
6835         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6836                 allMatch(pl -> pl.equals(commonParameterSequence));
6837 
6838         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6839     }
6840 
6841     private static void loopChecks0(MethodHandle[][] clauses) {
6842         if (clauses == null || clauses.length == 0) {
6843             throw newIllegalArgumentException("null or no clauses passed");
6844         }
6845         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6846             throw newIllegalArgumentException("null clauses are not allowed");
6847         }
6848         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6849             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6850         }
6851     }
6852 
6853     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6854         if (in.type().returnType() != st.type().returnType()) {
6855             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6856                     st.type().returnType());
6857         }
6858     }
6859 
6860     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6861         return mhs.filter(Objects::nonNull)
6862                 // take only those that can contribute to a common suffix because they are longer than the prefix
6863                 .map(MethodHandle::type)
6864                 .filter(t -> t.parameterCount() > skipSize)
6865                 .max(Comparator.comparingInt(MethodType::parameterCount))
6866                 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount())))
6867                 .orElse(List.of());
6868     }
6869 
6870     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6871         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6872         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6873         return longest1.size() >= longest2.size() ? longest1 : longest2;
6874     }
6875 
6876     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6877         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6878                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6879             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6880                     " (common suffix: " + commonSuffix + ")");
6881         }
6882     }
6883 
6884     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6885         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6886                 anyMatch(t -> t != loopReturnType)) {
6887             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6888                     loopReturnType + ")");
6889         }
6890 
6891         if (pred.stream().noneMatch(Objects::nonNull)) {
6892             throw newIllegalArgumentException("no predicate found", pred);
6893         }
6894         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6895                 anyMatch(t -> t != boolean.class)) {
6896             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6897         }
6898     }
6899 
6900     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6901         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6902                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6903             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6904                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6905         }
6906     }
6907 
6908     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6909         return hs.stream().map(h -> {
6910             int pc = h.type().parameterCount();
6911             int tpsize = targetParams.size();
6912             return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
6913         }).toList();
6914     }
6915 
6916     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6917         return hs.stream().map(MethodHandle::asFixedArity).toList();
6918     }
6919 
6920     /**
6921      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6922      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6923      * <p>
6924      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6925      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6926      * evaluates to {@code true}).
6927      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6928      * <p>
6929      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6930      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6931      * and updated with the value returned from its invocation. The result of loop execution will be
6932      * the final value of the additional loop-local variable (if present).
6933      * <p>
6934      * The following rules hold for these argument handles:<ul>
6935      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6936      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6937      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6938      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6939      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6940      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6941      * It will constrain the parameter lists of the other loop parts.
6942      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6943      * list {@code (A...)} is called the <em>external parameter list</em>.
6944      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6945      * additional state variable of the loop.
6946      * The body must both accept and return a value of this type {@code V}.
6947      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6948      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6949      * <a href="MethodHandles.html#effid">effectively identical</a>
6950      * to the external parameter list {@code (A...)}.
6951      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6952      * {@linkplain #empty default value}.
6953      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6954      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6955      * effectively identical to the internal parameter list.
6956      * </ul>
6957      * <p>
6958      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6959      * <li>The loop handle's result type is the result type {@code V} of the body.
6960      * <li>The loop handle's parameter types are the types {@code (A...)},
6961      * from the external parameter list.
6962      * </ul>
6963      * <p>
6964      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6965      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6966      * passed to the loop.
6967      * {@snippet lang="java" :
6968      * V init(A...);
6969      * boolean pred(V, A...);
6970      * V body(V, A...);
6971      * V whileLoop(A... a...) {
6972      *   V v = init(a...);
6973      *   while (pred(v, a...)) {
6974      *     v = body(v, a...);
6975      *   }
6976      *   return v;
6977      * }
6978      * }
6979      *
6980      * @apiNote Example:
6981      * {@snippet lang="java" :
6982      * // implement the zip function for lists as a loop handle
6983      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6984      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6985      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6986      *   zip.add(a.next());
6987      *   zip.add(b.next());
6988      *   return zip;
6989      * }
6990      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6991      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6992      * List<String> a = Arrays.asList("a", "b", "c", "d");
6993      * List<String> b = Arrays.asList("e", "f", "g", "h");
6994      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6995      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6996      * }
6997      *
6998      *
6999      * @apiNote The implementation of this method can be expressed as follows:
7000      * {@snippet lang="java" :
7001      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
7002      *     MethodHandle fini = (body.type().returnType() == void.class
7003      *                         ? null : identity(body.type().returnType()));
7004      *     MethodHandle[]
7005      *         checkExit = { null, null, pred, fini },
7006      *         varBody   = { init, body };
7007      *     return loop(checkExit, varBody);
7008      * }
7009      * }
7010      *
7011      * @param init optional initializer, providing the initial value of the loop variable.
7012      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7013      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7014      *             above for other constraints.
7015      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7016      *             See above for other constraints.
7017      *
7018      * @return a method handle implementing the {@code while} loop as described by the arguments.
7019      * @throws IllegalArgumentException if the rules for the arguments are violated.
7020      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7021      *
7022      * @see #loop(MethodHandle[][])
7023      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
7024      * @since 9
7025      */
7026     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
7027         whileLoopChecks(init, pred, body);
7028         MethodHandle fini = identityOrVoid(body.type().returnType());
7029         MethodHandle[] checkExit = { null, null, pred, fini };
7030         MethodHandle[] varBody = { init, body };
7031         return loop(checkExit, varBody);
7032     }
7033 
7034     /**
7035      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
7036      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7037      * <p>
7038      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
7039      * method will, in each iteration, first execute its body and then evaluate the predicate.
7040      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
7041      * <p>
7042      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
7043      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
7044      * and updated with the value returned from its invocation. The result of loop execution will be
7045      * the final value of the additional loop-local variable (if present).
7046      * <p>
7047      * The following rules hold for these argument handles:<ul>
7048      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7049      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
7050      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7051      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
7052      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
7053      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
7054      * It will constrain the parameter lists of the other loop parts.
7055      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
7056      * list {@code (A...)} is called the <em>external parameter list</em>.
7057      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7058      * additional state variable of the loop.
7059      * The body must both accept and return a value of this type {@code V}.
7060      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7061      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7062      * <a href="MethodHandles.html#effid">effectively identical</a>
7063      * to the external parameter list {@code (A...)}.
7064      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7065      * {@linkplain #empty default value}.
7066      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
7067      * Its parameter list (either empty or of the form {@code (V A*)}) must be
7068      * effectively identical to the internal parameter list.
7069      * </ul>
7070      * <p>
7071      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7072      * <li>The loop handle's result type is the result type {@code V} of the body.
7073      * <li>The loop handle's parameter types are the types {@code (A...)},
7074      * from the external parameter list.
7075      * </ul>
7076      * <p>
7077      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7078      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
7079      * passed to the loop.
7080      * {@snippet lang="java" :
7081      * V init(A...);
7082      * boolean pred(V, A...);
7083      * V body(V, A...);
7084      * V doWhileLoop(A... a...) {
7085      *   V v = init(a...);
7086      *   do {
7087      *     v = body(v, a...);
7088      *   } while (pred(v, a...));
7089      *   return v;
7090      * }
7091      * }
7092      *
7093      * @apiNote Example:
7094      * {@snippet lang="java" :
7095      * // int i = 0; while (i < limit) { ++i; } return i; => limit
7096      * static int zero(int limit) { return 0; }
7097      * static int step(int i, int limit) { return i + 1; }
7098      * static boolean pred(int i, int limit) { return i < limit; }
7099      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
7100      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
7101      * assertEquals(23, loop.invoke(23));
7102      * }
7103      *
7104      *
7105      * @apiNote The implementation of this method can be expressed as follows:
7106      * {@snippet lang="java" :
7107      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7108      *     MethodHandle fini = (body.type().returnType() == void.class
7109      *                         ? null : identity(body.type().returnType()));
7110      *     MethodHandle[] clause = { init, body, pred, fini };
7111      *     return loop(clause);
7112      * }
7113      * }
7114      *
7115      * @param init optional initializer, providing the initial value of the loop variable.
7116      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7117      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7118      *             See above for other constraints.
7119      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7120      *             above for other constraints.
7121      *
7122      * @return a method handle implementing the {@code while} loop as described by the arguments.
7123      * @throws IllegalArgumentException if the rules for the arguments are violated.
7124      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7125      *
7126      * @see #loop(MethodHandle[][])
7127      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
7128      * @since 9
7129      */
7130     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7131         whileLoopChecks(init, pred, body);
7132         MethodHandle fini = identityOrVoid(body.type().returnType());
7133         MethodHandle[] clause = {init, body, pred, fini };
7134         return loop(clause);
7135     }
7136 
7137     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
7138         Objects.requireNonNull(pred);
7139         Objects.requireNonNull(body);
7140         MethodType bodyType = body.type();
7141         Class<?> returnType = bodyType.returnType();
7142         List<Class<?>> innerList = bodyType.parameterList();
7143         List<Class<?>> outerList = innerList;
7144         if (returnType == void.class) {
7145             // OK
7146         } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
7147             // leading V argument missing => error
7148             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7149             throw misMatchedTypes("body function", bodyType, expected);
7150         } else {
7151             outerList = innerList.subList(1, innerList.size());
7152         }
7153         MethodType predType = pred.type();
7154         if (predType.returnType() != boolean.class ||
7155                 !predType.effectivelyIdenticalParameters(0, innerList)) {
7156             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
7157         }
7158         if (init != null) {
7159             MethodType initType = init.type();
7160             if (initType.returnType() != returnType ||
7161                     !initType.effectivelyIdenticalParameters(0, outerList)) {
7162                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7163             }
7164         }
7165     }
7166 
7167     /**
7168      * Constructs a loop that runs a given number of iterations.
7169      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7170      * <p>
7171      * The number of iterations is determined by the {@code iterations} handle evaluation result.
7172      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
7173      * It will be initialized to 0 and incremented by 1 in each iteration.
7174      * <p>
7175      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7176      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7177      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7178      * <p>
7179      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7180      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7181      * iteration variable.
7182      * The result of the loop handle execution will be the final {@code V} value of that variable
7183      * (or {@code void} if there is no {@code V} variable).
7184      * <p>
7185      * The following rules hold for the argument handles:<ul>
7186      * <li>The {@code iterations} handle must not be {@code null}, and must return
7187      * the type {@code int}, referred to here as {@code I} in parameter type lists.
7188      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7189      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7190      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7191      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7192      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7193      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7194      * of types called the <em>internal parameter list</em>.
7195      * It will constrain the parameter lists of the other loop parts.
7196      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7197      * with no additional {@code A} types, then the internal parameter list is extended by
7198      * the argument types {@code A...} of the {@code iterations} handle.
7199      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7200      * list {@code (A...)} is called the <em>external parameter list</em>.
7201      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7202      * additional state variable of the loop.
7203      * The body must both accept a leading parameter and return a value of this type {@code V}.
7204      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7205      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7206      * <a href="MethodHandles.html#effid">effectively identical</a>
7207      * to the external parameter list {@code (A...)}.
7208      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7209      * {@linkplain #empty default value}.
7210      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
7211      * effectively identical to the external parameter list {@code (A...)}.
7212      * </ul>
7213      * <p>
7214      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7215      * <li>The loop handle's result type is the result type {@code V} of the body.
7216      * <li>The loop handle's parameter types are the types {@code (A...)},
7217      * from the external parameter list.
7218      * </ul>
7219      * <p>
7220      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7221      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7222      * arguments passed to the loop.
7223      * {@snippet lang="java" :
7224      * int iterations(A...);
7225      * V init(A...);
7226      * V body(V, int, A...);
7227      * V countedLoop(A... a...) {
7228      *   int end = iterations(a...);
7229      *   V v = init(a...);
7230      *   for (int i = 0; i < end; ++i) {
7231      *     v = body(v, i, a...);
7232      *   }
7233      *   return v;
7234      * }
7235      * }
7236      *
7237      * @apiNote Example with a fully conformant body method:
7238      * {@snippet lang="java" :
7239      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7240      * // => a variation on a well known theme
7241      * static String step(String v, int counter, String init) { return "na " + v; }
7242      * // assume MH_step is a handle to the method above
7243      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
7244      * MethodHandle start = MethodHandles.identity(String.class);
7245      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
7246      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
7247      * }
7248      *
7249      * @apiNote Example with the simplest possible body method type,
7250      * and passing the number of iterations to the loop invocation:
7251      * {@snippet lang="java" :
7252      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7253      * // => a variation on a well known theme
7254      * static String step(String v, int counter ) { return "na " + v; }
7255      * // assume MH_step is a handle to the method above
7256      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
7257      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
7258      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
7259      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
7260      * }
7261      *
7262      * @apiNote Example that treats the number of iterations, string to append to, and string to append
7263      * as loop parameters:
7264      * {@snippet lang="java" :
7265      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7266      * // => a variation on a well known theme
7267      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
7268      * // assume MH_step is a handle to the method above
7269      * MethodHandle count = MethodHandles.identity(int.class);
7270      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
7271      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
7272      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
7273      * }
7274      *
7275      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
7276      * to enforce a loop type:
7277      * {@snippet lang="java" :
7278      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7279      * // => a variation on a well known theme
7280      * static String step(String v, int counter, String pre) { return pre + " " + v; }
7281      * // assume MH_step is a handle to the method above
7282      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
7283      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
7284      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
7285      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
7286      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
7287      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
7288      * }
7289      *
7290      * @apiNote The implementation of this method can be expressed as follows:
7291      * {@snippet lang="java" :
7292      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7293      *     return countedLoop(empty(iterations.type()), iterations, init, body);
7294      * }
7295      * }
7296      *
7297      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
7298      *                   result type must be {@code int}. See above for other constraints.
7299      * @param init optional initializer, providing the initial value of the loop variable.
7300      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7301      * @param body body of the loop, which may not be {@code null}.
7302      *             It controls the loop parameters and result type in the standard case (see above for details).
7303      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7304      *             and may accept any number of additional types.
7305      *             See above for other constraints.
7306      *
7307      * @return a method handle representing the loop.
7308      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7309      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7310      *
7311      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7312      * @since 9
7313      */
7314     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7315         return countedLoop(empty(iterations.type()), iterations, init, body);
7316     }
7317 
7318     /**
7319      * Constructs a loop that counts over a range of numbers.
7320      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7321      * <p>
7322      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7323      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7324      * values of the loop counter.
7325      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7326      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7327      * <p>
7328      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7329      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7330      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7331      * <p>
7332      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7333      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7334      * iteration variable.
7335      * The result of the loop handle execution will be the final {@code V} value of that variable
7336      * (or {@code void} if there is no {@code V} variable).
7337      * <p>
7338      * The following rules hold for the argument handles:<ul>
7339      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7340      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7341      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7342      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7343      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7344      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7345      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7346      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7347      * of types called the <em>internal parameter list</em>.
7348      * It will constrain the parameter lists of the other loop parts.
7349      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7350      * with no additional {@code A} types, then the internal parameter list is extended by
7351      * the argument types {@code A...} of the {@code end} handle.
7352      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7353      * list {@code (A...)} is called the <em>external parameter list</em>.
7354      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7355      * additional state variable of the loop.
7356      * The body must both accept a leading parameter and return a value of this type {@code V}.
7357      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7358      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7359      * <a href="MethodHandles.html#effid">effectively identical</a>
7360      * to the external parameter list {@code (A...)}.
7361      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7362      * {@linkplain #empty default value}.
7363      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7364      * effectively identical to the external parameter list {@code (A...)}.
7365      * <li>Likewise, the parameter list of {@code end} must be effectively identical
7366      * to the external parameter list.
7367      * </ul>
7368      * <p>
7369      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7370      * <li>The loop handle's result type is the result type {@code V} of the body.
7371      * <li>The loop handle's parameter types are the types {@code (A...)},
7372      * from the external parameter list.
7373      * </ul>
7374      * <p>
7375      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7376      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7377      * arguments passed to the loop.
7378      * {@snippet lang="java" :
7379      * int start(A...);
7380      * int end(A...);
7381      * V init(A...);
7382      * V body(V, int, A...);
7383      * V countedLoop(A... a...) {
7384      *   int e = end(a...);
7385      *   int s = start(a...);
7386      *   V v = init(a...);
7387      *   for (int i = s; i < e; ++i) {
7388      *     v = body(v, i, a...);
7389      *   }
7390      *   return v;
7391      * }
7392      * }
7393      *
7394      * @apiNote The implementation of this method can be expressed as follows:
7395      * {@snippet lang="java" :
7396      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7397      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7398      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7399      *     // the following semantics:
7400      *     // MH_increment: (int limit, int counter) -> counter + 1
7401      *     // MH_predicate: (int limit, int counter) -> counter < limit
7402      *     Class<?> counterType = start.type().returnType();  // int
7403      *     Class<?> returnType = body.type().returnType();
7404      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7405      *     if (returnType != void.class) {  // ignore the V variable
7406      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7407      *         pred = dropArguments(pred, 1, returnType);  // ditto
7408      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7409      *     }
7410      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
7411      *     MethodHandle[]
7412      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7413      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
7414      *         indexVar   = { start, incr };           // i = start(); i = i + 1
7415      *     return loop(loopLimit, bodyClause, indexVar);
7416      * }
7417      * }
7418      *
7419      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7420      *              See above for other constraints.
7421      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7422      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
7423      * @param init optional initializer, providing the initial value of the loop variable.
7424      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7425      * @param body body of the loop, which may not be {@code null}.
7426      *             It controls the loop parameters and result type in the standard case (see above for details).
7427      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7428      *             and may accept any number of additional types.
7429      *             See above for other constraints.
7430      *
7431      * @return a method handle representing the loop.
7432      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7433      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7434      *
7435      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7436      * @since 9
7437      */
7438     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7439         countedLoopChecks(start, end, init, body);
7440         Class<?> counterType = start.type().returnType();  // int, but who's counting?
7441         Class<?> limitType   = end.type().returnType();    // yes, int again
7442         Class<?> returnType  = body.type().returnType();
7443         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7444         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7445         MethodHandle retv = null;
7446         if (returnType != void.class) {
7447             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7448             pred = dropArguments(pred, 1, returnType);  // ditto
7449             retv = dropArguments(identity(returnType), 0, counterType);
7450         }
7451         body = dropArguments(body, 0, counterType);  // ignore the limit variable
7452         MethodHandle[]
7453             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7454             bodyClause = { init, body },            // v = init(); v = body(v, i)
7455             indexVar   = { start, incr };           // i = start(); i = i + 1
7456         return loop(loopLimit, bodyClause, indexVar);
7457     }
7458 
7459     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7460         Objects.requireNonNull(start);
7461         Objects.requireNonNull(end);
7462         Objects.requireNonNull(body);
7463         Class<?> counterType = start.type().returnType();
7464         if (counterType != int.class) {
7465             MethodType expected = start.type().changeReturnType(int.class);
7466             throw misMatchedTypes("start function", start.type(), expected);
7467         } else if (end.type().returnType() != counterType) {
7468             MethodType expected = end.type().changeReturnType(counterType);
7469             throw misMatchedTypes("end function", end.type(), expected);
7470         }
7471         MethodType bodyType = body.type();
7472         Class<?> returnType = bodyType.returnType();
7473         List<Class<?>> innerList = bodyType.parameterList();
7474         // strip leading V value if present
7475         int vsize = (returnType == void.class ? 0 : 1);
7476         if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7477             // argument list has no "V" => error
7478             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7479             throw misMatchedTypes("body function", bodyType, expected);
7480         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7481             // missing I type => error
7482             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7483             throw misMatchedTypes("body function", bodyType, expected);
7484         }
7485         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7486         if (outerList.isEmpty()) {
7487             // special case; take lists from end handle
7488             outerList = end.type().parameterList();
7489             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7490         }
7491         MethodType expected = methodType(counterType, outerList);
7492         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7493             throw misMatchedTypes("start parameter types", start.type(), expected);
7494         }
7495         if (end.type() != start.type() &&
7496             !end.type().effectivelyIdenticalParameters(0, outerList)) {
7497             throw misMatchedTypes("end parameter types", end.type(), expected);
7498         }
7499         if (init != null) {
7500             MethodType initType = init.type();
7501             if (initType.returnType() != returnType ||
7502                 !initType.effectivelyIdenticalParameters(0, outerList)) {
7503                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7504             }
7505         }
7506     }
7507 
7508     /**
7509      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7510      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7511      * <p>
7512      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7513      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7514      * <p>
7515      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7516      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7517      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7518      * <p>
7519      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7520      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7521      * iteration variable.
7522      * The result of the loop handle execution will be the final {@code V} value of that variable
7523      * (or {@code void} if there is no {@code V} variable).
7524      * <p>
7525      * The following rules hold for the argument handles:<ul>
7526      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7527      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7528      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7529      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7530      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7531      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7532      * of types called the <em>internal parameter list</em>.
7533      * It will constrain the parameter lists of the other loop parts.
7534      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7535      * with no additional {@code A} types, then the internal parameter list is extended by
7536      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7537      * single type {@code Iterable} is added and constitutes the {@code A...} list.
7538      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7539      * list {@code (A...)} is called the <em>external parameter list</em>.
7540      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7541      * additional state variable of the loop.
7542      * The body must both accept a leading parameter and return a value of this type {@code V}.
7543      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7544      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7545      * <a href="MethodHandles.html#effid">effectively identical</a>
7546      * to the external parameter list {@code (A...)}.
7547      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7548      * {@linkplain #empty default value}.
7549      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7550      * type {@code java.util.Iterator} or a subtype thereof.
7551      * The iterator it produces when the loop is executed will be assumed
7552      * to yield values which can be converted to type {@code T}.
7553      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7554      * effectively identical to the external parameter list {@code (A...)}.
7555      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7556      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7557      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7558      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7559      * the {@link MethodHandle#asType asType} conversion method.
7560      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7561      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7562      * </ul>
7563      * <p>
7564      * The type {@code T} may be either a primitive or reference.
7565      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7566      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7567      * as if by the {@link MethodHandle#asType asType} conversion method.
7568      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7569      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7570      * <p>
7571      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7572      * <li>The loop handle's result type is the result type {@code V} of the body.
7573      * <li>The loop handle's parameter types are the types {@code (A...)},
7574      * from the external parameter list.
7575      * </ul>
7576      * <p>
7577      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7578      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7579      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7580      * {@snippet lang="java" :
7581      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7582      * V init(A...);
7583      * V body(V,T,A...);
7584      * V iteratedLoop(A... a...) {
7585      *   Iterator<T> it = iterator(a...);
7586      *   V v = init(a...);
7587      *   while (it.hasNext()) {
7588      *     T t = it.next();
7589      *     v = body(v, t, a...);
7590      *   }
7591      *   return v;
7592      * }
7593      * }
7594      *
7595      * @apiNote Example:
7596      * {@snippet lang="java" :
7597      * // get an iterator from a list
7598      * static List<String> reverseStep(List<String> r, String e) {
7599      *   r.add(0, e);
7600      *   return r;
7601      * }
7602      * static List<String> newArrayList() { return new ArrayList<>(); }
7603      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7604      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7605      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7606      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7607      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7608      * }
7609      *
7610      * @apiNote The implementation of this method can be expressed approximately as follows:
7611      * {@snippet lang="java" :
7612      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7613      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7614      *     Class<?> returnType = body.type().returnType();
7615      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7616      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7617      *     MethodHandle retv = null, step = body, startIter = iterator;
7618      *     if (returnType != void.class) {
7619      *         // the simple thing first:  in (I V A...), drop the I to get V
7620      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7621      *         // body type signature (V T A...), internal loop types (I V A...)
7622      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7623      *     }
7624      *     if (startIter == null)  startIter = MH_getIter;
7625      *     MethodHandle[]
7626      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7627      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7628      *     return loop(iterVar, bodyClause);
7629      * }
7630      * }
7631      *
7632      * @param iterator an optional handle to return the iterator to start the loop.
7633      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7634      *                 See above for other constraints.
7635      * @param init optional initializer, providing the initial value of the loop variable.
7636      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7637      * @param body body of the loop, which may not be {@code null}.
7638      *             It controls the loop parameters and result type in the standard case (see above for details).
7639      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7640      *             and may accept any number of additional types.
7641      *             See above for other constraints.
7642      *
7643      * @return a method handle embodying the iteration loop functionality.
7644      * @throws NullPointerException if the {@code body} handle is {@code null}.
7645      * @throws IllegalArgumentException if any argument violates the above requirements.
7646      *
7647      * @since 9
7648      */
7649     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7650         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7651         Class<?> returnType = body.type().returnType();
7652         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7653         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7654         MethodHandle startIter;
7655         MethodHandle nextVal;
7656         {
7657             MethodType iteratorType;
7658             if (iterator == null) {
7659                 // derive argument type from body, if available, else use Iterable
7660                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7661                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7662             } else {
7663                 // force return type to the internal iterator class
7664                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7665                 startIter = iterator;
7666             }
7667             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7668             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7669 
7670             // perform the asType transforms under an exception transformer, as per spec.:
7671             try {
7672                 startIter = startIter.asType(iteratorType);
7673                 nextVal = nextRaw.asType(nextValType);
7674             } catch (WrongMethodTypeException ex) {
7675                 throw new IllegalArgumentException(ex);
7676             }
7677         }
7678 
7679         MethodHandle retv = null, step = body;
7680         if (returnType != void.class) {
7681             // the simple thing first:  in (I V A...), drop the I to get V
7682             retv = dropArguments(identity(returnType), 0, Iterator.class);
7683             // body type signature (V T A...), internal loop types (I V A...)
7684             step = swapArguments(body, 0, 1);  // swap V <-> T
7685         }
7686 
7687         MethodHandle[]
7688             iterVar    = { startIter, null, hasNext, retv },
7689             bodyClause = { init, filterArgument(step, 0, nextVal) };
7690         return loop(iterVar, bodyClause);
7691     }
7692 
7693     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7694         Objects.requireNonNull(body);
7695         MethodType bodyType = body.type();
7696         Class<?> returnType = bodyType.returnType();
7697         List<Class<?>> internalParamList = bodyType.parameterList();
7698         // strip leading V value if present
7699         int vsize = (returnType == void.class ? 0 : 1);
7700         if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7701             // argument list has no "V" => error
7702             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7703             throw misMatchedTypes("body function", bodyType, expected);
7704         } else if (internalParamList.size() <= vsize) {
7705             // missing T type => error
7706             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7707             throw misMatchedTypes("body function", bodyType, expected);
7708         }
7709         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7710         Class<?> iterableType = null;
7711         if (iterator != null) {
7712             // special case; if the body handle only declares V and T then
7713             // the external parameter list is obtained from iterator handle
7714             if (externalParamList.isEmpty()) {
7715                 externalParamList = iterator.type().parameterList();
7716             }
7717             MethodType itype = iterator.type();
7718             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7719                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7720             }
7721             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7722                 MethodType expected = methodType(itype.returnType(), externalParamList);
7723                 throw misMatchedTypes("iterator parameters", itype, expected);
7724             }
7725         } else {
7726             if (externalParamList.isEmpty()) {
7727                 // special case; if the iterator handle is null and the body handle
7728                 // only declares V and T then the external parameter list consists
7729                 // of Iterable
7730                 externalParamList = List.of(Iterable.class);
7731                 iterableType = Iterable.class;
7732             } else {
7733                 // special case; if the iterator handle is null and the external
7734                 // parameter list is not empty then the first parameter must be
7735                 // assignable to Iterable
7736                 iterableType = externalParamList.get(0);
7737                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7738                     throw newIllegalArgumentException(
7739                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7740                 }
7741             }
7742         }
7743         if (init != null) {
7744             MethodType initType = init.type();
7745             if (initType.returnType() != returnType ||
7746                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7747                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7748             }
7749         }
7750         return iterableType;  // help the caller a bit
7751     }
7752 
7753     /*non-public*/
7754     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7755         // there should be a better way to uncross my wires
7756         int arity = mh.type().parameterCount();
7757         int[] order = new int[arity];
7758         for (int k = 0; k < arity; k++)  order[k] = k;
7759         order[i] = j; order[j] = i;
7760         Class<?>[] types = mh.type().parameterArray();
7761         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7762         MethodType swapType = methodType(mh.type().returnType(), types);
7763         return permuteArguments(mh, swapType, order);
7764     }
7765 
7766     /**
7767      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7768      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7769      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7770      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7771      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7772      * {@code try-finally} handle.
7773      * <p>
7774      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7775      * The first is the exception thrown during the
7776      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7777      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7778      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7779      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7780      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7781      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7782      * <p>
7783      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7784      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7785      * two extra leading parameters:<ul>
7786      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7787      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7788      * the result from the execution of the {@code target} handle.
7789      * This parameter is not present if the {@code target} returns {@code void}.
7790      * </ul>
7791      * <p>
7792      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7793      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7794      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7795      * the cleanup.
7796      * {@snippet lang="java" :
7797      * V target(A..., B...);
7798      * V cleanup(Throwable, V, A...);
7799      * V adapter(A... a, B... b) {
7800      *   V result = (zero value for V);
7801      *   Throwable throwable = null;
7802      *   try {
7803      *     result = target(a..., b...);
7804      *   } catch (Throwable t) {
7805      *     throwable = t;
7806      *     throw t;
7807      *   } finally {
7808      *     result = cleanup(throwable, result, a...);
7809      *   }
7810      *   return result;
7811      * }
7812      * }
7813      * <p>
7814      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7815      * be modified by execution of the target, and so are passed unchanged
7816      * from the caller to the cleanup, if it is invoked.
7817      * <p>
7818      * The target and cleanup must return the same type, even if the cleanup
7819      * always throws.
7820      * To create such a throwing cleanup, compose the cleanup logic
7821      * with {@link #throwException throwException},
7822      * in order to create a method handle of the correct return type.
7823      * <p>
7824      * Note that {@code tryFinally} never converts exceptions into normal returns.
7825      * In rare cases where exceptions must be converted in that way, first wrap
7826      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7827      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7828      * <p>
7829      * It is recommended that the first parameter type of {@code cleanup} be
7830      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7831      * {@code cleanup} will always be invoked with whatever exception that
7832      * {@code target} throws.  Declaring a narrower type may result in a
7833      * {@code ClassCastException} being thrown by the {@code try-finally}
7834      * handle if the type of the exception thrown by {@code target} is not
7835      * assignable to the first parameter type of {@code cleanup}.  Note that
7836      * various exception types of {@code VirtualMachineError},
7837      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7838      * thrown by almost any kind of Java code, and a finally clause that
7839      * catches (say) only {@code IOException} would mask any of the others
7840      * behind a {@code ClassCastException}.
7841      *
7842      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7843      * @param cleanup the handle that is invoked in the finally block.
7844      *
7845      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7846      * @throws NullPointerException if any argument is null
7847      * @throws IllegalArgumentException if {@code cleanup} does not accept
7848      *          the required leading arguments, or if the method handle types do
7849      *          not match in their return types and their
7850      *          corresponding trailing parameters
7851      *
7852      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7853      * @since 9
7854      */
7855     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7856         Class<?>[] targetParamTypes = target.type().ptypes();
7857         Class<?> rtype = target.type().returnType();
7858 
7859         tryFinallyChecks(target, cleanup);
7860 
7861         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7862         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7863         // target parameter list.
7864         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false);
7865 
7866         // Ensure that the intrinsic type checks the instance thrown by the
7867         // target against the first parameter of cleanup
7868         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7869 
7870         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7871         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7872     }
7873 
7874     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7875         Class<?> rtype = target.type().returnType();
7876         if (rtype != cleanup.type().returnType()) {
7877             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7878         }
7879         MethodType cleanupType = cleanup.type();
7880         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7881             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7882         }
7883         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7884             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7885         }
7886         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7887         // target parameter list.
7888         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7889         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7890             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7891                     cleanup.type(), target.type());
7892         }
7893     }
7894 
7895     /**
7896      * Creates a table switch method handle, which can be used to switch over a set of target
7897      * method handles, based on a given target index, called selector.
7898      * <p>
7899      * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7900      * and where {@code N} is the number of target method handles, the table switch method
7901      * handle will invoke the n-th target method handle from the list of target method handles.
7902      * <p>
7903      * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7904      * method handle will invoke the given fallback method handle.
7905      * <p>
7906      * All method handles passed to this method must have the same type, with the additional
7907      * requirement that the leading parameter be of type {@code int}. The leading parameter
7908      * represents the selector.
7909      * <p>
7910      * Any trailing parameters present in the type will appear on the returned table switch
7911      * method handle as well. Any arguments assigned to these parameters will be forwarded,
7912      * together with the selector value, to the selected method handle when invoking it.
7913      *
7914      * @apiNote Example:
7915      * The cases each drop the {@code selector} value they are given, and take an additional
7916      * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7917      * to a specific constant label string for each case:
7918      * {@snippet lang="java" :
7919      * MethodHandles.Lookup lookup = MethodHandles.lookup();
7920      * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7921      *         MethodType.methodType(String.class, String.class));
7922      * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7923      *
7924      * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7925      * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7926      * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7927      *
7928      * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7929      *     caseDefault,
7930      *     case0,
7931      *     case1
7932      * );
7933      *
7934      * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7935      * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7936      * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7937      * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7938      * }
7939      *
7940      * @param fallback the fallback method handle that is called when the selector is not
7941      *                 within the range {@code [0, N)}.
7942      * @param targets array of target method handles.
7943      * @return the table switch method handle.
7944      * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7945      *                              any of the elements of the {@code targets} array are
7946      *                              {@code null}.
7947      * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7948      *                                  parameter of the fallback handle or any of the target
7949      *                                  handles is not {@code int}, or if the types of
7950      *                                  the fallback handle and all of target handles are
7951      *                                  not the same.
7952      */
7953     public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7954         Objects.requireNonNull(fallback);
7955         Objects.requireNonNull(targets);
7956         targets = targets.clone();
7957         MethodType type = tableSwitchChecks(fallback, targets);
7958         return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7959     }
7960 
7961     private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7962         if (caseActions.length == 0)
7963             throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7964 
7965         MethodType expectedType = defaultCase.type();
7966 
7967         if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7968             throw new IllegalArgumentException(
7969                 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7970 
7971         for (MethodHandle mh : caseActions) {
7972             Objects.requireNonNull(mh);
7973             if (mh.type() != expectedType)
7974                 throw new IllegalArgumentException(
7975                     "Case actions must have the same type: " + Arrays.toString(caseActions));
7976         }
7977 
7978         return expectedType;
7979     }
7980 
7981     /**
7982      * Creates a var handle object, which can be used to dereference a {@linkplain java.lang.foreign.MemorySegment memory segment}
7983      * at a given byte offset, using the provided value layout.
7984      *
7985      * <p>The provided layout specifies the {@linkplain ValueLayout#carrier() carrier type},
7986      * the {@linkplain ValueLayout#byteSize() byte size},
7987      * the {@linkplain ValueLayout#byteAlignment() byte alignment} and the {@linkplain ValueLayout#order() byte order}
7988      * associated with the returned var handle.
7989      *
7990      * <p>The list of coordinate types associated with the returned var handle is {@code (MemorySegment, long)},
7991      * where the {@code long} coordinate type corresponds to byte offset into the given memory segment coordinate.
7992      * Thus, the returned var handle accesses bytes at an offset in a given memory segment, composing bytes to or from
7993      * a value of the var handle type. Moreover, the access operation will honor the endianness and the
7994      * alignment constraints expressed in the provided layout.
7995      *
7996      * <p>As an example, consider the memory layout expressed by a {@link GroupLayout} instance constructed as follows:
7997      * {@snippet lang="java" :
7998      *     GroupLayout seq = java.lang.foreign.MemoryLayout.structLayout(
7999      *             MemoryLayout.paddingLayout(4),
8000      *             ValueLayout.JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN).withName("value")
8001      *     );
8002      * }
8003      * To access the member layout named {@code value}, we can construct a memory segment view var handle as follows:
8004      * {@snippet lang="java" :
8005      *     VarHandle handle = MethodHandles.memorySegmentViewVarHandle(ValueLayout.JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN)); //(MemorySegment, long) -> int
8006      *     handle = MethodHandles.insertCoordinates(handle, 1, 4); //(MemorySegment) -> int
8007      * }
8008      *
8009      * @apiNote The resulting var handle features certain <i>access mode restrictions</i>,
8010      * which are common to all memory segment view var handles. A memory segment view var handle is associated
8011      * with an access size {@code S} and an alignment constraint {@code B}
8012      * (both expressed in bytes). We say that a memory access operation is <em>fully aligned</em> if it occurs
8013      * at a memory address {@code A} which is compatible with both alignment constraints {@code S} and {@code B}.
8014      * If access is fully aligned then following access modes are supported and are
8015      * guaranteed to support atomic access:
8016      * <ul>
8017      * <li>read write access modes for all {@code T}, with the exception of
8018      *     access modes {@code get} and {@code set} for {@code long} and
8019      *     {@code double} on 32-bit platforms.
8020      * <li>atomic update access modes for {@code int}, {@code long},
8021      *     {@code float}, {@code double} or {@link MemorySegment}.
8022      *     (Future major platform releases of the JDK may support additional
8023      *     types for certain currently unsupported access modes.)
8024      * <li>numeric atomic update access modes for {@code int}, {@code long} and {@link MemorySegment}.
8025      *     (Future major platform releases of the JDK may support additional
8026      *     numeric types for certain currently unsupported access modes.)
8027      * <li>bitwise atomic update access modes for {@code int}, {@code long} and {@link MemorySegment}.
8028      *     (Future major platform releases of the JDK may support additional
8029      *     numeric types for certain currently unsupported access modes.)
8030      * </ul>
8031      *
8032      * If {@code T} is {@code float}, {@code double} or {@link MemorySegment} then atomic
8033      * update access modes compare values using their bitwise representation
8034      * (see {@link Float#floatToRawIntBits},
8035      * {@link Double#doubleToRawLongBits} and {@link MemorySegment#address()}, respectively).
8036      * <p>
8037      * Alternatively, a memory access operation is <em>partially aligned</em> if it occurs at a memory address {@code A}
8038      * which is only compatible with the alignment constraint {@code B}; in such cases, access for anything other than the
8039      * {@code get} and {@code set} access modes will result in an {@code IllegalStateException}. If access is partially aligned,
8040      * atomic access is only guaranteed with respect to the largest power of two that divides the GCD of {@code A} and {@code S}.
8041      * <p>
8042      * In all other cases, we say that a memory access operation is <em>misaligned</em>; in such cases an
8043      * {@code IllegalStateException} is thrown, irrespective of the access mode being used.
8044      * <p>
8045      * Finally, if {@code T} is {@code MemorySegment} all write access modes throw {@link IllegalArgumentException}
8046      * unless the value to be written is a {@linkplain MemorySegment#isNative() native} memory segment.
8047      *
8048      * @param layout the value layout for which a memory access handle is to be obtained.
8049      * @return the new memory segment view var handle.
8050      * @throws NullPointerException if {@code layout} is {@code null}.
8051      * @see MemoryLayout#varHandle(MemoryLayout.PathElement...)
8052      * @since 19
8053      */
8054     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8055     public static VarHandle memorySegmentViewVarHandle(ValueLayout layout) {
8056         Objects.requireNonNull(layout);
8057         return Utils.makeSegmentViewVarHandle(layout);
8058     }
8059 
8060     /**
8061      * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions.
8062      * <p>
8063      * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where
8064      * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed
8065      * to the target var handle.
8066      * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from
8067      * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function)
8068      * is processed using the second filter and returned to the caller. More advanced access mode types, such as
8069      * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time.
8070      * <p>
8071      * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and
8072      * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case,
8073      * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which
8074      * will be appended to the coordinates of the target var handle).
8075      * <p>
8076      * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will
8077      * throw an {@link IllegalStateException}.
8078      * <p>
8079      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8080      * atomic access guarantees as those featured by the target var handle.
8081      *
8082      * @param target the target var handle
8083      * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target}
8084      * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S}
8085      * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions.
8086      * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types
8087      * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle,
8088      * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions.
8089      * @throws NullPointerException if any of the arguments is {@code null}.
8090      * @since 19
8091      */
8092     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8093     public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
8094         return VarHandles.filterValue(target, filterToTarget, filterFromTarget);
8095     }
8096 
8097     /**
8098      * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions.
8099      * <p>
8100      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values
8101      * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types
8102      * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the
8103      * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered
8104      * by the adaptation) to the target var handle.
8105      * <p>
8106      * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn},
8107      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
8108      * <p>
8109      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8110      * throw an {@link IllegalStateException}.
8111      * <p>
8112      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8113      * atomic access guarantees as those featured by the target var handle.
8114      *
8115      * @param target the target var handle
8116      * @param pos the position of the first coordinate to be transformed
8117      * @param filters the unary functions which are used to transform coordinates starting at position {@code pos}
8118      * @return an adapter var handle which accepts new coordinate types, applying the provided transformation
8119      * to the new coordinate values.
8120      * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types
8121      * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting
8122      * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8123      * or if more filters are provided than the actual number of coordinate types available starting at {@code pos},
8124      * or if it's determined that any of the filters throws any checked exceptions.
8125      * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}.
8126      * @since 19
8127      */
8128     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8129     public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
8130         return VarHandles.filterCoordinates(target, pos, filters);
8131     }
8132 
8133     /**
8134      * Provides a target var handle with one or more <em>bound coordinates</em>
8135      * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less
8136      * coordinate types than the target var handle.
8137      * <p>
8138      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values
8139      * are joined with bound coordinate values, and then passed to the target var handle.
8140      * <p>
8141      * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn },
8142      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
8143      * <p>
8144      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8145      * atomic access guarantees as those featured by the target var handle.
8146      *
8147      * @param target the var handle to invoke after the bound coordinates are inserted
8148      * @param pos the position of the first coordinate to be inserted
8149      * @param values the series of bound coordinates to insert
8150      * @return an adapter var handle which inserts additional coordinates,
8151      *         before calling the target var handle
8152      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8153      * or if more values are provided than the actual number of coordinate types available starting at {@code pos}.
8154      * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types
8155      * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos}
8156      * of the target var handle.
8157      * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}.
8158      * @since 19
8159      */
8160     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8161     public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
8162         return VarHandles.insertCoordinates(target, pos, values);
8163     }
8164 
8165     /**
8166      * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them
8167      * so that the new coordinates match the provided ones.
8168      * <p>
8169      * The given array controls the reordering.
8170      * Call {@code #I} the number of incoming coordinates (the value
8171      * {@code newCoordinates.size()}), and call {@code #O} the number
8172      * of outgoing coordinates (the number of coordinates associated with the target var handle).
8173      * Then the length of the reordering array must be {@code #O},
8174      * and each element must be a non-negative number less than {@code #I}.
8175      * For every {@code N} less than {@code #O}, the {@code N}-th
8176      * outgoing coordinate will be taken from the {@code I}-th incoming
8177      * coordinate, where {@code I} is {@code reorder[N]}.
8178      * <p>
8179      * No coordinate value conversions are applied.
8180      * The type of each incoming coordinate, as determined by {@code newCoordinates},
8181      * must be identical to the type of the corresponding outgoing coordinate
8182      * in the target var handle.
8183      * <p>
8184      * The reordering array need not specify an actual permutation.
8185      * An incoming coordinate will be duplicated if its index appears
8186      * more than once in the array, and an incoming coordinate will be dropped
8187      * if its index does not appear in the array.
8188      * <p>
8189      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8190      * atomic access guarantees as those featured by the target var handle.
8191      * @param target the var handle to invoke after the coordinates have been reordered
8192      * @param newCoordinates the new coordinate types
8193      * @param reorder an index array which controls the reordering
8194      * @return an adapter var handle which re-arranges the incoming coordinate values,
8195      * before calling the target var handle
8196      * @throws IllegalArgumentException if the index array length is not equal to
8197      * the number of coordinates of the target var handle, or if any index array element is not a valid index for
8198      * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in
8199      * the target var handle and in {@code newCoordinates} are not identical.
8200      * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}.
8201      * @since 19
8202      */
8203     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8204     public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
8205         return VarHandles.permuteCoordinates(target, newCoordinates, reorder);
8206     }
8207 
8208     /**
8209      * Adapts a target var handle by pre-processing
8210      * a sub-sequence of its coordinate values with a filter (a method handle).
8211      * The pre-processed coordinates are replaced by the result (if any) of the
8212      * filter function and the target var handle is then called on the modified (usually shortened)
8213      * coordinate list.
8214      * <p>
8215      * If {@code R} is the return type of the filter, then:
8216      * <ul>
8217      * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in
8218      * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos}
8219      * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first,
8220      * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the
8221      * target var handle.</li>
8222      * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the
8223      * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle
8224      * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a
8225      * downstream invocation of the target var handle.</li>
8226      * </ul>
8227      * <p>
8228      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8229      * throw an {@link IllegalStateException}.
8230      * <p>
8231      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8232      * atomic access guarantees as those featured by the target var handle.
8233      *
8234      * @param target the var handle to invoke after the coordinates have been filtered
8235      * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted
8236      * @param filter the filter method handle
8237      * @return an adapter var handle which filters the incoming coordinate values,
8238      * before calling the target var handle
8239      * @throws IllegalArgumentException if the return type of {@code filter}
8240      * is not void, and it is not the same as the {@code pos} coordinate of the target var handle,
8241      * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8242      * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>,
8243      * or if it's determined that {@code filter} throws any checked exceptions.
8244      * @throws NullPointerException if any of the arguments is {@code null}.
8245      * @since 19
8246      */
8247     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8248     public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
8249         return VarHandles.collectCoordinates(target, pos, filter);
8250     }
8251 
8252     /**
8253      * Returns a var handle which will discard some dummy coordinates before delegating to the
8254      * target var handle. As a consequence, the resulting var handle will feature more
8255      * coordinate types than the target var handle.
8256      * <p>
8257      * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the
8258      * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede
8259      * the target's real arguments; if {@code pos} is <i>N</i> they will come after.
8260      * <p>
8261      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8262      * atomic access guarantees as those featured by the target var handle.
8263      *
8264      * @param target the var handle to invoke after the dummy coordinates are dropped
8265      * @param pos position of the first coordinate to drop (zero for the leftmost)
8266      * @param valueTypes the type(s) of the coordinate(s) to drop
8267      * @return an adapter var handle which drops some dummy coordinates,
8268      *         before calling the target var handle
8269      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive.
8270      * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}.
8271      * @since 19
8272      */
8273     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8274     public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
8275         return VarHandles.dropCoordinates(target, pos, valueTypes);
8276     }
8277 }