1 /*
   2  * Copyright (c) 2008, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import jdk.internal.access.SharedSecrets;
  29 import jdk.internal.value.PrimitiveClass;
  30 import jdk.internal.foreign.Utils;
  31 import jdk.internal.javac.PreviewFeature;
  32 import jdk.internal.misc.Unsafe;
  33 import jdk.internal.misc.VM;
  34 import jdk.internal.org.objectweb.asm.ClassReader;
  35 import jdk.internal.org.objectweb.asm.Opcodes;
  36 import jdk.internal.org.objectweb.asm.Type;
  37 import jdk.internal.reflect.CallerSensitive;
  38 import jdk.internal.reflect.CallerSensitiveAdapter;
  39 import jdk.internal.reflect.Reflection;
  40 import jdk.internal.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.MemoryAddress;
  50 import java.lang.foreign.MemoryLayout;
  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.Iterator;
  64 import java.util.List;
  65 import java.util.Objects;
  66 import java.util.Set;
  67 import java.util.concurrent.ConcurrentHashMap;
  68 import java.util.stream.Stream;
  69 
  70 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
  71 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  72 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  73 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
  74 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  75 import static java.lang.invoke.MethodHandleStatics.newInternalError;
  76 import static java.lang.invoke.MethodType.methodType;
  77 
  78 /**
  79  * This class consists exclusively of static methods that operate on or return
  80  * method handles. They fall into several categories:
  81  * <ul>
  82  * <li>Lookup methods which help create method handles for methods and fields.
  83  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  84  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  85  * </ul>
  86  * A lookup, combinator, or factory method will fail and throw an
  87  * {@code IllegalArgumentException} if the created method handle's type
  88  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  89  *
  90  * @author John Rose, JSR 292 EG
  91  * @since 1.7
  92  */
  93 public class MethodHandles {
  94 
  95     private MethodHandles() { }  // do not instantiate
  96 
  97     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  98 
  99     // See IMPL_LOOKUP below.
 100 
 101     //// Method handle creation from ordinary methods.
 102 
 103     /**
 104      * Returns a {@link Lookup lookup object} with
 105      * full capabilities to emulate all supported bytecode behaviors of the caller.
 106      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
 107      * Factory methods on the lookup object can create
 108      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
 109      * for any member that the caller has access to via bytecodes,
 110      * including protected and private fields and methods.
 111      * This lookup object is created by the original lookup class
 112      * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
 113      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 114      * Do not store it in place where untrusted code can access it.
 115      * <p>
 116      * This method is caller sensitive, which means that it may return different
 117      * values to different callers.
 118      * In cases where {@code MethodHandles.lookup} is called from a context where
 119      * there is no caller frame on the stack (e.g. when called directly
 120      * from a JNI attached thread), {@code IllegalCallerException} is thrown.
 121      * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will
 122      * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()}
 123      * to obtain a low-privileged lookup instead.
 124      * @return a lookup object for the caller of this method, with
 125      * {@linkplain Lookup#ORIGINAL original} and
 126      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
 127      * @throws IllegalCallerException if there is no caller frame on the stack.
 128      */
 129     @CallerSensitive
 130     @ForceInline // to ensure Reflection.getCallerClass optimization
 131     public static Lookup lookup() {
 132         final Class<?> c = Reflection.getCallerClass();
 133         if (c == null) {
 134             throw new IllegalCallerException("no caller frame");
 135         }
 136         return new Lookup(c);
 137     }
 138 
 139     /**
 140      * This lookup method is the alternate implementation of
 141      * the lookup method with a leading caller class argument which is
 142      * non-caller-sensitive.  This method is only invoked by reflection
 143      * and method handle.
 144      */
 145     @CallerSensitiveAdapter
 146     private static Lookup lookup(Class<?> caller) {
 147         if (caller.getClassLoader() == null) {
 148             throw newInternalError("calling lookup() reflectively is not supported: "+caller);
 149         }
 150         return new Lookup(caller);
 151     }
 152 
 153     /**
 154      * Returns a {@link Lookup lookup object} which is trusted minimally.
 155      * The lookup has the {@code UNCONDITIONAL} mode.
 156      * It can only be used to create method handles to public members of
 157      * public classes in packages that are exported unconditionally.
 158      * <p>
 159      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 160      * of this lookup object will be {@link java.lang.Object}.
 161      *
 162      * @apiNote The use of Object is conventional, and because the lookup modes are
 163      * limited, there is no special access provided to the internals of Object, its package
 164      * or its module.  This public lookup object or other lookup object with
 165      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 166      * is not used to determine the lookup context.
 167      *
 168      * <p style="font-size:smaller;">
 169      * <em>Discussion:</em>
 170      * The lookup class can be changed to any other class {@code C} using an expression of the form
 171      * {@link Lookup#in publicLookup().in(C.class)}.
 172      * A public lookup object is always subject to
 173      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 174      * Also, it cannot access
 175      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 176      * @return a lookup object which is trusted minimally
 177      *
 178      * @revised 9
 179      */
 180     public static Lookup publicLookup() {
 181         return Lookup.PUBLIC_LOOKUP;
 182     }
 183 
 184     /**
 185      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 186      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 187      * The returned lookup object can provide access to classes in modules and packages,
 188      * and members of those classes, outside the normal rules of Java access control,
 189      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 190      * <p>
 191      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 192      * allowed to do deep reflection on module {@code M2} and package of the target class
 193      * if and only if all of the following conditions are {@code true}:
 194      * <ul>
 195      * <li>If there is a security manager, its {@code checkPermission} method is
 196      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 197      * that must return normally.
 198      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 199      * full privilege access}.  Specifically:
 200      *   <ul>
 201      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 202      *         (This is because otherwise there would be no way to ensure the original lookup
 203      *         creator was a member of any particular module, and so any subsequent checks
 204      *         for readability and qualified exports would become ineffective.)
 205      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 206      *         (This is because an application intending to share intra-module access
 207      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 208      *         deep reflection to its own module.)
 209      *   </ul>
 210      * <li>The target class must be a proper class, not a primitive or array class.
 211      * (Thus, {@code M2} is well-defined.)
 212      * <li>If the caller module {@code M1} differs from
 213      * the target module {@code M2} then both of the following must be true:
 214      *   <ul>
 215      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 216      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 217      *         containing the target class to at least {@code M1}.</li>
 218      *   </ul>
 219      * </ul>
 220      * <p>
 221      * If any of the above checks is violated, this method fails with an
 222      * exception.
 223      * <p>
 224      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 225      * returns a {@code Lookup} on {@code targetClass} with
 226      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 227      * with {@code null} previous lookup class.
 228      * <p>
 229      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 230      * returns a {@code Lookup} on {@code targetClass} that records
 231      * the lookup class of the caller as the new previous lookup class with
 232      * {@code PRIVATE} access but no {@code MODULE} access.
 233      * <p>
 234      * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
 235      *
 236      * @param targetClass the target class
 237      * @param caller the caller lookup object
 238      * @return a lookup object for the target class, with private access
 239      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 240      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 241      * @throws SecurityException if denied by the security manager
 242      * @throws IllegalAccessException if any of the other access checks specified above fails
 243      * @since 9
 244      * @see Lookup#dropLookupMode
 245      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 246      */
 247     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 248         if (caller.allowedModes == Lookup.TRUSTED) {
 249             return new Lookup(targetClass);
 250         }
 251 
 252         @SuppressWarnings("removal")
 253         SecurityManager sm = System.getSecurityManager();
 254         if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 255         if (targetClass.isPrimitive())
 256             throw new IllegalArgumentException(targetClass + " is a primitive class");
 257         if (targetClass.isArray())
 258             throw new IllegalArgumentException(targetClass + " is an array class");
 259         // Ensure that we can reason accurately about private and module access.
 260         int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
 261         if ((caller.lookupModes() & requireAccess) != requireAccess)
 262             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 263 
 264         // previous lookup class is never set if it has MODULE access
 265         assert caller.previousLookupClass() == null;
 266 
 267         Class<?> callerClass = caller.lookupClass();
 268         Module callerModule = callerClass.getModule();  // M1
 269         Module targetModule = targetClass.getModule();  // M2
 270         Class<?> newPreviousClass = null;
 271         int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
 272 
 273         if (targetModule != callerModule) {
 274             if (!callerModule.canRead(targetModule))
 275                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 276             if (targetModule.isNamed()) {
 277                 String pn = targetClass.getPackageName();
 278                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 279                 if (!targetModule.isOpen(pn, callerModule))
 280                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 281             }
 282 
 283             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 284             newPreviousClass = callerClass;
 285             newModes &= ~Lookup.MODULE;
 286         }
 287         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 288     }
 289 
 290     /**
 291      * Returns the <em>class data</em> associated with the lookup class
 292      * of the given {@code caller} lookup object, or {@code null}.
 293      *
 294      * <p> A hidden class with class data can be created by calling
 295      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 296      * Lookup::defineHiddenClassWithClassData}.
 297      * This method will cause the static class initializer of the lookup
 298      * class of the given {@code caller} lookup object be executed if
 299      * it has not been initialized.
 300      *
 301      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 302      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 303      * {@code null} is returned if this method is called on the lookup object
 304      * on these classes.
 305      *
 306      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 307      * must have {@linkplain Lookup#ORIGINAL original access}
 308      * in order to retrieve the class data.
 309      *
 310      * @apiNote
 311      * This method can be called as a bootstrap method for a dynamically computed
 312      * constant.  A framework can create a hidden class with class data, for
 313      * example that can be {@code Class} or {@code MethodHandle} object.
 314      * The class data is accessible only to the lookup object
 315      * created by the original caller but inaccessible to other members
 316      * in the same nest.  If a framework passes security sensitive objects
 317      * to a hidden class via class data, it is recommended to load the value
 318      * of class data as a dynamically computed constant instead of storing
 319      * the class data in private static field(s) which are accessible to
 320      * other nestmates.
 321      *
 322      * @param <T> the type to cast the class data object to
 323      * @param caller the lookup context describing the class performing the
 324      * operation (normally stacked by the JVM)
 325      * @param name must be {@link ConstantDescs#DEFAULT_NAME}
 326      *             ({@code "_"})
 327      * @param type the type of the class data
 328      * @return the value of the class data if present in the lookup class;
 329      * otherwise {@code null}
 330      * @throws IllegalArgumentException if name is not {@code "_"}
 331      * @throws IllegalAccessException if the lookup context does not have
 332      * {@linkplain Lookup#ORIGINAL original} access
 333      * @throws ClassCastException if the class data cannot be converted to
 334      * the given {@code type}
 335      * @throws NullPointerException if {@code caller} or {@code type} argument
 336      * is {@code null}
 337      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 338      * @see MethodHandles#classDataAt(Lookup, String, Class, int)
 339      * @since 16
 340      * @jvms 5.5 Initialization
 341      */
 342      public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 343          Objects.requireNonNull(caller);
 344          Objects.requireNonNull(type);
 345          if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
 346              throw new IllegalArgumentException("name must be \"_\": " + name);
 347          }
 348 
 349          if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL)  {
 350              throw new IllegalAccessException(caller + " does not have ORIGINAL access");
 351          }
 352 
 353          Object classdata = classData(caller.lookupClass());
 354          if (classdata == null) return null;
 355 
 356          try {
 357              return BootstrapMethodInvoker.widenAndCast(classdata, type);
 358          } catch (RuntimeException|Error e) {
 359              throw e; // let CCE and other runtime exceptions through
 360          } catch (Throwable e) {
 361              throw new InternalError(e);
 362          }
 363     }
 364 
 365     /*
 366      * Returns the class data set by the VM in the Class::classData field.
 367      *
 368      * This is also invoked by LambdaForms as it cannot use condy via
 369      * MethodHandles::classData due to bootstrapping issue.
 370      */
 371     static Object classData(Class<?> c) {
 372         UNSAFE.ensureClassInitialized(c);
 373         return SharedSecrets.getJavaLangAccess().classData(c);
 374     }
 375 
 376     /**
 377      * Returns the element at the specified index in the
 378      * {@linkplain #classData(Lookup, String, Class) class data},
 379      * if the class data associated with the lookup class
 380      * of the given {@code caller} lookup object is a {@code List}.
 381      * If the class data is not present in this lookup class, this method
 382      * returns {@code null}.
 383      *
 384      * <p> A hidden class with class data can be created by calling
 385      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 386      * Lookup::defineHiddenClassWithClassData}.
 387      * This method will cause the static class initializer of the lookup
 388      * class of the given {@code caller} lookup object be executed if
 389      * it has not been initialized.
 390      *
 391      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 392      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 393      * {@code null} is returned if this method is called on the lookup object
 394      * on these classes.
 395      *
 396      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 397      * must have {@linkplain Lookup#ORIGINAL original access}
 398      * in order to retrieve the class data.
 399      *
 400      * @apiNote
 401      * This method can be called as a bootstrap method for a dynamically computed
 402      * constant.  A framework can create a hidden class with class data, for
 403      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 404      * one object and use this method to load one element at a specific index.
 405      * The class data is accessible only to the lookup object
 406      * created by the original caller but inaccessible to other members
 407      * in the same nest.  If a framework passes security sensitive objects
 408      * to a hidden class via class data, it is recommended to load the value
 409      * of class data as a dynamically computed constant instead of storing
 410      * the class data in private static field(s) which are accessible to other
 411      * nestmates.
 412      *
 413      * @param <T> the type to cast the result object to
 414      * @param caller the lookup context describing the class performing the
 415      * operation (normally stacked by the JVM)
 416      * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
 417      *             ({@code "_"})
 418      * @param type the type of the element at the given index in the class data
 419      * @param index index of the element in the class data
 420      * @return the element at the given index in the class data
 421      * if the class data is present; otherwise {@code null}
 422      * @throws IllegalArgumentException if name is not {@code "_"}
 423      * @throws IllegalAccessException if the lookup context does not have
 424      * {@linkplain Lookup#ORIGINAL original} access
 425      * @throws ClassCastException if the class data cannot be converted to {@code List}
 426      * or the element at the specified index cannot be converted to the given type
 427      * @throws IndexOutOfBoundsException if the index is out of range
 428      * @throws NullPointerException if {@code caller} or {@code type} argument is
 429      * {@code null}; or if unboxing operation fails because
 430      * the element at the given index is {@code null}
 431      *
 432      * @since 16
 433      * @see #classData(Lookup, String, Class)
 434      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 435      */
 436     public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
 437             throws IllegalAccessException
 438     {
 439         @SuppressWarnings("unchecked")
 440         List<Object> classdata = (List<Object>)classData(caller, name, List.class);
 441         if (classdata == null) return null;
 442 
 443         try {
 444             Object element = classdata.get(index);
 445             return BootstrapMethodInvoker.widenAndCast(element, type);
 446         } catch (RuntimeException|Error e) {
 447             throw e; // let specified exceptions and other runtime exceptions/errors through
 448         } catch (Throwable e) {
 449             throw new InternalError(e);
 450         }
 451     }
 452 
 453     /**
 454      * Performs an unchecked "crack" of a
 455      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 456      * The result is as if the user had obtained a lookup object capable enough
 457      * to crack the target method handle, called
 458      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 459      * on the target to obtain its symbolic reference, and then called
 460      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 461      * to resolve the symbolic reference to a member.
 462      * <p>
 463      * If there is a security manager, its {@code checkPermission} method
 464      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 465      * @param <T> the desired type of the result, either {@link Member} or a subtype
 466      * @param target a direct method handle to crack into symbolic reference components
 467      * @param expected a class object representing the desired result type {@code T}
 468      * @return a reference to the method, constructor, or field object
 469      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 470      * @throws    NullPointerException if either argument is {@code null}
 471      * @throws    IllegalArgumentException if the target is not a direct method handle
 472      * @throws    ClassCastException if the member is not of the expected type
 473      * @since 1.8
 474      */
 475     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 476         @SuppressWarnings("removal")
 477         SecurityManager smgr = System.getSecurityManager();
 478         if (smgr != null)  smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 479         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 480         return lookup.revealDirect(target).reflectAs(expected, lookup);
 481     }
 482 
 483     /**
 484      * A <em>lookup object</em> is a factory for creating method handles,
 485      * when the creation requires access checking.
 486      * Method handles do not perform
 487      * access checks when they are called, but rather when they are created.
 488      * Therefore, method handle access
 489      * restrictions must be enforced when a method handle is created.
 490      * The caller class against which those restrictions are enforced
 491      * is known as the {@linkplain #lookupClass() lookup class}.
 492      * <p>
 493      * A lookup class which needs to create method handles will call
 494      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 495      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 496      * determined, and securely stored in the {@code Lookup} object.
 497      * The lookup class (or its delegates) may then use factory methods
 498      * on the {@code Lookup} object to create method handles for access-checked members.
 499      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 500      * even private ones.
 501      *
 502      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 503      * The factory methods on a {@code Lookup} object correspond to all major
 504      * use cases for methods, constructors, and fields.
 505      * Each method handle created by a factory method is the functional
 506      * equivalent of a particular <em>bytecode behavior</em>.
 507      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 508      * the Java Virtual Machine Specification.)
 509      * Here is a summary of the correspondence between these factory methods and
 510      * the behavior of the resulting method handles:
 511      * <table class="striped">
 512      * <caption style="display:none">lookup method behaviors</caption>
 513      * <thead>
 514      * <tr>
 515      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 516      *     <th scope="col">member</th>
 517      *     <th scope="col">bytecode behavior</th>
 518      * </tr>
 519      * </thead>
 520      * <tbody>
 521      * <tr>
 522      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 523      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 524      * </tr>
 525      * <tr>
 526      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 527      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 528      * </tr>
 529      * <tr>
 530      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 531      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 532      * </tr>
 533      * <tr>
 534      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 535      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 536      * </tr>
 537      * <tr>
 538      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 539      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 540      * </tr>
 541      * <tr>
 542      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 543      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 544      * </tr>
 545      * <tr>
 546      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 547      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 548      * </tr>
 549      * <tr>
 550      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 551      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 552      * </tr>
 553      * <tr>
 554      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 555      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 556      * </tr>
 557      * <tr>
 558      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 559      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 560      * </tr>
 561      * <tr>
 562      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 563      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 564      * </tr>
 565      * <tr>
 566      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 567      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 568      * </tr>
 569      * <tr>
 570      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 571      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 572      * </tr>
 573      * <tr>
 574      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 575      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 576      * </tr>
 577      * </tbody>
 578      * </table>
 579      *
 580      * Here, the type {@code C} is the class or interface being searched for a member,
 581      * documented as a parameter named {@code refc} in the lookup methods.
 582      * The method type {@code MT} is composed from the return type {@code T}
 583      * and the sequence of argument types {@code A*}.
 584      * The constructor also has a sequence of argument types {@code A*} and
 585      * is deemed to return the newly-created object of type {@code C}.
 586      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 587      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 588      * if it is present, it is always the leading argument to the method handle invocation.
 589      * (In the case of some {@code protected} members, {@code this} may be
 590      * restricted in type to the lookup class; see below.)
 591      * The name {@code arg} stands for all the other method handle arguments.
 592      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 593      * stands for a null reference if the accessed method or field is static,
 594      * and {@code this} otherwise.
 595      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 596      * for reflective objects corresponding to the given members declared in type {@code C}.
 597      * <p>
 598      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 599      * as if by {@code ldc CONSTANT_Class}.
 600      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 601      * <p>
 602      * In cases where the given member is of variable arity (i.e., a method or constructor)
 603      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 604      * In all other cases, the returned method handle will be of fixed arity.
 605      * <p style="font-size:smaller;">
 606      * <em>Discussion:</em>
 607      * The equivalence between looked-up method handles and underlying
 608      * class members and bytecode behaviors
 609      * can break down in a few ways:
 610      * <ul style="font-size:smaller;">
 611      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 612      * the lookup can still succeed, even when there is no equivalent
 613      * Java expression or bytecoded constant.
 614      * <li>Likewise, if {@code T} or {@code MT}
 615      * is not symbolically accessible from the lookup class's loader,
 616      * the lookup can still succeed.
 617      * For example, lookups for {@code MethodHandle.invokeExact} and
 618      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 619      * <li>If there is a security manager installed, it can forbid the lookup
 620      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 621      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 622      * constant is not subject to security manager checks.
 623      * <li>If the looked-up method has a
 624      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 625      * the method handle creation may fail with an
 626      * {@code IllegalArgumentException}, due to the method handle type having
 627      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 628      * </ul>
 629      *
 630      * <h2><a id="access"></a>Access checking</h2>
 631      * Access checks are applied in the factory methods of {@code Lookup},
 632      * when a method handle is created.
 633      * This is a key difference from the Core Reflection API, since
 634      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 635      * performs access checking against every caller, on every call.
 636      * <p>
 637      * All access checks start from a {@code Lookup} object, which
 638      * compares its recorded lookup class against all requests to
 639      * create method handles.
 640      * A single {@code Lookup} object can be used to create any number
 641      * of access-checked method handles, all checked against a single
 642      * lookup class.
 643      * <p>
 644      * A {@code Lookup} object can be shared with other trusted code,
 645      * such as a metaobject protocol.
 646      * A shared {@code Lookup} object delegates the capability
 647      * to create method handles on private members of the lookup class.
 648      * Even if privileged code uses the {@code Lookup} object,
 649      * the access checking is confined to the privileges of the
 650      * original lookup class.
 651      * <p>
 652      * A lookup can fail, because
 653      * the containing class is not accessible to the lookup class, or
 654      * because the desired class member is missing, or because the
 655      * desired class member is not accessible to the lookup class, or
 656      * because the lookup object is not trusted enough to access the member.
 657      * In the case of a field setter function on a {@code final} field,
 658      * finality enforcement is treated as a kind of access control,
 659      * and the lookup will fail, except in special cases of
 660      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 661      * In any of these cases, a {@code ReflectiveOperationException} will be
 662      * thrown from the attempted lookup.  The exact class will be one of
 663      * the following:
 664      * <ul>
 665      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 666      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 667      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 668      * </ul>
 669      * <p>
 670      * In general, the conditions under which a method handle may be
 671      * looked up for a method {@code M} are no more restrictive than the conditions
 672      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 673      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 674      * a method handle lookup will generally raise a corresponding
 675      * checked exception, such as {@code NoSuchMethodException}.
 676      * And the effect of invoking the method handle resulting from the lookup
 677      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 678      * to executing the compiled, verified, and resolved call to {@code M}.
 679      * The same point is true of fields and constructors.
 680      * <p style="font-size:smaller;">
 681      * <em>Discussion:</em>
 682      * Access checks only apply to named and reflected methods,
 683      * constructors, and fields.
 684      * Other method handle creation methods, such as
 685      * {@link MethodHandle#asType MethodHandle.asType},
 686      * do not require any access checks, and are used
 687      * independently of any {@code Lookup} object.
 688      * <p>
 689      * If the desired member is {@code protected}, the usual JVM rules apply,
 690      * including the requirement that the lookup class must either be in the
 691      * same package as the desired member, or must inherit that member.
 692      * (See the Java Virtual Machine Specification, sections {@jvms
 693      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 694      * In addition, if the desired member is a non-static field or method
 695      * in a different package, the resulting method handle may only be applied
 696      * to objects of the lookup class or one of its subclasses.
 697      * This requirement is enforced by narrowing the type of the leading
 698      * {@code this} parameter from {@code C}
 699      * (which will necessarily be a superclass of the lookup class)
 700      * to the lookup class itself.
 701      * <p>
 702      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 703      * that the receiver argument must match both the resolved method <em>and</em>
 704      * the current class.  Again, this requirement is enforced by narrowing the
 705      * type of the leading parameter to the resulting method handle.
 706      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 707      * <p>
 708      * The JVM represents constructors and static initializer blocks as internal methods
 709      * with special names ({@code "<init>"} and {@code "<clinit>"}).
 710      * The internal syntax of invocation instructions allows them to refer to such internal
 711      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 712      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 713      * <p>
 714      * If the relationship between nested types is expressed directly through the
 715      * {@code NestHost} and {@code NestMembers} attributes
 716      * (see the Java Virtual Machine Specification, sections {@jvms
 717      * 4.7.28} and {@jvms 4.7.29}),
 718      * then the associated {@code Lookup} object provides direct access to
 719      * the lookup class and all of its nestmates
 720      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 721      * Otherwise, access between nested classes is obtained by the Java compiler creating
 722      * a wrapper method to access a private method of another class in the same nest.
 723      * For example, a nested class {@code C.D}
 724      * can access private members within other related classes such as
 725      * {@code C}, {@code C.D.E}, or {@code C.B},
 726      * but the Java compiler may need to generate wrapper methods in
 727      * those related classes.  In such cases, a {@code Lookup} object on
 728      * {@code C.E} would be unable to access those private members.
 729      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 730      * which can transform a lookup on {@code C.E} into one on any of those other
 731      * classes, without special elevation of privilege.
 732      * <p>
 733      * The accesses permitted to a given lookup object may be limited,
 734      * according to its set of {@link #lookupModes lookupModes},
 735      * to a subset of members normally accessible to the lookup class.
 736      * For example, the {@link MethodHandles#publicLookup publicLookup}
 737      * method produces a lookup object which is only allowed to access
 738      * public members in public classes of exported packages.
 739      * The caller sensitive method {@link MethodHandles#lookup lookup}
 740      * produces a lookup object with full capabilities relative to
 741      * its caller class, to emulate all supported bytecode behaviors.
 742      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 743      * with fewer access modes than the original lookup object.
 744      *
 745      * <p style="font-size:smaller;">
 746      * <a id="privacc"></a>
 747      * <em>Discussion of private and module access:</em>
 748      * We say that a lookup has <em>private access</em>
 749      * if its {@linkplain #lookupModes lookup modes}
 750      * include the possibility of accessing {@code private} members
 751      * (which includes the private members of nestmates).
 752      * As documented in the relevant methods elsewhere,
 753      * only lookups with private access possess the following capabilities:
 754      * <ul style="font-size:smaller;">
 755      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 756      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 757      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 758      *     for classes accessible to the lookup class
 759      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 760      *     within the same package member
 761      * </ul>
 762      * <p style="font-size:smaller;">
 763      * Similarly, a lookup with module access ensures that the original lookup creator was
 764      * a member in the same module as the lookup class.
 765      * <p style="font-size:smaller;">
 766      * Private and module access are independently determined modes; a lookup may have
 767      * either or both or neither.  A lookup which possesses both access modes is said to
 768      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
 769      * <p style="font-size:smaller;">
 770      * A lookup with <em>original access</em> ensures that this lookup is created by
 771      * the original lookup class and the bootstrap method invoked by the VM.
 772      * Such a lookup with original access also has private and module access
 773      * which has the following additional capability:
 774      * <ul style="font-size:smaller;">
 775      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 776      *     such as {@code Class.forName}
 777      * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
 778      * class data} associated with the lookup class</li>
 779      * </ul>
 780      * <p style="font-size:smaller;">
 781      * Each of these permissions is a consequence of the fact that a lookup object
 782      * with private access can be securely traced back to an originating class,
 783      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 784      * can be reliably determined and emulated by method handles.
 785      *
 786      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 787      * When a lookup class in one module {@code M1} accesses a class in another module
 788      * {@code M2}, extra access checking is performed beyond the access mode bits.
 789      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 790      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 791      * and when the type is in a package of {@code M2} that is exported to
 792      * at least {@code M1}.
 793      * <p>
 794      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 795      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 796      * MethodHandles.privateLookupIn} methods.
 797      * Teleporting across modules will always record the original lookup class as
 798      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 799      * and drops {@link Lookup#MODULE MODULE} access.
 800      * If the target class is in the same module as the lookup class {@code C},
 801      * then the target class becomes the new lookup class
 802      * and there is no change to the previous lookup class.
 803      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 804      * {@code C} becomes the new previous lookup class
 805      * and the target class becomes the new lookup class.
 806      * In that case, if there was already a previous lookup class in {@code M0},
 807      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 808      * drops all privileges.
 809      * For example,
 810      * {@snippet lang="java" :
 811      * Lookup lookup = MethodHandles.lookup();   // in class C
 812      * Lookup lookup2 = lookup.in(D.class);
 813      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 814      * }
 815      * <p>
 816      * The {@link #lookup()} factory method produces a {@code Lookup} object
 817      * with {@code null} previous lookup class.
 818      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 819      * to class {@code D} without elevation of privileges.
 820      * If {@code C} and {@code D} are in the same module,
 821      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 822      * same previous lookup class as the original {@code lookup}, or
 823      * {@code null} if not present.
 824      * <p>
 825      * When a {@code Lookup} teleports from a class
 826      * in one nest to another nest, {@code PRIVATE} access is dropped.
 827      * When a {@code Lookup} teleports from a class in one package to
 828      * another package, {@code PACKAGE} access is dropped.
 829      * When a {@code Lookup} teleports from a class in one module to another module,
 830      * {@code MODULE} access is dropped.
 831      * Teleporting across modules drops the ability to access non-exported classes
 832      * in both the module of the new lookup class and the module of the old lookup class
 833      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 834      * A {@code Lookup} can teleport back and forth to a class in the module of
 835      * the lookup class and the module of the previous class lookup.
 836      * Teleporting across modules can only decrease access but cannot increase it.
 837      * Teleporting to some third module drops all accesses.
 838      * <p>
 839      * In the above example, if {@code C} and {@code D} are in different modules,
 840      * {@code lookup2} records {@code D} as its lookup class and
 841      * {@code C} as its previous lookup class and {@code lookup2} has only
 842      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 843      * {@code C}'s module and {@code D}'s module.
 844      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 845      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 846      * class {@code D} is recorded as its previous lookup class.
 847      * <p>
 848      * Teleporting across modules restricts access to the public types that
 849      * both the lookup class and the previous lookup class can equally access
 850      * (see below).
 851      * <p>
 852      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 853      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 854      * and create a new {@code Lookup} with <a href="#privacc">private access</a>
 855      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 856      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 857      * to call {@code privateLookupIn}.
 858      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 859      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 860      * produces a new {@code Lookup} on {@code T} with full capabilities.
 861      * A {@code lookup} on {@code C} is also allowed
 862      * to do deep reflection on {@code T} in another module {@code M2} if
 863      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 864      * the package containing {@code T} to at least {@code M1}.
 865      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 866      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 867      * The resulting {@code Lookup} can be used to do member lookup or teleport
 868      * to another lookup class by calling {@link #in Lookup::in}.  But
 869      * it cannot be used to obtain another private {@code Lookup} by calling
 870      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 871      * because it has no {@code MODULE} access.
 872      *
 873      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 874      *
 875      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 876      * allows cross-module access. The access checking is performed with respect
 877      * to both the lookup class and the previous lookup class if present.
 878      * <p>
 879      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 880      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 881      * exported unconditionally}.
 882      * <p>
 883      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 884      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 885      * that are readable to {@code M1} and the type is in a package that is exported
 886      * at least to {@code M1}.
 887      * <p>
 888      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 889      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 890      * the intersection of all public types that are accessible to {@code M1}
 891      * with all public types that are accessible to {@code M0}. {@code M0}
 892      * reads {@code M1} and hence the set of accessible types includes:
 893      *
 894      * <ul>
 895      * <li>unconditional-exported packages from {@code M1}</li>
 896      * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li>
 897      * <li>
 898      *     unconditional-exported packages from a third module {@code M2}if both {@code M0}
 899      *     and {@code M1} read {@code M2}
 900      * </li>
 901      * <li>qualified-exported packages from {@code M1} to {@code M0}</li>
 902      * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li>
 903      * <li>
 904      *     qualified-exported packages from a third module {@code M2} to both {@code M0} and
 905      *     {@code M1} if both {@code M0} and {@code M1} read {@code M2}
 906      * </li>
 907      * </ul>
 908      *
 909      * <h2><a id="access-modes"></a>Access modes</h2>
 910      *
 911      * The table below shows the access modes of a {@code Lookup} produced by
 912      * any of the following factory or transformation methods:
 913      * <ul>
 914      * <li>{@link #lookup() MethodHandles::lookup}</li>
 915      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 916      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 917      * <li>{@link Lookup#in Lookup::in}</li>
 918      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 919      * </ul>
 920      *
 921      * <table class="striped">
 922      * <caption style="display:none">
 923      * Access mode summary
 924      * </caption>
 925      * <thead>
 926      * <tr>
 927      * <th scope="col">Lookup object</th>
 928      * <th style="text-align:center">original</th>
 929      * <th style="text-align:center">protected</th>
 930      * <th style="text-align:center">private</th>
 931      * <th style="text-align:center">package</th>
 932      * <th style="text-align:center">module</th>
 933      * <th style="text-align:center">public</th>
 934      * </tr>
 935      * </thead>
 936      * <tbody>
 937      * <tr>
 938      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 939      * <td style="text-align:center">ORI</td>
 940      * <td style="text-align:center">PRO</td>
 941      * <td style="text-align:center">PRI</td>
 942      * <td style="text-align:center">PAC</td>
 943      * <td style="text-align:center">MOD</td>
 944      * <td style="text-align:center">1R</td>
 945      * </tr>
 946      * <tr>
 947      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 948      * <td></td>
 949      * <td></td>
 950      * <td></td>
 951      * <td style="text-align:center">PAC</td>
 952      * <td style="text-align:center">MOD</td>
 953      * <td style="text-align:center">1R</td>
 954      * </tr>
 955      * <tr>
 956      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 957      * <td></td>
 958      * <td></td>
 959      * <td></td>
 960      * <td></td>
 961      * <td style="text-align:center">MOD</td>
 962      * <td style="text-align:center">1R</td>
 963      * </tr>
 964      * <tr>
 965      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 966      * <td></td>
 967      * <td></td>
 968      * <td></td>
 969      * <td></td>
 970      * <td></td>
 971      * <td style="text-align:center">2R</td>
 972      * </tr>
 973      * <tr>
 974      * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th>
 975      * <td></td>
 976      * <td></td>
 977      * <td></td>
 978      * <td></td>
 979      * <td></td>
 980      * <td style="text-align:center">2R</td>
 981      * </tr>
 982      * <tr>
 983      * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th>
 984      * <td></td>
 985      * <td style="text-align:center">PRO</td>
 986      * <td style="text-align:center">PRI</td>
 987      * <td style="text-align:center">PAC</td>
 988      * <td style="text-align:center">MOD</td>
 989      * <td style="text-align:center">1R</td>
 990      * </tr>
 991      * <tr>
 992      * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th>
 993      * <td></td>
 994      * <td style="text-align:center">PRO</td>
 995      * <td style="text-align:center">PRI</td>
 996      * <td style="text-align:center">PAC</td>
 997      * <td style="text-align:center">MOD</td>
 998      * <td style="text-align:center">1R</td>
 999      * </tr>
1000      * <tr>
1001      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th>
1002      * <td></td>
1003      * <td></td>
1004      * <td></td>
1005      * <td style="text-align:center">PAC</td>
1006      * <td style="text-align:center">MOD</td>
1007      * <td style="text-align:center">1R</td>
1008      * </tr>
1009      * <tr>
1010      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th>
1011      * <td></td>
1012      * <td></td>
1013      * <td></td>
1014      * <td></td>
1015      * <td style="text-align:center">MOD</td>
1016      * <td style="text-align:center">1R</td>
1017      * </tr>
1018      * <tr>
1019      * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th>
1020      * <td></td>
1021      * <td></td>
1022      * <td></td>
1023      * <td></td>
1024      * <td></td>
1025      * <td style="text-align:center">2R</td>
1026      * </tr>
1027      * <tr>
1028      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th>
1029      * <td></td>
1030      * <td></td>
1031      * <td style="text-align:center">PRI</td>
1032      * <td style="text-align:center">PAC</td>
1033      * <td style="text-align:center">MOD</td>
1034      * <td style="text-align:center">1R</td>
1035      * </tr>
1036      * <tr>
1037      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th>
1038      * <td></td>
1039      * <td></td>
1040      * <td></td>
1041      * <td style="text-align:center">PAC</td>
1042      * <td style="text-align:center">MOD</td>
1043      * <td style="text-align:center">1R</td>
1044      * </tr>
1045      * <tr>
1046      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th>
1047      * <td></td>
1048      * <td></td>
1049      * <td></td>
1050      * <td></td>
1051      * <td style="text-align:center">MOD</td>
1052      * <td style="text-align:center">1R</td>
1053      * </tr>
1054      * <tr>
1055      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th>
1056      * <td></td>
1057      * <td></td>
1058      * <td></td>
1059      * <td></td>
1060      * <td></td>
1061      * <td style="text-align:center">1R</td>
1062      * </tr>
1063      * <tr>
1064      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th>
1065      * <td></td>
1066      * <td></td>
1067      * <td></td>
1068      * <td></td>
1069      * <td></td>
1070      * <td style="text-align:center">none</td>
1071      * <tr>
1072      * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th>
1073      * <td></td>
1074      * <td style="text-align:center">PRO</td>
1075      * <td style="text-align:center">PRI</td>
1076      * <td style="text-align:center">PAC</td>
1077      * <td></td>
1078      * <td style="text-align:center">2R</td>
1079      * </tr>
1080      * <tr>
1081      * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th>
1082      * <td></td>
1083      * <td style="text-align:center">PRO</td>
1084      * <td style="text-align:center">PRI</td>
1085      * <td style="text-align:center">PAC</td>
1086      * <td></td>
1087      * <td style="text-align:center">2R</td>
1088      * </tr>
1089      * <tr>
1090      * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th>
1091      * <td></td>
1092      * <td></td>
1093      * <td></td>
1094      * <td></td>
1095      * <td></td>
1096      * <td style="text-align:center">IAE</td>
1097      * </tr>
1098      * <tr>
1099      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th>
1100      * <td></td>
1101      * <td></td>
1102      * <td></td>
1103      * <td style="text-align:center">PAC</td>
1104      * <td></td>
1105      * <td style="text-align:center">2R</td>
1106      * </tr>
1107      * <tr>
1108      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th>
1109      * <td></td>
1110      * <td></td>
1111      * <td></td>
1112      * <td></td>
1113      * <td></td>
1114      * <td style="text-align:center">2R</td>
1115      * </tr>
1116      * <tr>
1117      * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th>
1118      * <td></td>
1119      * <td></td>
1120      * <td></td>
1121      * <td></td>
1122      * <td></td>
1123      * <td style="text-align:center">2R</td>
1124      * </tr>
1125      * <tr>
1126      * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th>
1127      * <td></td>
1128      * <td></td>
1129      * <td></td>
1130      * <td></td>
1131      * <td></td>
1132      * <td style="text-align:center">none</td>
1133      * </tr>
1134      * <tr>
1135      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th>
1136      * <td></td>
1137      * <td></td>
1138      * <td style="text-align:center">PRI</td>
1139      * <td style="text-align:center">PAC</td>
1140      * <td></td>
1141      * <td style="text-align:center">2R</td>
1142      * </tr>
1143      * <tr>
1144      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th>
1145      * <td></td>
1146      * <td></td>
1147      * <td></td>
1148      * <td style="text-align:center">PAC</td>
1149      * <td></td>
1150      * <td style="text-align:center">2R</td>
1151      * </tr>
1152      * <tr>
1153      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th>
1154      * <td></td>
1155      * <td></td>
1156      * <td></td>
1157      * <td></td>
1158      * <td></td>
1159      * <td style="text-align:center">2R</td>
1160      * </tr>
1161      * <tr>
1162      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th>
1163      * <td></td>
1164      * <td></td>
1165      * <td></td>
1166      * <td></td>
1167      * <td></td>
1168      * <td style="text-align:center">2R</td>
1169      * </tr>
1170      * <tr>
1171      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th>
1172      * <td></td>
1173      * <td></td>
1174      * <td></td>
1175      * <td></td>
1176      * <td></td>
1177      * <td style="text-align:center">none</td>
1178      * </tr>
1179      * <tr>
1180      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th>
1181      * <td></td>
1182      * <td></td>
1183      * <td style="text-align:center">PRI</td>
1184      * <td style="text-align:center">PAC</td>
1185      * <td style="text-align:center">MOD</td>
1186      * <td style="text-align:center">1R</td>
1187      * </tr>
1188      * <tr>
1189      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th>
1190      * <td></td>
1191      * <td></td>
1192      * <td></td>
1193      * <td style="text-align:center">PAC</td>
1194      * <td style="text-align:center">MOD</td>
1195      * <td style="text-align:center">1R</td>
1196      * </tr>
1197      * <tr>
1198      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th>
1199      * <td></td>
1200      * <td></td>
1201      * <td></td>
1202      * <td></td>
1203      * <td style="text-align:center">MOD</td>
1204      * <td style="text-align:center">1R</td>
1205      * </tr>
1206      * <tr>
1207      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th>
1208      * <td></td>
1209      * <td></td>
1210      * <td></td>
1211      * <td></td>
1212      * <td></td>
1213      * <td style="text-align:center">1R</td>
1214      * </tr>
1215      * <tr>
1216      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th>
1217      * <td></td>
1218      * <td></td>
1219      * <td></td>
1220      * <td></td>
1221      * <td></td>
1222      * <td style="text-align:center">none</td>
1223      * </tr>
1224      * <tr>
1225      * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th>
1226      * <td></td>
1227      * <td></td>
1228      * <td></td>
1229      * <td></td>
1230      * <td></td>
1231      * <td style="text-align:center">U</td>
1232      * </tr>
1233      * <tr>
1234      * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th>
1235      * <td></td>
1236      * <td></td>
1237      * <td></td>
1238      * <td></td>
1239      * <td></td>
1240      * <td style="text-align:center">U</td>
1241      * </tr>
1242      * <tr>
1243      * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th>
1244      * <td></td>
1245      * <td></td>
1246      * <td></td>
1247      * <td></td>
1248      * <td></td>
1249      * <td style="text-align:center">U</td>
1250      * </tr>
1251      * <tr>
1252      * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th>
1253      * <td></td>
1254      * <td></td>
1255      * <td></td>
1256      * <td></td>
1257      * <td></td>
1258      * <td style="text-align:center">none</td>
1259      * </tr>
1260      * <tr>
1261      * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th>
1262      * <td></td>
1263      * <td></td>
1264      * <td></td>
1265      * <td></td>
1266      * <td></td>
1267      * <td style="text-align:center">IAE</td>
1268      * </tr>
1269      * <tr>
1270      * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th>
1271      * <td></td>
1272      * <td></td>
1273      * <td></td>
1274      * <td></td>
1275      * <td></td>
1276      * <td style="text-align:center">none</td>
1277      * </tr>
1278      * </tbody>
1279      * </table>
1280      *
1281      * <p>
1282      * Notes:
1283      * <ul>
1284      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1285      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1286      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1287      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1288      * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1289      *     {@code PRO} indicates {@link #PROTECTED} bit set,
1290      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1291      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1292      *     {@code MOD} indicates {@link #MODULE} bit set,
1293      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1294      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1295      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1296      * <li>Public access comes in three kinds:
1297      * <ul>
1298      * <li>unconditional ({@code U}): the lookup assumes readability.
1299      *     The lookup has {@code null} previous lookup class.
1300      * <li>one-module-reads ({@code 1R}): the module access checking is
1301      *     performed with respect to the lookup class.  The lookup has {@code null}
1302      *     previous lookup class.
1303      * <li>two-module-reads ({@code 2R}): the module access checking is
1304      *     performed with respect to the lookup class and the previous lookup class.
1305      *     The lookup has a non-null previous lookup class which is in a
1306      *     different module from the current lookup class.
1307      * </ul>
1308      * <li>Any attempt to reach a third module loses all access.</li>
1309      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1310      * all access modes are dropped.</li>
1311      * </ul>
1312      *
1313      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1314      * Although bytecode instructions can only refer to classes in
1315      * a related class loader, this API can search for methods in any
1316      * class, as long as a reference to its {@code Class} object is
1317      * available.  Such cross-loader references are also possible with the
1318      * Core Reflection API, and are impossible to bytecode instructions
1319      * such as {@code invokestatic} or {@code getfield}.
1320      * There is a {@linkplain java.lang.SecurityManager security manager API}
1321      * to allow applications to check such cross-loader references.
1322      * These checks apply to both the {@code MethodHandles.Lookup} API
1323      * and the Core Reflection API
1324      * (as found on {@link java.lang.Class Class}).
1325      * <p>
1326      * If a security manager is present, member and class lookups are subject to
1327      * additional checks.
1328      * From one to three calls are made to the security manager.
1329      * Any of these calls can refuse access by throwing a
1330      * {@link java.lang.SecurityException SecurityException}.
1331      * Define {@code smgr} as the security manager,
1332      * {@code lookc} as the lookup class of the current lookup object,
1333      * {@code refc} as the containing class in which the member
1334      * is being sought, and {@code defc} as the class in which the
1335      * member is actually defined.
1336      * (If a class or other type is being accessed,
1337      * the {@code refc} and {@code defc} values are the class itself.)
1338      * The value {@code lookc} is defined as <em>not present</em>
1339      * if the current lookup object does not have
1340      * {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1341      * The calls are made according to the following rules:
1342      * <ul>
1343      * <li><b>Step 1:</b>
1344      *     If {@code lookc} is not present, or if its class loader is not
1345      *     the same as or an ancestor of the class loader of {@code refc},
1346      *     then {@link SecurityManager#checkPackageAccess
1347      *     smgr.checkPackageAccess(refcPkg)} is called,
1348      *     where {@code refcPkg} is the package of {@code refc}.
1349      * <li><b>Step 2a:</b>
1350      *     If the retrieved member is not public and
1351      *     {@code lookc} is not present, then
1352      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1353      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
1354      * <li><b>Step 2b:</b>
1355      *     If the retrieved class has a {@code null} class loader,
1356      *     and {@code lookc} is not present, then
1357      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1358      *     with {@code RuntimePermission("getClassLoader")} is called.
1359      * <li><b>Step 3:</b>
1360      *     If the retrieved member is not public,
1361      *     and if {@code lookc} is not present,
1362      *     and if {@code defc} and {@code refc} are different,
1363      *     then {@link SecurityManager#checkPackageAccess
1364      *     smgr.checkPackageAccess(defcPkg)} is called,
1365      *     where {@code defcPkg} is the package of {@code defc}.
1366      * </ul>
1367      * Security checks are performed after other access checks have passed.
1368      * Therefore, the above rules presuppose a member or class that is public,
1369      * or else that is being accessed from a lookup class that has
1370      * rights to access the member or class.
1371      * <p>
1372      * If a security manager is present and the current lookup object does not have
1373      * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then
1374      * {@link #defineClass(byte[]) defineClass},
1375      * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass},
1376      * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...)
1377      * defineHiddenClassWithClassData}
1378      * calls {@link SecurityManager#checkPermission smgr.checkPermission}
1379      * with {@code RuntimePermission("defineClass")}.
1380      *
1381      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1382      * A small number of Java methods have a special property called caller sensitivity.
1383      * A <em>caller-sensitive</em> method can behave differently depending on the
1384      * identity of its immediate caller.
1385      * <p>
1386      * If a method handle for a caller-sensitive method is requested,
1387      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1388      * but they take account of the lookup class in a special way.
1389      * The resulting method handle behaves as if it were called
1390      * from an instruction contained in the lookup class,
1391      * so that the caller-sensitive method detects the lookup class.
1392      * (By contrast, the invoker of the method handle is disregarded.)
1393      * Thus, in the case of caller-sensitive methods,
1394      * different lookup classes may give rise to
1395      * differently behaving method handles.
1396      * <p>
1397      * In cases where the lookup object is
1398      * {@link MethodHandles#publicLookup() publicLookup()},
1399      * or some other lookup object without the
1400      * {@linkplain #ORIGINAL original access},
1401      * the lookup class is disregarded.
1402      * In such cases, no caller-sensitive method handle can be created,
1403      * access is forbidden, and the lookup fails with an
1404      * {@code IllegalAccessException}.
1405      * <p style="font-size:smaller;">
1406      * <em>Discussion:</em>
1407      * For example, the caller-sensitive method
1408      * {@link java.lang.Class#forName(String) Class.forName(x)}
1409      * can return varying classes or throw varying exceptions,
1410      * depending on the class loader of the class that calls it.
1411      * A public lookup of {@code Class.forName} will fail, because
1412      * there is no reasonable way to determine its bytecode behavior.
1413      * <p style="font-size:smaller;">
1414      * If an application caches method handles for broad sharing,
1415      * it should use {@code publicLookup()} to create them.
1416      * If there is a lookup of {@code Class.forName}, it will fail,
1417      * and the application must take appropriate action in that case.
1418      * It may be that a later lookup, perhaps during the invocation of a
1419      * bootstrap method, can incorporate the specific identity
1420      * of the caller, making the method accessible.
1421      * <p style="font-size:smaller;">
1422      * The function {@code MethodHandles.lookup} is caller sensitive
1423      * so that there can be a secure foundation for lookups.
1424      * Nearly all other methods in the JSR 292 API rely on lookup
1425      * objects to check access requests.
1426      *
1427      * @revised 9
1428      */
1429     public static final
1430     class Lookup {
1431         /** The class on behalf of whom the lookup is being performed. */
1432         private final Class<?> lookupClass;
1433 
1434         /** previous lookup class */
1435         private final Class<?> prevLookupClass;
1436 
1437         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1438         private final int allowedModes;
1439 
1440         static {
1441             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1442         }
1443 
1444         /** A single-bit mask representing {@code public} access,
1445          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1446          *  The value, {@code 0x01}, happens to be the same as the value of the
1447          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1448          *  <p>
1449          *  A {@code Lookup} with this lookup mode performs cross-module access check
1450          *  with respect to the {@linkplain #lookupClass() lookup class} and
1451          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1452          */
1453         public static final int PUBLIC = Modifier.PUBLIC;
1454 
1455         /** A single-bit mask representing {@code private} access,
1456          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1457          *  The value, {@code 0x02}, happens to be the same as the value of the
1458          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1459          */
1460         public static final int PRIVATE = Modifier.PRIVATE;
1461 
1462         /** A single-bit mask representing {@code protected} access,
1463          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1464          *  The value, {@code 0x04}, happens to be the same as the value of the
1465          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1466          */
1467         public static final int PROTECTED = Modifier.PROTECTED;
1468 
1469         /** A single-bit mask representing {@code package} access (default access),
1470          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1471          *  The value is {@code 0x08}, which does not correspond meaningfully to
1472          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1473          */
1474         public static final int PACKAGE = Modifier.STATIC;
1475 
1476         /** A single-bit mask representing {@code module} access,
1477          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1478          *  The value is {@code 0x10}, which does not correspond meaningfully to
1479          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1480          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1481          *  with this lookup mode can access all public types in the module of the
1482          *  lookup class and public types in packages exported by other modules
1483          *  to the module of the lookup class.
1484          *  <p>
1485          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1486          *  previous lookup class} is always {@code null}.
1487          *
1488          *  @since 9
1489          */
1490         public static final int MODULE = PACKAGE << 1;
1491 
1492         /** A single-bit mask representing {@code unconditional} access
1493          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1494          *  The value is {@code 0x20}, which does not correspond meaningfully to
1495          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1496          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1497          *  java.lang.Module#canRead(java.lang.Module) readability}.
1498          *  This lookup mode can access all public members of public types
1499          *  of all modules when the type is in a package that is {@link
1500          *  java.lang.Module#isExported(String) exported unconditionally}.
1501          *
1502          *  <p>
1503          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1504          *  previous lookup class} is always {@code null}.
1505          *
1506          *  @since 9
1507          *  @see #publicLookup()
1508          */
1509         public static final int UNCONDITIONAL = PACKAGE << 2;
1510 
1511         /** A single-bit mask representing {@code original} access
1512          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1513          *  The value is {@code 0x40}, which does not correspond meaningfully to
1514          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1515          *
1516          *  <p>
1517          *  If this lookup mode is set, the {@code Lookup} object must be
1518          *  created by the original lookup class by calling
1519          *  {@link MethodHandles#lookup()} method or by a bootstrap method
1520          *  invoked by the VM.  The {@code Lookup} object with this lookup
1521          *  mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1522          *
1523          *  @since 16
1524          */
1525         public static final int ORIGINAL = PACKAGE << 3;
1526 
1527         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1528         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);   // with original access
1529         private static final int TRUSTED   = -1;
1530 
1531         /*
1532          * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1533          * Adjust 0 => PACKAGE
1534          */
1535         private static int fixmods(int mods) {
1536             mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1537             if (Modifier.isPublic(mods))
1538                 mods |= UNCONDITIONAL;
1539             return (mods != 0) ? mods : PACKAGE;
1540         }
1541 
1542         /** Tells which class is performing the lookup.  It is this class against
1543          *  which checks are performed for visibility and access permissions.
1544          *  <p>
1545          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1546          *  access checks are performed against both the lookup class and the previous lookup class.
1547          *  <p>
1548          *  The class implies a maximum level of access permission,
1549          *  but the permissions may be additionally limited by the bitmask
1550          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1551          *  can be accessed.
1552          *  @return the lookup class, on behalf of which this lookup object finds members
1553          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1554          */
1555         public Class<?> lookupClass() {
1556             return lookupClass;
1557         }
1558 
1559         /** Reports a lookup class in another module that this lookup object
1560          * was previously teleported from, or {@code null}.
1561          * <p>
1562          * A {@code Lookup} object produced by the factory methods, such as the
1563          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1564          * has {@code null} previous lookup class.
1565          * A {@code Lookup} object has a non-null previous lookup class
1566          * when this lookup was teleported from an old lookup class
1567          * in one module to a new lookup class in another module.
1568          *
1569          * @return the lookup class in another module that this lookup object was
1570          *         previously teleported from, or {@code null}
1571          * @since 14
1572          * @see #in(Class)
1573          * @see MethodHandles#privateLookupIn(Class, Lookup)
1574          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1575          */
1576         public Class<?> previousLookupClass() {
1577             return prevLookupClass;
1578         }
1579 
1580         // This is just for calling out to MethodHandleImpl.
1581         private Class<?> lookupClassOrNull() {
1582             return (allowedModes == TRUSTED) ? null : lookupClass;
1583         }
1584 
1585         /** Tells which access-protection classes of members this lookup object can produce.
1586          *  The result is a bit-mask of the bits
1587          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1588          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1589          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1590          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1591          *  {@linkplain #MODULE MODULE (0x10)},
1592          *  {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1593          *  and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1594          *  <p>
1595          *  A freshly-created lookup object
1596          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1597          *  all possible bits set, except {@code UNCONDITIONAL}.
1598          *  A lookup object on a new lookup class
1599          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1600          *  may have some mode bits set to zero.
1601          *  Mode bits can also be
1602          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1603          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1604          *  The purpose of this is to restrict access via the new lookup object,
1605          *  so that it can access only names which can be reached by the original
1606          *  lookup object, and also by the new lookup class.
1607          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1608          *  @see #in
1609          *  @see #dropLookupMode
1610          *
1611          *  @revised 9
1612          */
1613         public int lookupModes() {
1614             return allowedModes & ALL_MODES;
1615         }
1616 
1617         /** Embody the current class (the lookupClass) as a lookup class
1618          * for method handle creation.
1619          * Must be called by from a method in this package,
1620          * which in turn is called by a method not in this package.
1621          */
1622         Lookup(Class<?> lookupClass) {
1623             this(lookupClass, null, FULL_POWER_MODES);
1624         }
1625 
1626         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1627             assert PrimitiveClass.isPrimaryType(lookupClass);
1628             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1629                     && prevLookupClass.getModule() != lookupClass.getModule());
1630             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1631             this.lookupClass = lookupClass;
1632             this.prevLookupClass = prevLookupClass;
1633             this.allowedModes = allowedModes;
1634         }
1635 
1636         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1637             // make sure we haven't accidentally picked up a privileged class:
1638             checkUnprivilegedlookupClass(lookupClass);
1639             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1640         }
1641 
1642         /**
1643          * Creates a lookup on the specified new lookup class.
1644          * The resulting object will report the specified
1645          * class as its own {@link #lookupClass() lookupClass}.
1646          *
1647          * <p>
1648          * However, the resulting {@code Lookup} object is guaranteed
1649          * to have no more access capabilities than the original.
1650          * In particular, access capabilities can be lost as follows:<ul>
1651          * <li>If the new lookup class is different from the old lookup class,
1652          * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1653          * <li>If the new lookup class is in a different module from the old one,
1654          * i.e. {@link #MODULE MODULE} access is lost.
1655          * <li>If the new lookup class is in a different package
1656          * than the old one, protected and default (package) members will not be accessible,
1657          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1658          * <li>If the new lookup class is not within the same package member
1659          * as the old one, private members will not be accessible, and protected members
1660          * will not be accessible by virtue of inheritance,
1661          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1662          * (Protected members may continue to be accessible because of package sharing.)
1663          * <li>If the new lookup class is not
1664          * {@linkplain #accessClass(Class) accessible} to this lookup,
1665          * then no members, not even public members, will be accessible
1666          * i.e. all access modes are lost.
1667          * <li>If the new lookup class, the old lookup class and the previous lookup class
1668          * are all in different modules i.e. teleporting to a third module,
1669          * all access modes are lost.
1670          * </ul>
1671          * <p>
1672          * The new previous lookup class is chosen as follows:
1673          * <ul>
1674          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1675          * the new previous lookup class is {@code null}.
1676          * <li>If the new lookup class is in the same module as the old lookup class,
1677          * the new previous lookup class is the old previous lookup class.
1678          * <li>If the new lookup class is in a different module from the old lookup class,
1679          * the new previous lookup class is the old lookup class.
1680          *</ul>
1681          * <p>
1682          * The resulting lookup's capabilities for loading classes
1683          * (used during {@link #findClass} invocations)
1684          * are determined by the lookup class' loader,
1685          * which may change due to this operation.
1686          *
1687          * @param requestedLookupClass the desired lookup class for the new lookup object
1688          * @return a lookup object which reports the desired lookup class, or the same object
1689          * if there is no change
1690          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1691          * @throws NullPointerException if the argument is null
1692          *
1693          * @revised 9
1694          * @see #accessClass(Class)
1695          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1696          */
1697         public Lookup in(Class<?> requestedLookupClass) {
1698             Objects.requireNonNull(requestedLookupClass);
1699             if (requestedLookupClass.isPrimitive())
1700                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1701             if (requestedLookupClass.isArray())
1702                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1703 
1704             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1705                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1706             if (requestedLookupClass == this.lookupClass)
1707                 return this;  // keep same capabilities
1708             int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1709             Module fromModule = this.lookupClass.getModule();
1710             Module targetModule = requestedLookupClass.getModule();
1711             Class<?> plc = this.previousLookupClass();
1712             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1713                 assert plc == null;
1714                 newModes = UNCONDITIONAL;
1715             } else if (fromModule != targetModule) {
1716                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1717                     // allow hopping back and forth between fromModule and plc's module
1718                     // but not the third module
1719                     newModes = 0;
1720                 }
1721                 // drop MODULE access
1722                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1723                 // teleport from this lookup class
1724                 plc = this.lookupClass;
1725             }
1726             if ((newModes & PACKAGE) != 0
1727                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1728                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1729             }
1730             // Allow nestmate lookups to be created without special privilege:
1731             if ((newModes & PRIVATE) != 0
1732                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1733                 newModes &= ~(PRIVATE|PROTECTED);
1734             }
1735             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1736                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1737                 // The requested class it not accessible from the lookup class.
1738                 // No permissions.
1739                 newModes = 0;
1740             }
1741             return newLookup(requestedLookupClass, plc, newModes);
1742         }
1743 
1744         /**
1745          * Creates a lookup on the same lookup class which this lookup object
1746          * finds members, but with a lookup mode that has lost the given lookup mode.
1747          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1748          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1749          * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1750          * {@link #UNCONDITIONAL UNCONDITIONAL}.
1751          *
1752          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1753          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1754          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1755          * lookup has no access.
1756          *
1757          * <p> If this lookup is not a public lookup, then the following applies
1758          * regardless of its {@linkplain #lookupModes() lookup modes}.
1759          * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1760          * dropped and so the resulting lookup mode will never have these access
1761          * capabilities. When dropping {@code PACKAGE}
1762          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1763          * access. When dropping {@code MODULE} then the resulting lookup will not
1764          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1765          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1766          *
1767          * @apiNote
1768          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1769          * delegate non-public access within the package of the lookup class without
1770          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1771          * A lookup with {@code MODULE} but not
1772          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1773          * the module of the lookup class without conferring package access.
1774          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1775          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1776          * to public classes accessible to both the module of the lookup class
1777          * and the module of the previous lookup class.
1778          *
1779          * @param modeToDrop the lookup mode to drop
1780          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1781          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1782          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1783          * or {@code UNCONDITIONAL}
1784          * @see MethodHandles#privateLookupIn
1785          * @since 9
1786          */
1787         public Lookup dropLookupMode(int modeToDrop) {
1788             int oldModes = lookupModes();
1789             int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1790             switch (modeToDrop) {
1791                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1792                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1793                 case PACKAGE: newModes &= ~(PRIVATE); break;
1794                 case PROTECTED:
1795                 case PRIVATE:
1796                 case ORIGINAL:
1797                 case UNCONDITIONAL: break;
1798                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1799             }
1800             if (newModes == oldModes) return this;  // return self if no change
1801             return newLookup(lookupClass(), previousLookupClass(), newModes);
1802         }
1803 
1804         /**
1805          * Creates and links a class or interface from {@code bytes}
1806          * with the same class loader and in the same runtime package and
1807          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1808          * {@linkplain #lookupClass() lookup class} as if calling
1809          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1810          * ClassLoader::defineClass}.
1811          *
1812          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1813          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1814          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1815          * that the lookup object was created by a caller in the runtime package (or derived
1816          * from a lookup originally created by suitably privileged code to a target class in
1817          * the runtime package). </p>
1818          *
1819          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1820          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1821          * same package as the lookup class. </p>
1822          *
1823          * <p> This method does not run the class initializer. The class initializer may
1824          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1825          * Specification</em>. </p>
1826          *
1827          * <p> If there is a security manager and this lookup does not have {@linkplain
1828          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1829          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1830          *
1831          * @param bytes the class bytes
1832          * @return the {@code Class} object for the class
1833          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1834          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1835          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1836          * than the lookup class or {@code bytes} is not a class or interface
1837          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1838          * @throws VerifyError if the newly created class cannot be verified
1839          * @throws LinkageError if the newly created class cannot be linked for any other reason
1840          * @throws SecurityException if a security manager is present and it
1841          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1842          * @throws NullPointerException if {@code bytes} is {@code null}
1843          * @since 9
1844          * @see Lookup#privateLookupIn
1845          * @see Lookup#dropLookupMode
1846          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1847          */
1848         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1849             ensureDefineClassPermission();
1850             if ((lookupModes() & PACKAGE) == 0)
1851                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1852             return makeClassDefiner(bytes.clone()).defineClass(false);
1853         }
1854 
1855         private void ensureDefineClassPermission() {
1856             if (allowedModes == TRUSTED)  return;
1857 
1858             if (!hasFullPrivilegeAccess()) {
1859                 @SuppressWarnings("removal")
1860                 SecurityManager sm = System.getSecurityManager();
1861                 if (sm != null)
1862                     sm.checkPermission(new RuntimePermission("defineClass"));
1863             }
1864         }
1865 
1866         /**
1867          * The set of class options that specify whether a hidden class created by
1868          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1869          * Lookup::defineHiddenClass} method is dynamically added as a new member
1870          * to the nest of a lookup class and/or whether a hidden class has
1871          * a strong relationship with the class loader marked as its defining loader.
1872          *
1873          * @since 15
1874          */
1875         public enum ClassOption {
1876             /**
1877              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1878              * of a lookup class as a nestmate.
1879              *
1880              * <p> A hidden nestmate class has access to the private members of all
1881              * classes and interfaces in the same nest.
1882              *
1883              * @see Class#getNestHost()
1884              */
1885             NESTMATE(NESTMATE_CLASS),
1886 
1887             /**
1888              * Specifies that a hidden class has a <em>strong</em>
1889              * relationship with the class loader marked as its defining loader,
1890              * as a normal class or interface has with its own defining loader.
1891              * This means that the hidden class may be unloaded if and only if
1892              * its defining loader is not reachable and thus may be reclaimed
1893              * by a garbage collector (JLS {@jls 12.7}).
1894              *
1895              * <p> By default, a hidden class or interface may be unloaded
1896              * even if the class loader that is marked as its defining loader is
1897              * <a href="../ref/package-summary.html#reachability">reachable</a>.
1898 
1899              *
1900              * @jls 12.7 Unloading of Classes and Interfaces
1901              */
1902             STRONG(STRONG_LOADER_LINK);
1903 
1904             /* the flag value is used by VM at define class time */
1905             private final int flag;
1906             ClassOption(int flag) {
1907                 this.flag = flag;
1908             }
1909 
1910             static int optionsToFlag(Set<ClassOption> options) {
1911                 int flags = 0;
1912                 for (ClassOption cp : options) {
1913                     flags |= cp.flag;
1914                 }
1915                 return flags;
1916             }
1917         }
1918 
1919         /**
1920          * Creates a <em>hidden</em> class or interface from {@code bytes},
1921          * returning a {@code Lookup} on the newly created class or interface.
1922          *
1923          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1924          * which either defines {@code C} directly or delegates to another class loader.
1925          * A class loader defines {@code C} directly by invoking
1926          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1927          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1928          * to derive {@code C} from a purported representation in {@code class} file format.
1929          * In situations where use of a class loader is undesirable, a class or interface
1930          * {@code C} can be created by this method instead. This method is capable of
1931          * defining {@code C}, and thereby creating it, without invoking
1932          * {@code ClassLoader::defineClass}.
1933          * Instead, this method defines {@code C} as if by arranging for
1934          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1935          * from a purported representation in {@code class} file format
1936          * using the following rules:
1937          *
1938          * <ol>
1939          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1940          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1941          * This level of access is needed to create {@code C} in the module
1942          * of the lookup class of this {@code Lookup}.</li>
1943          *
1944          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1945          * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1946          * The major and minor version may differ from the {@code class} file version
1947          * of the lookup class of this {@code Lookup}.</li>
1948          *
1949          * <li> The value of {@code this_class} must be a valid index in the
1950          * {@code constant_pool} table, and the entry at that index must be a valid
1951          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1952          * encoded in internal form that is specified by this structure. {@code N} must
1953          * denote a class or interface in the same package as the lookup class.</li>
1954          *
1955          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1956          * where {@code <suffix>} is an unqualified name.
1957          *
1958          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1959          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1960          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1961          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1962          * refers to the new {@code CONSTANT_Utf8_info} structure.
1963          *
1964          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1965          *
1966          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1967          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1968          * with the following adjustments:
1969          * <ul>
1970          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1971          * that includes a single {@code "."} character, even though this is not a valid
1972          * binary class or interface name in internal form.</li>
1973          *
1974          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1975          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1976          *
1977          * <li> {@code C} is considered to have the same runtime
1978          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1979          * and {@linkplain java.security.ProtectionDomain protection domain}
1980          * as the lookup class of this {@code Lookup}.
1981          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1982          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1983          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1984          * <ul>
1985          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1986          *      even though this is not a valid binary class or interface name.</li>
1987          * <li> {@link Class#descriptorString()} returns the string
1988          *      {@code "L" + N + "." + <suffix> + ";"},
1989          *      even though this is not a valid type descriptor name.</li>
1990          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
1991          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
1992          * </ul>
1993          * </ul>
1994          * </li>
1995          * </ol>
1996          *
1997          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1998          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
1999          * <ul>
2000          * <li> During verification, whenever it is necessary to load the class named
2001          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
2002          * made of any class loader.</li>
2003          *
2004          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
2005          * by {@code this_class}, the symbolic reference is considered to be resolved to
2006          * {@code C} and resolution always succeeds immediately.</li>
2007          * </ul>
2008          *
2009          * <p> If the {@code initialize} parameter is {@code true},
2010          * then {@code C} is initialized by the Java Virtual Machine.
2011          *
2012          * <p> The newly created class or interface {@code C} serves as the
2013          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
2014          * returned by this method. {@code C} is <em>hidden</em> in the sense that
2015          * no other class or interface can refer to {@code C} via a constant pool entry.
2016          * That is, a hidden class or interface cannot be named as a supertype, a field type,
2017          * a method parameter type, or a method return type by any other class.
2018          * This is because a hidden class or interface does not have a binary name, so
2019          * there is no internal form available to record in any class's constant pool.
2020          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
2021          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
2022          * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class)
2023          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
2024          * JVM Tool Interface</a>.
2025          *
2026          * <p> A class or interface created by
2027          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
2028          * a class loader} has a strong relationship with that class loader.
2029          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
2030          * that {@linkplain Class#getClassLoader() defined it}.
2031          * This means that a class created by a class loader may be unloaded if and
2032          * only if its defining loader is not reachable and thus may be reclaimed
2033          * by a garbage collector (JLS {@jls 12.7}).
2034          *
2035          * By default, however, a hidden class or interface may be unloaded even if
2036          * the class loader that is marked as its defining loader is
2037          * <a href="../ref/package-summary.html#reachability">reachable</a>.
2038          * This behavior is useful when a hidden class or interface serves multiple
2039          * classes defined by arbitrary class loaders.  In other cases, a hidden
2040          * class or interface may be linked to a single class (or a small number of classes)
2041          * with the same defining loader as the hidden class or interface.
2042          * In such cases, where the hidden class or interface must be coterminous
2043          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
2044          * option may be passed in {@code options}.
2045          * This arranges for a hidden class to have the same strong relationship
2046          * with the class loader marked as its defining loader,
2047          * as a normal class or interface has with its own defining loader.
2048          *
2049          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
2050          * may still prevent a hidden class or interface from being
2051          * unloaded by ensuring that the {@code Class} object is reachable.
2052          *
2053          * <p> The unloading characteristics are set for each hidden class when it is
2054          * defined, and cannot be changed later.  An advantage of allowing hidden classes
2055          * to be unloaded independently of the class loader marked as their defining loader
2056          * is that a very large number of hidden classes may be created by an application.
2057          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
2058          * just as if normal classes were created by class loaders.
2059          *
2060          * <p> Classes and interfaces in a nest are allowed to have mutual access to
2061          * their private members.  The nest relationship is determined by
2062          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
2063          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
2064          * By default, a hidden class belongs to a nest consisting only of itself
2065          * because a hidden class has no binary name.
2066          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
2067          * to create a hidden class or interface {@code C} as a member of a nest.
2068          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
2069          * in the {@code ClassFile} structure from which {@code C} was derived.
2070          * Instead, the following rules determine the nest host of {@code C}:
2071          * <ul>
2072          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
2073          *     been determined, then let {@code H} be the nest host of the lookup class.
2074          *     Otherwise, the nest host of the lookup class is determined using the
2075          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
2076          * <li>The nest host of {@code C} is determined to be {@code H},
2077          *     the nest host of the lookup class.</li>
2078          * </ul>
2079          *
2080          * <p> A hidden class or interface may be serializable, but this requires a custom
2081          * serialization mechanism in order to ensure that instances are properly serialized
2082          * and deserialized. The default serialization mechanism supports only classes and
2083          * interfaces that are discoverable by their class name.
2084          *
2085          * @param bytes the bytes that make up the class data,
2086          * in the format of a valid {@code class} file as defined by
2087          * <cite>The Java Virtual Machine Specification</cite>.
2088          * @param initialize if {@code true} the class will be initialized.
2089          * @param options {@linkplain ClassOption class options}
2090          * @return the {@code Lookup} object on the hidden class,
2091          * with {@linkplain #ORIGINAL original} and
2092          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2093          *
2094          * @throws IllegalAccessException if this {@code Lookup} does not have
2095          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2096          * @throws SecurityException if a security manager is present and it
2097          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2098          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2099          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2100          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2101          * than the lookup class or {@code bytes} is not a class or interface
2102          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2103          * @throws IncompatibleClassChangeError if the class or interface named as
2104          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2105          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2106          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2107          * {@code C} is {@code C} itself
2108          * @throws VerifyError if the newly created class cannot be verified
2109          * @throws LinkageError if the newly created class cannot be linked for any other reason
2110          * @throws NullPointerException if any parameter is {@code null}
2111          *
2112          * @since 15
2113          * @see Class#isHidden()
2114          * @jvms 4.2.1 Binary Class and Interface Names
2115          * @jvms 4.2.2 Unqualified Names
2116          * @jvms 4.7.28 The {@code NestHost} Attribute
2117          * @jvms 4.7.29 The {@code NestMembers} Attribute
2118          * @jvms 5.4.3.1 Class and Interface Resolution
2119          * @jvms 5.4.4 Access Control
2120          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2121          * @jvms 5.4 Linking
2122          * @jvms 5.5 Initialization
2123          * @jls 12.7 Unloading of Classes and Interfaces
2124          */
2125         @SuppressWarnings("doclint:reference") // cross-module links
2126         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2127                 throws IllegalAccessException
2128         {
2129             Objects.requireNonNull(bytes);
2130             Objects.requireNonNull(options);
2131 
2132             ensureDefineClassPermission();
2133             if (!hasFullPrivilegeAccess()) {
2134                 throw new IllegalAccessException(this + " does not have full privilege access");
2135             }
2136 
2137             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
2138         }
2139 
2140         /**
2141          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2142          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2143          * returning a {@code Lookup} on the newly created class or interface.
2144          *
2145          * <p> This method is equivalent to calling
2146          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2147          * as if the hidden class is injected with a private static final <i>unnamed</i>
2148          * field which is initialized with the given {@code classData} at
2149          * the first instruction of the class initializer.
2150          * The newly created class is linked by the Java Virtual Machine.
2151          *
2152          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2153          * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2154          * methods can be used to retrieve the {@code classData}.
2155          *
2156          * @apiNote
2157          * A framework can create a hidden class with class data with one or more
2158          * objects and load the class data as dynamically-computed constant(s)
2159          * via a bootstrap method.  {@link MethodHandles#classData(Lookup, String, Class)
2160          * Class data} is accessible only to the lookup object created by the newly
2161          * defined hidden class but inaccessible to other members in the same nest
2162          * (unlike private static fields that are accessible to nestmates).
2163          * Care should be taken w.r.t. mutability for example when passing
2164          * an array or other mutable structure through the class data.
2165          * Changing any value stored in the class data at runtime may lead to
2166          * unpredictable behavior.
2167          * If the class data is a {@code List}, it is good practice to make it
2168          * unmodifiable for example via {@link List#of List::of}.
2169          *
2170          * @param bytes     the class bytes
2171          * @param classData pre-initialized class data
2172          * @param initialize if {@code true} the class will be initialized.
2173          * @param options   {@linkplain ClassOption class options}
2174          * @return the {@code Lookup} object on the hidden class,
2175          * with {@linkplain #ORIGINAL original} and
2176          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2177          *
2178          * @throws IllegalAccessException if this {@code Lookup} does not have
2179          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2180          * @throws SecurityException if a security manager is present and it
2181          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2182          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2183          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2184          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2185          * than the lookup class or {@code bytes} is not a class or interface
2186          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2187          * @throws IncompatibleClassChangeError if the class or interface named as
2188          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2189          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2190          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2191          * {@code C} is {@code C} itself
2192          * @throws VerifyError if the newly created class cannot be verified
2193          * @throws LinkageError if the newly created class cannot be linked for any other reason
2194          * @throws NullPointerException if any parameter is {@code null}
2195          *
2196          * @since 16
2197          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2198          * @see Class#isHidden()
2199          * @see MethodHandles#classData(Lookup, String, Class)
2200          * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2201          * @jvms 4.2.1 Binary Class and Interface Names
2202          * @jvms 4.2.2 Unqualified Names
2203          * @jvms 4.7.28 The {@code NestHost} Attribute
2204          * @jvms 4.7.29 The {@code NestMembers} Attribute
2205          * @jvms 5.4.3.1 Class and Interface Resolution
2206          * @jvms 5.4.4 Access Control
2207          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2208          * @jvms 5.4 Linking
2209          * @jvms 5.5 Initialization
2210          * @jls 12.7 Unloading of Classes and Interface
2211          */
2212         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2213                 throws IllegalAccessException
2214         {
2215             Objects.requireNonNull(bytes);
2216             Objects.requireNonNull(classData);
2217             Objects.requireNonNull(options);
2218 
2219             ensureDefineClassPermission();
2220             if (!hasFullPrivilegeAccess()) {
2221                 throw new IllegalAccessException(this + " does not have full privilege access");
2222             }
2223 
2224             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2225                        .defineClassAsLookup(initialize, classData);
2226         }
2227 
2228         static class ClassFile {
2229             final String name;
2230             final int accessFlags;
2231             final byte[] bytes;
2232             ClassFile(String name, int accessFlags, byte[] bytes) {
2233                 this.name = name;
2234                 this.accessFlags = accessFlags;
2235                 this.bytes = bytes;
2236             }
2237 
2238             static ClassFile newInstanceNoCheck(String name, byte[] bytes) {
2239                 return new ClassFile(name, 0, bytes);
2240             }
2241 
2242             /**
2243              * This method checks the class file version and the structure of `this_class`.
2244              * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2245              * that is in the named package.
2246              *
2247              * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2248              * or the class is not in the given package name.
2249              */
2250             static ClassFile newInstance(byte[] bytes, String pkgName) {
2251                 int magic = readInt(bytes, 0);
2252                 if (magic != 0xCAFEBABE) {
2253                     throw new ClassFormatError("Incompatible magic value: " + magic);
2254                 }
2255                 int minor = readUnsignedShort(bytes, 4);
2256                 int major = readUnsignedShort(bytes, 6);
2257                 if (!VM.isSupportedClassFileVersion(major, minor)) {
2258                     throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2259                 }
2260 
2261                 String name;
2262                 int accessFlags;
2263                 try {
2264                     ClassReader reader = new ClassReader(bytes);
2265                     // ClassReader::getClassName does not check if `this_class` is CONSTANT_Class_info
2266                     // workaround to read `this_class` using readConst and validate the value
2267                     int thisClass = reader.readUnsignedShort(reader.header + 2);
2268                     Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]);
2269                     if (!(constant instanceof Type type)) {
2270                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2271                     }
2272                     if (!type.getDescriptor().startsWith("L")) {
2273                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2274                     }
2275                     name = type.getClassName();
2276                     accessFlags = reader.readUnsignedShort(reader.header);
2277                 } catch (RuntimeException e) {
2278                     // ASM exceptions are poorly specified
2279                     ClassFormatError cfe = new ClassFormatError();
2280                     cfe.initCause(e);
2281                     throw cfe;
2282                 }
2283 
2284                 // must be a class or interface
2285                 if ((accessFlags & Opcodes.ACC_MODULE) != 0) {
2286                     throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2287                 }
2288 
2289                 // check if it's in the named package
2290                 int index = name.lastIndexOf('.');
2291                 String pn = (index == -1) ? "" : name.substring(0, index);
2292                 if (!pn.equals(pkgName)) {
2293                     throw newIllegalArgumentException(name + " not in same package as lookup class");
2294                 }
2295 
2296                 return new ClassFile(name, accessFlags, bytes);
2297             }
2298 
2299             private static int readInt(byte[] bytes, int offset) {
2300                 if ((offset+4) > bytes.length) {
2301                     throw new ClassFormatError("Invalid ClassFile structure");
2302                 }
2303                 return ((bytes[offset] & 0xFF) << 24)
2304                         | ((bytes[offset + 1] & 0xFF) << 16)
2305                         | ((bytes[offset + 2] & 0xFF) << 8)
2306                         | (bytes[offset + 3] & 0xFF);
2307             }
2308 
2309             private static int readUnsignedShort(byte[] bytes, int offset) {
2310                 if ((offset+2) > bytes.length) {
2311                     throw new ClassFormatError("Invalid ClassFile structure");
2312                 }
2313                 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2314             }
2315         }
2316 
2317         /*
2318          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2319          * from the given bytes.
2320          *
2321          * Caller should make a defensive copy of the arguments if needed
2322          * before calling this factory method.
2323          *
2324          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2325          * {@bytes} denotes a class in a different package than the lookup class
2326          */
2327         private ClassDefiner makeClassDefiner(byte[] bytes) {
2328             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2329             return new ClassDefiner(this, cf, STRONG_LOADER_LINK);
2330         }
2331 
2332         /**
2333          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2334          * from the given bytes.  The name must be in the same package as the lookup class.
2335          *
2336          * Caller should make a defensive copy of the arguments if needed
2337          * before calling this factory method.
2338          *
2339          * @param bytes   class bytes
2340          * @return ClassDefiner that defines a hidden class of the given bytes.
2341          *
2342          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2343          * {@bytes} denotes a class in a different package than the lookup class
2344          */
2345         ClassDefiner makeHiddenClassDefiner(byte[] bytes) {
2346             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2347             return makeHiddenClassDefiner(cf, Set.of(), false);
2348         }
2349 
2350         /**
2351          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2352          * from the given bytes and options.
2353          * The name must be in the same package as the lookup class.
2354          *
2355          * Caller should make a defensive copy of the arguments if needed
2356          * before calling this factory method.
2357          *
2358          * @param bytes   class bytes
2359          * @param options class options
2360          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2361          * @return ClassDefiner that defines a hidden class of the given bytes and options
2362          *
2363          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2364          * {@bytes} denotes a class in a different package than the lookup class
2365          */
2366         ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2367                                             Set<ClassOption> options,
2368                                             boolean accessVmAnnotations) {
2369             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2370             return makeHiddenClassDefiner(cf, options, accessVmAnnotations);
2371         }
2372 
2373         /**
2374          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2375          * from the given bytes and the given options.  No package name check on the given name.
2376          *
2377          * @param name    fully-qualified name that specifies the prefix of the hidden class
2378          * @param bytes   class bytes
2379          * @param options class options
2380          * @return ClassDefiner that defines a hidden class of the given bytes and options.
2381          */
2382         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options) {
2383             // skip name and access flags validation
2384             return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false);
2385         }
2386 
2387         /**
2388          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2389          * from the given class file and options.
2390          *
2391          * @param cf ClassFile
2392          * @param options class options
2393          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2394          */
2395         private ClassDefiner makeHiddenClassDefiner(ClassFile cf,
2396                                                     Set<ClassOption> options,
2397                                                     boolean accessVmAnnotations) {
2398             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2399             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2400                 // jdk.internal.vm.annotations are permitted for classes
2401                 // defined to boot loader and platform loader
2402                 flags |= ACCESS_VM_ANNOTATIONS;
2403             }
2404 
2405             return new ClassDefiner(this, cf, flags);
2406         }
2407 
2408         static class ClassDefiner {
2409             private final Lookup lookup;
2410             private final String name;
2411             private final byte[] bytes;
2412             private final int classFlags;
2413 
2414             private ClassDefiner(Lookup lookup, ClassFile cf, int flags) {
2415                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2416                 this.lookup = lookup;
2417                 this.bytes = cf.bytes;
2418                 this.name = cf.name;
2419                 this.classFlags = flags;
2420             }
2421 
2422             String className() {
2423                 return name;
2424             }
2425 
2426             Class<?> defineClass(boolean initialize) {
2427                 return defineClass(initialize, null);
2428             }
2429 
2430             Lookup defineClassAsLookup(boolean initialize) {
2431                 Class<?> c = defineClass(initialize, null);
2432                 return new Lookup(c, null, FULL_POWER_MODES);
2433             }
2434 
2435             /**
2436              * Defines the class of the given bytes and the given classData.
2437              * If {@code initialize} parameter is true, then the class will be initialized.
2438              *
2439              * @param initialize true if the class to be initialized
2440              * @param classData classData or null
2441              * @return the class
2442              *
2443              * @throws LinkageError linkage error
2444              */
2445             Class<?> defineClass(boolean initialize, Object classData) {
2446                 Class<?> lookupClass = lookup.lookupClass();
2447                 ClassLoader loader = lookupClass.getClassLoader();
2448                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2449                 Class<?> c = SharedSecrets.getJavaLangAccess()
2450                         .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2451                 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2452                 return c;
2453             }
2454 
2455             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2456                 Class<?> c = defineClass(initialize, classData);
2457                 return new Lookup(c, null, FULL_POWER_MODES);
2458             }
2459 
2460             private boolean isNestmate() {
2461                 return (classFlags & NESTMATE_CLASS) != 0;
2462             }
2463         }
2464 
2465         private ProtectionDomain lookupClassProtectionDomain() {
2466             ProtectionDomain pd = cachedProtectionDomain;
2467             if (pd == null) {
2468                 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2469             }
2470             return pd;
2471         }
2472 
2473         // cached protection domain
2474         private volatile ProtectionDomain cachedProtectionDomain;
2475 
2476         // Make sure outer class is initialized first.
2477         static { IMPL_NAMES.getClass(); }
2478 
2479         /** Package-private version of lookup which is trusted. */
2480         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2481 
2482         /** Version of lookup which is trusted minimally.
2483          *  It can only be used to create method handles to publicly accessible
2484          *  members in packages that are exported unconditionally.
2485          */
2486         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2487 
2488         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2489             String name = lookupClass.getName();
2490             if (name.startsWith("java.lang.invoke."))
2491                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2492         }
2493 
2494         /**
2495          * Displays the name of the class from which lookups are to be made,
2496          * followed by "/" and the name of the {@linkplain #previousLookupClass()
2497          * previous lookup class} if present.
2498          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2499          * If there are restrictions on the access permitted to this lookup,
2500          * this is indicated by adding a suffix to the class name, consisting
2501          * of a slash and a keyword.  The keyword represents the strongest
2502          * allowed access, and is chosen as follows:
2503          * <ul>
2504          * <li>If no access is allowed, the suffix is "/noaccess".
2505          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2506          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2507          * <li>If only public and module access are allowed, the suffix is "/module".
2508          * <li>If public and package access are allowed, the suffix is "/package".
2509          * <li>If public, package, and private access are allowed, the suffix is "/private".
2510          * </ul>
2511          * If none of the above cases apply, it is the case that
2512          * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2513          * (public, module, package, private, and protected) is allowed.
2514          * In this case, no suffix is added.
2515          * This is true only of an object obtained originally from
2516          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2517          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2518          * always have restricted access, and will display a suffix.
2519          * <p>
2520          * (It may seem strange that protected access should be
2521          * stronger than private access.  Viewed independently from
2522          * package access, protected access is the first to be lost,
2523          * because it requires a direct subclass relationship between
2524          * caller and callee.)
2525          * @see #in
2526          *
2527          * @revised 9
2528          */
2529         @Override
2530         public String toString() {
2531             String cname = lookupClass.getName();
2532             if (prevLookupClass != null)
2533                 cname += "/" + prevLookupClass.getName();
2534             switch (allowedModes) {
2535             case 0:  // no privileges
2536                 return cname + "/noaccess";
2537             case UNCONDITIONAL:
2538                 return cname + "/publicLookup";
2539             case PUBLIC:
2540                 return cname + "/public";
2541             case PUBLIC|MODULE:
2542                 return cname + "/module";
2543             case PUBLIC|PACKAGE:
2544             case PUBLIC|MODULE|PACKAGE:
2545                 return cname + "/package";
2546             case PUBLIC|PACKAGE|PRIVATE:
2547             case PUBLIC|MODULE|PACKAGE|PRIVATE:
2548                     return cname + "/private";
2549             case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2550             case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2551             case FULL_POWER_MODES:
2552                     return cname;
2553             case TRUSTED:
2554                 return "/trusted";  // internal only; not exported
2555             default:  // Should not happen, but it's a bitfield...
2556                 cname = cname + "/" + Integer.toHexString(allowedModes);
2557                 assert(false) : cname;
2558                 return cname;
2559             }
2560         }
2561 
2562         /**
2563          * Produces a method handle for a static method.
2564          * The type of the method handle will be that of the method.
2565          * (Since static methods do not take receivers, there is no
2566          * additional receiver argument inserted into the method handle type,
2567          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2568          * The method and all its argument types must be accessible to the lookup object.
2569          * <p>
2570          * The returned method handle will have
2571          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2572          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2573          * <p>
2574          * If the returned method handle is invoked, the method's class will
2575          * be initialized, if it has not already been initialized.
2576          * <p><b>Example:</b>
2577          * {@snippet lang="java" :
2578 import static java.lang.invoke.MethodHandles.*;
2579 import static java.lang.invoke.MethodType.*;
2580 ...
2581 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2582   "asList", methodType(List.class, Object[].class));
2583 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2584          * }
2585          * @param refc the class from which the method is accessed
2586          * @param name the name of the method
2587          * @param type the type of the method
2588          * @return the desired method handle
2589          * @throws NoSuchMethodException if the method does not exist
2590          * @throws IllegalAccessException if access checking fails,
2591          *                                or if the method is not {@code static},
2592          *                                or if the method's variable arity modifier bit
2593          *                                is set and {@code asVarargsCollector} fails
2594          * @throws    SecurityException if a security manager is present and it
2595          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2596          * @throws NullPointerException if any argument is null
2597          */
2598         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2599             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2600             // resolveOrFail could return a non-static <init> method if present
2601             // detect and throw NSME before producing a MethodHandle
2602             if (!method.isStatic() && name.equals("<init>")) {
2603                 throw new NoSuchMethodException("illegal method name: " + name);
2604             }
2605 
2606             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2607         }
2608 
2609         /**
2610          * Produces a method handle for a virtual method.
2611          * The type of the method handle will be that of the method,
2612          * with the receiver type (usually {@code refc}) prepended.
2613          * The method and all its argument types must be accessible to the lookup object.
2614          * <p>
2615          * When called, the handle will treat the first argument as a receiver
2616          * and, for non-private methods, dispatch on the receiver's type to determine which method
2617          * implementation to enter.
2618          * For private methods the named method in {@code refc} will be invoked on the receiver.
2619          * (The dispatching action is identical with that performed by an
2620          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2621          * <p>
2622          * The first argument will be of type {@code refc} if the lookup
2623          * class has full privileges to access the member.  Otherwise
2624          * the member must be {@code protected} and the first argument
2625          * will be restricted in type to the lookup class.
2626          * <p>
2627          * The returned method handle will have
2628          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2629          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2630          * <p>
2631          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2632          * instructions and method handles produced by {@code findVirtual},
2633          * if the class is {@code MethodHandle} and the name string is
2634          * {@code invokeExact} or {@code invoke}, the resulting
2635          * method handle is equivalent to one produced by
2636          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2637          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2638          * with the same {@code type} argument.
2639          * <p>
2640          * If the class is {@code VarHandle} and the name string corresponds to
2641          * the name of a signature-polymorphic access mode method, the resulting
2642          * method handle is equivalent to one produced by
2643          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2644          * the access mode corresponding to the name string and with the same
2645          * {@code type} arguments.
2646          * <p>
2647          * <b>Example:</b>
2648          * {@snippet lang="java" :
2649 import static java.lang.invoke.MethodHandles.*;
2650 import static java.lang.invoke.MethodType.*;
2651 ...
2652 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2653   "concat", methodType(String.class, String.class));
2654 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2655   "hashCode", methodType(int.class));
2656 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2657   "hashCode", methodType(int.class));
2658 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2659 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2660 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2661 // interface method:
2662 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2663   "subSequence", methodType(CharSequence.class, int.class, int.class));
2664 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2665 // constructor "internal method" must be accessed differently:
2666 MethodType MT_newString = methodType(void.class); //()V for new String()
2667 try { assertEquals("impossible", lookup()
2668         .findVirtual(String.class, "<init>", MT_newString));
2669  } catch (NoSuchMethodException ex) { } // OK
2670 MethodHandle MH_newString = publicLookup()
2671   .findConstructor(String.class, MT_newString);
2672 assertEquals("", (String) MH_newString.invokeExact());
2673          * }
2674          *
2675          * @param refc the class or interface from which the method is accessed
2676          * @param name the name of the method
2677          * @param type the type of the method, with the receiver argument omitted
2678          * @return the desired method handle
2679          * @throws NoSuchMethodException if the method does not exist
2680          * @throws IllegalAccessException if access checking fails,
2681          *                                or if the method is {@code static},
2682          *                                or if the method's variable arity modifier bit
2683          *                                is set and {@code asVarargsCollector} fails
2684          * @throws    SecurityException if a security manager is present and it
2685          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2686          * @throws NullPointerException if any argument is null
2687          */
2688         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2689             if (refc == MethodHandle.class) {
2690                 MethodHandle mh = findVirtualForMH(name, type);
2691                 if (mh != null)  return mh;
2692             } else if (refc == VarHandle.class) {
2693                 MethodHandle mh = findVirtualForVH(name, type);
2694                 if (mh != null)  return mh;
2695             }
2696             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2697             MemberName method = resolveOrFail(refKind, refc, name, type);
2698             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2699         }
2700         private MethodHandle findVirtualForMH(String name, MethodType type) {
2701             // these names require special lookups because of the implicit MethodType argument
2702             if ("invoke".equals(name))
2703                 return invoker(type);
2704             if ("invokeExact".equals(name))
2705                 return exactInvoker(type);
2706             assert(!MemberName.isMethodHandleInvokeName(name));
2707             return null;
2708         }
2709         private MethodHandle findVirtualForVH(String name, MethodType type) {
2710             try {
2711                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2712             } catch (IllegalArgumentException e) {
2713                 return null;
2714             }
2715         }
2716 
2717         /**
2718          * Produces a method handle which creates an object and initializes it, using
2719          * the constructor of the specified type.
2720          * The parameter types of the method handle will be those of the constructor,
2721          * while the return type will be a reference to the constructor's class.
2722          * The constructor and all its argument types must be accessible to the lookup object.
2723          * <p>
2724          * The requested type must have a return type of {@code void}.
2725          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2726          * <p>
2727          * The returned method handle will have
2728          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2729          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2730          * <p>
2731          * If the returned method handle is invoked, the constructor's class will
2732          * be initialized, if it has not already been initialized.
2733          * <p><b>Example:</b>
2734          * {@snippet lang="java" :
2735 import static java.lang.invoke.MethodHandles.*;
2736 import static java.lang.invoke.MethodType.*;
2737 ...
2738 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2739   ArrayList.class, methodType(void.class, Collection.class));
2740 Collection orig = Arrays.asList("x", "y");
2741 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2742 assert(orig != copy);
2743 assertEquals(orig, copy);
2744 // a variable-arity constructor:
2745 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2746   ProcessBuilder.class, methodType(void.class, String[].class));
2747 ProcessBuilder pb = (ProcessBuilder)
2748   MH_newProcessBuilder.invoke("x", "y", "z");
2749 assertEquals("[x, y, z]", pb.command().toString());
2750          * }
2751          *
2752          * @apiNote
2753          * This method does not find a static {@code <init>} factory method as it is invoked
2754          * via {@code invokestatic} bytecode as opposed to {@code invokespecial} for an
2755          * object constructor.  To look up static {@code <init>} factory method, use
2756          * the {@link #findStatic(Class, String, MethodType) findStatic} method.
2757          *
2758          * @param refc the class or interface from which the method is accessed
2759          * @param type the type of the method, with the receiver argument omitted, and a void return type
2760          * @return the desired method handle
2761          * @throws NoSuchMethodException if the constructor does not exist
2762          * @throws IllegalAccessException if access checking fails
2763          *                                or if the method's variable arity modifier bit
2764          *                                is set and {@code asVarargsCollector} fails
2765          * @throws    SecurityException if a security manager is present and it
2766          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2767          * @throws NullPointerException if any argument is null
2768          */
2769         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2770             if (refc.isArray()) {
2771                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2772             }
2773             if (type.returnType() != void.class) {
2774                 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName());
2775             }
2776             String name = "<init>";
2777             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2778             return getDirectConstructor(refc, ctor);
2779         }
2780 
2781         /**
2782          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2783          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2784          * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2785          * and then determines whether the class is accessible to this lookup object.
2786          * <p>
2787          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2788          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2789          *
2790          * @param targetName the fully qualified name of the class to be looked up.
2791          * @return the requested class.
2792          * @throws SecurityException if a security manager is present and it
2793          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2794          * @throws LinkageError if the linkage fails
2795          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2796          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2797          * modes.
2798          * @throws NullPointerException if {@code targetName} is null
2799          * @since 9
2800          * @jvms 5.4.3.1 Class and Interface Resolution
2801          */
2802         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2803             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2804             return accessClass(targetClass);
2805         }
2806 
2807         /**
2808          * Ensures that {@code targetClass} has been initialized. The class
2809          * to be initialized must be {@linkplain #accessClass accessible}
2810          * to this {@code Lookup} object.  This method causes {@code targetClass}
2811          * to be initialized if it has not been already initialized,
2812          * as specified in JVMS {@jvms 5.5}.
2813          *
2814          * <p>
2815          * This method returns when {@code targetClass} is fully initialized, or
2816          * when {@code targetClass} is being initialized by the current thread.
2817          *
2818          * @param targetClass the class to be initialized
2819          * @return {@code targetClass} that has been initialized, or that is being
2820          *         initialized by the current thread.
2821          *
2822          * @throws  IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2823          *          or array class
2824          * @throws  IllegalAccessException if {@code targetClass} is not
2825          *          {@linkplain #accessClass accessible} to this lookup
2826          * @throws  ExceptionInInitializerError if the class initialization provoked
2827          *          by this method fails
2828          * @throws  SecurityException if a security manager is present and it
2829          *          <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2830          * @since 15
2831          * @jvms 5.5 Initialization
2832          */
2833         public Class<?> ensureInitialized(Class<?> targetClass) throws IllegalAccessException {
2834             if (targetClass.isPrimitive())
2835                 throw new IllegalArgumentException(targetClass + " is a primitive class");
2836             if (targetClass.isArray())
2837                 throw new IllegalArgumentException(targetClass + " is an array class");
2838 
2839             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2840                 throw makeAccessException(targetClass);
2841             }
2842             checkSecurityManager(targetClass);
2843 
2844             // ensure class initialization
2845             Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2846             return targetClass;
2847         }
2848 
2849         /*
2850          * Returns IllegalAccessException due to access violation to the given targetClass.
2851          *
2852          * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2853          * which verifies access to a class rather a member.
2854          */
2855         private IllegalAccessException makeAccessException(Class<?> targetClass) {
2856             String message = "access violation: "+ targetClass;
2857             if (this == MethodHandles.publicLookup()) {
2858                 message += ", from public Lookup";
2859             } else {
2860                 Module m = lookupClass().getModule();
2861                 message += ", from " + lookupClass() + " (" + m + ")";
2862                 if (prevLookupClass != null) {
2863                     message += ", previous lookup " +
2864                             prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2865                 }
2866             }
2867             return new IllegalAccessException(message);
2868         }
2869 
2870         /**
2871          * Determines if a class can be accessed from the lookup context defined by
2872          * this {@code Lookup} object. The static initializer of the class is not run.
2873          * If {@code targetClass} is an array class, {@code targetClass} is accessible
2874          * if the element type of the array class is accessible.  Otherwise,
2875          * {@code targetClass} is determined as accessible as follows.
2876          *
2877          * <p>
2878          * If {@code targetClass} is in the same module as the lookup class,
2879          * the lookup class is {@code LC} in module {@code M1} and
2880          * the previous lookup class is in module {@code M0} or
2881          * {@code null} if not present,
2882          * {@code targetClass} is accessible if and only if one of the following is true:
2883          * <ul>
2884          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2885          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2886          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2887          *     in the same runtime package of {@code LC}.</li>
2888          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2889          *     a public type in {@code M1}.</li>
2890          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2891          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2892          *     if the previous lookup class is present; otherwise, {@code targetClass}
2893          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2894          * </ul>
2895          *
2896          * <p>
2897          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2898          * can access public types in all modules when the type is in a package
2899          * that is exported unconditionally.
2900          * <p>
2901          * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2902          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2903          * is inaccessible.
2904          * <p>
2905          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2906          * {@code M1} is the module containing {@code lookupClass} and
2907          * {@code M2} is the module containing {@code targetClass},
2908          * then {@code targetClass} is accessible if and only if
2909          * <ul>
2910          * <li>{@code M1} reads {@code M2}, and
2911          * <li>{@code targetClass} is public and in a package exported by
2912          *     {@code M2} at least to {@code M1}.
2913          * </ul>
2914          * <p>
2915          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2916          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2917          * containing the previous lookup class, then {@code targetClass} is accessible
2918          * if and only if one of the following is true:
2919          * <ul>
2920          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2921          *     {@linkplain Module#reads reads} {@code M0} and the type is
2922          *     in a package that is exported to at least {@code M1}.
2923          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2924          *     {@linkplain Module#reads reads} {@code M1} and the type is
2925          *     in a package that is exported to at least {@code M0}.
2926          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2927          *     and {@code M1} reads {@code M2} and the type is in a package
2928          *     that is exported to at least both {@code M0} and {@code M2}.
2929          * </ul>
2930          * <p>
2931          * Otherwise, {@code targetClass} is not accessible.
2932          *
2933          * @param targetClass the class to be access-checked
2934          * @return the class that has been access-checked
2935          * @throws IllegalAccessException if the class is not accessible from the lookup class
2936          * and previous lookup class, if present, using the allowed access modes.
2937          * @throws SecurityException if a security manager is present and it
2938          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2939          * @throws NullPointerException if {@code targetClass} is {@code null}
2940          * @since 9
2941          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
2942          */
2943         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
2944             if (!isClassAccessible(targetClass)) {
2945                 throw makeAccessException(targetClass);
2946             }
2947             checkSecurityManager(targetClass);
2948             return targetClass;
2949         }
2950 
2951         /**
2952          * Produces an early-bound method handle for a virtual method.
2953          * It will bypass checks for overriding methods on the receiver,
2954          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
2955          * instruction from within the explicitly specified {@code specialCaller}.
2956          * The type of the method handle will be that of the method,
2957          * with a suitably restricted receiver type prepended.
2958          * (The receiver type will be {@code specialCaller} or a subtype.)
2959          * The method and all its argument types must be accessible
2960          * to the lookup object.
2961          * <p>
2962          * Before method resolution,
2963          * if the explicitly specified caller class is not identical with the
2964          * lookup class, or if this lookup object does not have
2965          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
2966          * privileges, the access fails.
2967          * <p>
2968          * The returned method handle will have
2969          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2970          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2971          * <p style="font-size:smaller;">
2972          * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
2973          * even though the {@code invokespecial} instruction can refer to them
2974          * in special circumstances.  Use {@link #findConstructor findConstructor}
2975          * to access instance initialization methods in a safe manner.)</em>
2976          * <p><b>Example:</b>
2977          * {@snippet lang="java" :
2978 import static java.lang.invoke.MethodHandles.*;
2979 import static java.lang.invoke.MethodType.*;
2980 ...
2981 static class Listie extends ArrayList {
2982   public String toString() { return "[wee Listie]"; }
2983   static Lookup lookup() { return MethodHandles.lookup(); }
2984 }
2985 ...
2986 // no access to constructor via invokeSpecial:
2987 MethodHandle MH_newListie = Listie.lookup()
2988   .findConstructor(Listie.class, methodType(void.class));
2989 Listie l = (Listie) MH_newListie.invokeExact();
2990 try { assertEquals("impossible", Listie.lookup().findSpecial(
2991         Listie.class, "<init>", methodType(void.class), Listie.class));
2992  } catch (NoSuchMethodException ex) { } // OK
2993 // access to super and self methods via invokeSpecial:
2994 MethodHandle MH_super = Listie.lookup().findSpecial(
2995   ArrayList.class, "toString" , methodType(String.class), Listie.class);
2996 MethodHandle MH_this = Listie.lookup().findSpecial(
2997   Listie.class, "toString" , methodType(String.class), Listie.class);
2998 MethodHandle MH_duper = Listie.lookup().findSpecial(
2999   Object.class, "toString" , methodType(String.class), Listie.class);
3000 assertEquals("[]", (String) MH_super.invokeExact(l));
3001 assertEquals(""+l, (String) MH_this.invokeExact(l));
3002 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
3003 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
3004         String.class, "toString", methodType(String.class), Listie.class));
3005  } catch (IllegalAccessException ex) { } // OK
3006 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
3007 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
3008          * }
3009          *
3010          * @param refc the class or interface from which the method is accessed
3011          * @param name the name of the method (which must not be "&lt;init&gt;")
3012          * @param type the type of the method, with the receiver argument omitted
3013          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
3014          * @return the desired method handle
3015          * @throws NoSuchMethodException if the method does not exist
3016          * @throws IllegalAccessException if access checking fails,
3017          *                                or if the method is {@code static},
3018          *                                or if the method's variable arity modifier bit
3019          *                                is set and {@code asVarargsCollector} fails
3020          * @throws    SecurityException if a security manager is present and it
3021          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3022          * @throws NullPointerException if any argument is null
3023          */
3024         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
3025                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
3026             checkSpecialCaller(specialCaller, refc);
3027             Lookup specialLookup = this.in(specialCaller);
3028             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
3029             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
3030         }
3031 
3032         /**
3033          * Produces a method handle giving read access to a non-static field.
3034          * The type of the method handle will have a return type of the field's
3035          * value type.
3036          * The method handle's single argument will be the instance containing
3037          * the field.
3038          * Access checking is performed immediately on behalf of the lookup class.
3039          * @param refc the class or interface from which the method is accessed
3040          * @param name the field's name
3041          * @param type the field's type
3042          * @return a method handle which can load values from the field
3043          * @throws NoSuchFieldException if the field does not exist
3044          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3045          * @throws    SecurityException if a security manager is present and it
3046          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3047          * @throws NullPointerException if any argument is null
3048          * @see #findVarHandle(Class, String, Class)
3049          */
3050         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3051             MemberName field = resolveOrFail(REF_getField, refc, name, type);
3052             return getDirectField(REF_getField, refc, field);
3053         }
3054 
3055         /**
3056          * Produces a method handle giving write access to a non-static field.
3057          * The type of the method handle will have a void return type.
3058          * The method handle will take two arguments, the instance containing
3059          * the field, and the value to be stored.
3060          * The second argument will be of the field's value type.
3061          * Access checking is performed immediately on behalf of the lookup class.
3062          * @param refc the class or interface from which the method is accessed
3063          * @param name the field's name
3064          * @param type the field's type
3065          * @return a method handle which can store values into the field
3066          * @throws NoSuchFieldException if the field does not exist
3067          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3068          *                                or {@code final}
3069          * @throws    SecurityException if a security manager is present and it
3070          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3071          * @throws NullPointerException if any argument is null
3072          * @see #findVarHandle(Class, String, Class)
3073          */
3074         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3075             MemberName field = resolveOrFail(REF_putField, refc, name, type);
3076             return getDirectField(REF_putField, refc, field);
3077         }
3078 
3079         /**
3080          * Produces a VarHandle giving access to a non-static field {@code name}
3081          * of type {@code type} declared in a class of type {@code recv}.
3082          * The VarHandle's variable type is {@code type} and it has one
3083          * coordinate type, {@code recv}.
3084          * <p>
3085          * Access checking is performed immediately on behalf of the lookup
3086          * class.
3087          * <p>
3088          * Certain access modes of the returned VarHandle are unsupported under
3089          * the following conditions:
3090          * <ul>
3091          * <li>if the field is declared {@code final}, then the write, atomic
3092          *     update, numeric atomic update, and bitwise atomic update access
3093          *     modes are unsupported.
3094          * <li>if the field type is anything other than {@code byte},
3095          *     {@code short}, {@code char}, {@code int}, {@code long},
3096          *     {@code float}, or {@code double} then numeric atomic update
3097          *     access modes are unsupported.
3098          * <li>if the field type is anything other than {@code boolean},
3099          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3100          *     {@code long} then bitwise atomic update access modes are
3101          *     unsupported.
3102          * </ul>
3103          * <p>
3104          * If the field is declared {@code volatile} then the returned VarHandle
3105          * will override access to the field (effectively ignore the
3106          * {@code volatile} declaration) in accordance to its specified
3107          * access modes.
3108          * <p>
3109          * If the field type is {@code float} or {@code double} then numeric
3110          * and atomic update access modes compare values using their bitwise
3111          * representation (see {@link Float#floatToRawIntBits} and
3112          * {@link Double#doubleToRawLongBits}, respectively).
3113          * @apiNote
3114          * Bitwise comparison of {@code float} values or {@code double} values,
3115          * as performed by the numeric and atomic update access modes, differ
3116          * from the primitive {@code ==} operator and the {@link Float#equals}
3117          * and {@link Double#equals} methods, specifically with respect to
3118          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3119          * Care should be taken when performing a compare and set or a compare
3120          * and exchange operation with such values since the operation may
3121          * unexpectedly fail.
3122          * There are many possible NaN values that are considered to be
3123          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3124          * provided by Java can distinguish between them.  Operation failure can
3125          * occur if the expected or witness value is a NaN value and it is
3126          * transformed (perhaps in a platform specific manner) into another NaN
3127          * value, and thus has a different bitwise representation (see
3128          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3129          * details).
3130          * The values {@code -0.0} and {@code +0.0} have different bitwise
3131          * representations but are considered equal when using the primitive
3132          * {@code ==} operator.  Operation failure can occur if, for example, a
3133          * numeric algorithm computes an expected value to be say {@code -0.0}
3134          * and previously computed the witness value to be say {@code +0.0}.
3135          * @param recv the receiver class, of type {@code R}, that declares the
3136          * non-static field
3137          * @param name the field's name
3138          * @param type the field's type, of type {@code T}
3139          * @return a VarHandle giving access to non-static fields.
3140          * @throws NoSuchFieldException if the field does not exist
3141          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3142          * @throws    SecurityException if a security manager is present and it
3143          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3144          * @throws NullPointerException if any argument is null
3145          * @since 9
3146          */
3147         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3148             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3149             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3150             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3151         }
3152 
3153         /**
3154          * Produces a method handle giving read access to a static field.
3155          * The type of the method handle will have a return type of the field's
3156          * value type.
3157          * The method handle will take no arguments.
3158          * Access checking is performed immediately on behalf of the lookup class.
3159          * <p>
3160          * If the returned method handle is invoked, the field's class will
3161          * be initialized, if it has not already been initialized.
3162          * @param refc the class or interface from which the method is accessed
3163          * @param name the field's name
3164          * @param type the field's type
3165          * @return a method handle which can load values from the field
3166          * @throws NoSuchFieldException if the field does not exist
3167          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3168          * @throws    SecurityException if a security manager is present and it
3169          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3170          * @throws NullPointerException if any argument is null
3171          */
3172         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3173             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3174             return getDirectField(REF_getStatic, refc, field);
3175         }
3176 
3177         /**
3178          * Produces a method handle giving write access to a static field.
3179          * The type of the method handle will have a void return type.
3180          * The method handle will take a single
3181          * argument, of the field's value type, the value to be stored.
3182          * Access checking is performed immediately on behalf of the lookup class.
3183          * <p>
3184          * If the returned method handle is invoked, the field's class will
3185          * be initialized, if it has not already been initialized.
3186          * @param refc the class or interface from which the method is accessed
3187          * @param name the field's name
3188          * @param type the field's type
3189          * @return a method handle which can store values into the field
3190          * @throws NoSuchFieldException if the field does not exist
3191          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3192          *                                or is {@code final}
3193          * @throws    SecurityException if a security manager is present and it
3194          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3195          * @throws NullPointerException if any argument is null
3196          */
3197         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3198             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3199             return getDirectField(REF_putStatic, refc, field);
3200         }
3201 
3202         /**
3203          * Produces a VarHandle giving access to a static field {@code name} of
3204          * type {@code type} declared in a class of type {@code decl}.
3205          * The VarHandle's variable type is {@code type} and it has no
3206          * coordinate types.
3207          * <p>
3208          * Access checking is performed immediately on behalf of the lookup
3209          * class.
3210          * <p>
3211          * If the returned VarHandle is operated on, the declaring class will be
3212          * initialized, if it has not already been initialized.
3213          * <p>
3214          * Certain access modes of the returned VarHandle are unsupported under
3215          * the following conditions:
3216          * <ul>
3217          * <li>if the field is declared {@code final}, then the write, atomic
3218          *     update, numeric atomic update, and bitwise atomic update access
3219          *     modes are unsupported.
3220          * <li>if the field type is anything other than {@code byte},
3221          *     {@code short}, {@code char}, {@code int}, {@code long},
3222          *     {@code float}, or {@code double}, then numeric atomic update
3223          *     access modes are unsupported.
3224          * <li>if the field type is anything other than {@code boolean},
3225          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3226          *     {@code long} then bitwise atomic update access modes are
3227          *     unsupported.
3228          * </ul>
3229          * <p>
3230          * If the field is declared {@code volatile} then the returned VarHandle
3231          * will override access to the field (effectively ignore the
3232          * {@code volatile} declaration) in accordance to its specified
3233          * access modes.
3234          * <p>
3235          * If the field type is {@code float} or {@code double} then numeric
3236          * and atomic update access modes compare values using their bitwise
3237          * representation (see {@link Float#floatToRawIntBits} and
3238          * {@link Double#doubleToRawLongBits}, respectively).
3239          * @apiNote
3240          * Bitwise comparison of {@code float} values or {@code double} values,
3241          * as performed by the numeric and atomic update access modes, differ
3242          * from the primitive {@code ==} operator and the {@link Float#equals}
3243          * and {@link Double#equals} methods, specifically with respect to
3244          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3245          * Care should be taken when performing a compare and set or a compare
3246          * and exchange operation with such values since the operation may
3247          * unexpectedly fail.
3248          * There are many possible NaN values that are considered to be
3249          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3250          * provided by Java can distinguish between them.  Operation failure can
3251          * occur if the expected or witness value is a NaN value and it is
3252          * transformed (perhaps in a platform specific manner) into another NaN
3253          * value, and thus has a different bitwise representation (see
3254          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3255          * details).
3256          * The values {@code -0.0} and {@code +0.0} have different bitwise
3257          * representations but are considered equal when using the primitive
3258          * {@code ==} operator.  Operation failure can occur if, for example, a
3259          * numeric algorithm computes an expected value to be say {@code -0.0}
3260          * and previously computed the witness value to be say {@code +0.0}.
3261          * @param decl the class that declares the static field
3262          * @param name the field's name
3263          * @param type the field's type, of type {@code T}
3264          * @return a VarHandle giving access to a static field
3265          * @throws NoSuchFieldException if the field does not exist
3266          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3267          * @throws    SecurityException if a security manager is present and it
3268          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3269          * @throws NullPointerException if any argument is null
3270          * @since 9
3271          */
3272         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3273             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3274             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3275             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3276         }
3277 
3278         /**
3279          * Produces an early-bound method handle for a non-static method.
3280          * The receiver must have a supertype {@code defc} in which a method
3281          * of the given name and type is accessible to the lookup class.
3282          * The method and all its argument types must be accessible to the lookup object.
3283          * The type of the method handle will be that of the method,
3284          * without any insertion of an additional receiver parameter.
3285          * The given receiver will be bound into the method handle,
3286          * so that every call to the method handle will invoke the
3287          * requested method on the given receiver.
3288          * <p>
3289          * The returned method handle will have
3290          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3291          * the method's variable arity modifier bit ({@code 0x0080}) is set
3292          * <em>and</em> the trailing array argument is not the only argument.
3293          * (If the trailing array argument is the only argument,
3294          * the given receiver value will be bound to it.)
3295          * <p>
3296          * This is almost equivalent to the following code, with some differences noted below:
3297          * {@snippet lang="java" :
3298 import static java.lang.invoke.MethodHandles.*;
3299 import static java.lang.invoke.MethodType.*;
3300 ...
3301 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3302 MethodHandle mh1 = mh0.bindTo(receiver);
3303 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3304 return mh1;
3305          * }
3306          * where {@code defc} is either {@code receiver.getClass()} or a super
3307          * type of that class, in which the requested method is accessible
3308          * to the lookup class.
3309          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3310          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3311          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3312          * the receiver is restricted by {@code findVirtual} to the lookup class.)
3313          * @param receiver the object from which the method is accessed
3314          * @param name the name of the method
3315          * @param type the type of the method, with the receiver argument omitted
3316          * @return the desired method handle
3317          * @throws NoSuchMethodException if the method does not exist
3318          * @throws IllegalAccessException if access checking fails
3319          *                                or if the method's variable arity modifier bit
3320          *                                is set and {@code asVarargsCollector} fails
3321          * @throws    SecurityException if a security manager is present and it
3322          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3323          * @throws NullPointerException if any argument is null
3324          * @see MethodHandle#bindTo
3325          * @see #findVirtual
3326          */
3327         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3328             Class<? extends Object> refc = receiver.getClass(); // may get NPE
3329             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3330             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3331             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3332                 throw new IllegalAccessException("The restricted defining class " +
3333                                                  mh.type().leadingReferenceParameter().getName() +
3334                                                  " is not assignable from receiver class " +
3335                                                  receiver.getClass().getName());
3336             }
3337             return mh.bindArgumentL(0, receiver).setVarargs(method);
3338         }
3339 
3340         /**
3341          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3342          * to <i>m</i>, if the lookup class has permission.
3343          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3344          * If <i>m</i> is virtual, overriding is respected on every call.
3345          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3346          * The type of the method handle will be that of the method,
3347          * with the receiver type prepended (but only if it is non-static).
3348          * If the method's {@code accessible} flag is not set,
3349          * access checking is performed immediately on behalf of the lookup class.
3350          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3351          * <p>
3352          * The returned method handle will have
3353          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3354          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3355          * <p>
3356          * If <i>m</i> is static, and
3357          * if the returned method handle is invoked, the method's class will
3358          * be initialized, if it has not already been initialized.
3359          * @param m the reflected method
3360          * @return a method handle which can invoke the reflected method
3361          * @throws IllegalAccessException if access checking fails
3362          *                                or if the method's variable arity modifier bit
3363          *                                is set and {@code asVarargsCollector} fails
3364          * @throws NullPointerException if the argument is null
3365          */
3366         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3367             if (m.getDeclaringClass() == MethodHandle.class) {
3368                 MethodHandle mh = unreflectForMH(m);
3369                 if (mh != null)  return mh;
3370             }
3371             if (m.getDeclaringClass() == VarHandle.class) {
3372                 MethodHandle mh = unreflectForVH(m);
3373                 if (mh != null)  return mh;
3374             }
3375             MemberName method = new MemberName(m);
3376             byte refKind = method.getReferenceKind();
3377             if (refKind == REF_invokeSpecial)
3378                 refKind = REF_invokeVirtual;
3379             assert(method.isMethod());
3380             @SuppressWarnings("deprecation")
3381             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3382             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3383         }
3384         private MethodHandle unreflectForMH(Method m) {
3385             // these names require special lookups because they throw UnsupportedOperationException
3386             if (MemberName.isMethodHandleInvokeName(m.getName()))
3387                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3388             return null;
3389         }
3390         private MethodHandle unreflectForVH(Method m) {
3391             // these names require special lookups because they throw UnsupportedOperationException
3392             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3393                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3394             return null;
3395         }
3396 
3397         /**
3398          * Produces a method handle for a reflected method.
3399          * It will bypass checks for overriding methods on the receiver,
3400          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3401          * instruction from within the explicitly specified {@code specialCaller}.
3402          * The type of the method handle will be that of the method,
3403          * with a suitably restricted receiver type prepended.
3404          * (The receiver type will be {@code specialCaller} or a subtype.)
3405          * If the method's {@code accessible} flag is not set,
3406          * access checking is performed immediately on behalf of the lookup class,
3407          * as if {@code invokespecial} instruction were being linked.
3408          * <p>
3409          * Before method resolution,
3410          * if the explicitly specified caller class is not identical with the
3411          * lookup class, or if this lookup object does not have
3412          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3413          * privileges, the access fails.
3414          * <p>
3415          * The returned method handle will have
3416          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3417          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3418          * @param m the reflected method
3419          * @param specialCaller the class nominally calling the method
3420          * @return a method handle which can invoke the reflected method
3421          * @throws IllegalAccessException if access checking fails,
3422          *                                or if the method is {@code static},
3423          *                                or if the method's variable arity modifier bit
3424          *                                is set and {@code asVarargsCollector} fails
3425          * @throws NullPointerException if any argument is null
3426          */
3427         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3428             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3429             Lookup specialLookup = this.in(specialCaller);
3430             MemberName method = new MemberName(m, true);
3431             assert(method.isMethod());
3432             // ignore m.isAccessible:  this is a new kind of access
3433             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3434         }
3435 
3436         /**
3437          * Produces a method handle for a reflected constructor.
3438          * The type of the method handle will be that of the constructor,
3439          * with the return type changed to the declaring class.
3440          * The method handle will perform a {@code newInstance} operation,
3441          * creating a new instance of the constructor's class on the
3442          * arguments passed to the method handle.
3443          * <p>
3444          * If the constructor's {@code accessible} flag is not set,
3445          * access checking is performed immediately on behalf of the lookup class.
3446          * <p>
3447          * The returned method handle will have
3448          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3449          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3450          * <p>
3451          * If the returned method handle is invoked, the constructor's class will
3452          * be initialized, if it has not already been initialized.
3453          * @param c the reflected constructor
3454          * @return a method handle which can invoke the reflected constructor
3455          * @throws IllegalAccessException if access checking fails
3456          *                                or if the method's variable arity modifier bit
3457          *                                is set and {@code asVarargsCollector} fails
3458          * @throws NullPointerException if the argument is null
3459          */
3460         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3461             MemberName ctor = new MemberName(c);
3462             assert(ctor.isObjectConstructorOrStaticInitMethod());
3463             @SuppressWarnings("deprecation")
3464             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3465             Class<?> defc = c.getDeclaringClass();
3466             if (ctor.isObjectConstructor()) {
3467                 assert(ctor.getReturnType() == void.class);
3468                 return lookup.getDirectConstructorNoSecurityManager(defc, ctor);
3469             } else {
3470                 // static init factory is a static method
3471                 assert(ctor.isMethod() && ctor.getReturnType() == defc && ctor.getReferenceKind() == REF_invokeStatic) : ctor.toString();
3472                 assert(!MethodHandleNatives.isCallerSensitive(ctor));  // must not be caller-sensitive
3473                 return lookup.getDirectMethodNoSecurityManager(ctor.getReferenceKind(), defc, ctor, lookup);
3474             }
3475         }
3476 
3477         /**
3478          * Produces a method handle giving read access to a reflected field.
3479          * The type of the method handle will have a return type of the field's
3480          * value type.
3481          * If the field is {@code static}, the method handle will take no arguments.
3482          * Otherwise, its single argument will be the instance containing
3483          * the field.
3484          * If the {@code Field} object's {@code accessible} flag is not set,
3485          * access checking is performed immediately on behalf of the lookup class.
3486          * <p>
3487          * If the field is static, and
3488          * if the returned method handle is invoked, the field's class will
3489          * be initialized, if it has not already been initialized.
3490          * @param f the reflected field
3491          * @return a method handle which can load values from the reflected field
3492          * @throws IllegalAccessException if access checking fails
3493          * @throws NullPointerException if the argument is null
3494          */
3495         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3496             return unreflectField(f, false);
3497         }
3498 
3499         /**
3500          * Produces a method handle giving write access to a reflected field.
3501          * The type of the method handle will have a void return type.
3502          * If the field is {@code static}, the method handle will take a single
3503          * argument, of the field's value type, the value to be stored.
3504          * Otherwise, the two arguments will be the instance containing
3505          * the field, and the value to be stored.
3506          * If the {@code Field} object's {@code accessible} flag is not set,
3507          * access checking is performed immediately on behalf of the lookup class.
3508          * <p>
3509          * If the field is {@code final}, write access will not be
3510          * allowed and access checking will fail, except under certain
3511          * narrow circumstances documented for {@link Field#set Field.set}.
3512          * A method handle is returned only if a corresponding call to
3513          * the {@code Field} object's {@code set} method could return
3514          * normally.  In particular, fields which are both {@code static}
3515          * and {@code final} may never be set.
3516          * <p>
3517          * If the field is {@code static}, and
3518          * if the returned method handle is invoked, the field's class will
3519          * be initialized, if it has not already been initialized.
3520          * @param f the reflected field
3521          * @return a method handle which can store values into the reflected field
3522          * @throws IllegalAccessException if access checking fails,
3523          *         or if the field is {@code final} and write access
3524          *         is not enabled on the {@code Field} object
3525          * @throws NullPointerException if the argument is null
3526          */
3527         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3528             return unreflectField(f, true);
3529         }
3530 
3531         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3532             MemberName field = new MemberName(f, isSetter);
3533             if (isSetter && field.isFinal()) {
3534                 if (field.isTrustedFinalField()) {
3535                     String msg = field.isStatic() ? "static final field has no write access"
3536                                                   : "final field has no write access";
3537                     throw field.makeAccessException(msg, this);
3538                 }
3539             }
3540             assert(isSetter
3541                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3542                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3543             @SuppressWarnings("deprecation")
3544             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3545             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3546         }
3547 
3548         /**
3549          * Produces a VarHandle giving access to a reflected field {@code f}
3550          * of type {@code T} declared in a class of type {@code R}.
3551          * The VarHandle's variable type is {@code T}.
3552          * If the field is non-static the VarHandle has one coordinate type,
3553          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3554          * coordinate types.
3555          * <p>
3556          * Access checking is performed immediately on behalf of the lookup
3557          * class, regardless of the value of the field's {@code accessible}
3558          * flag.
3559          * <p>
3560          * If the field is static, and if the returned VarHandle is operated
3561          * on, the field's declaring class will be initialized, if it has not
3562          * already been initialized.
3563          * <p>
3564          * Certain access modes of the returned VarHandle are unsupported under
3565          * the following conditions:
3566          * <ul>
3567          * <li>if the field is declared {@code final}, then the write, atomic
3568          *     update, numeric atomic update, and bitwise atomic update access
3569          *     modes are unsupported.
3570          * <li>if the field type is anything other than {@code byte},
3571          *     {@code short}, {@code char}, {@code int}, {@code long},
3572          *     {@code float}, or {@code double} then numeric atomic update
3573          *     access modes are unsupported.
3574          * <li>if the field type is anything other than {@code boolean},
3575          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3576          *     {@code long} then bitwise atomic update access modes are
3577          *     unsupported.
3578          * </ul>
3579          * <p>
3580          * If the field is declared {@code volatile} then the returned VarHandle
3581          * will override access to the field (effectively ignore the
3582          * {@code volatile} declaration) in accordance to its specified
3583          * access modes.
3584          * <p>
3585          * If the field type is {@code float} or {@code double} then numeric
3586          * and atomic update access modes compare values using their bitwise
3587          * representation (see {@link Float#floatToRawIntBits} and
3588          * {@link Double#doubleToRawLongBits}, respectively).
3589          * @apiNote
3590          * Bitwise comparison of {@code float} values or {@code double} values,
3591          * as performed by the numeric and atomic update access modes, differ
3592          * from the primitive {@code ==} operator and the {@link Float#equals}
3593          * and {@link Double#equals} methods, specifically with respect to
3594          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3595          * Care should be taken when performing a compare and set or a compare
3596          * and exchange operation with such values since the operation may
3597          * unexpectedly fail.
3598          * There are many possible NaN values that are considered to be
3599          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3600          * provided by Java can distinguish between them.  Operation failure can
3601          * occur if the expected or witness value is a NaN value and it is
3602          * transformed (perhaps in a platform specific manner) into another NaN
3603          * value, and thus has a different bitwise representation (see
3604          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3605          * details).
3606          * The values {@code -0.0} and {@code +0.0} have different bitwise
3607          * representations but are considered equal when using the primitive
3608          * {@code ==} operator.  Operation failure can occur if, for example, a
3609          * numeric algorithm computes an expected value to be say {@code -0.0}
3610          * and previously computed the witness value to be say {@code +0.0}.
3611          * @param f the reflected field, with a field of type {@code T}, and
3612          * a declaring class of type {@code R}
3613          * @return a VarHandle giving access to non-static fields or a static
3614          * field
3615          * @throws IllegalAccessException if access checking fails
3616          * @throws NullPointerException if the argument is null
3617          * @since 9
3618          */
3619         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3620             MemberName getField = new MemberName(f, false);
3621             MemberName putField = new MemberName(f, true);
3622             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
3623                                                       f.getDeclaringClass(), getField, putField);
3624         }
3625 
3626         /**
3627          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3628          * created by this lookup object or a similar one.
3629          * Security and access checks are performed to ensure that this lookup object
3630          * is capable of reproducing the target method handle.
3631          * This means that the cracking may fail if target is a direct method handle
3632          * but was created by an unrelated lookup object.
3633          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3634          * and was created by a lookup object for a different class.
3635          * @param target a direct method handle to crack into symbolic reference components
3636          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3637          * @throws    SecurityException if a security manager is present and it
3638          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3639          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3640          * @throws    NullPointerException if the target is {@code null}
3641          * @see MethodHandleInfo
3642          * @since 1.8
3643          */
3644         public MethodHandleInfo revealDirect(MethodHandle target) {
3645             if (!target.isCrackable()) {
3646                 throw newIllegalArgumentException("not a direct method handle");
3647             }
3648             MemberName member = target.internalMemberName();
3649             Class<?> defc = member.getDeclaringClass();
3650             byte refKind = member.getReferenceKind();
3651             assert(MethodHandleNatives.refKindIsValid(refKind));
3652             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3653                 // Devirtualized method invocation is usually formally virtual.
3654                 // To avoid creating extra MemberName objects for this common case,
3655                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3656                 refKind = REF_invokeVirtual;
3657             if (refKind == REF_invokeVirtual && defc.isInterface())
3658                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3659                 refKind = REF_invokeInterface;
3660             // Check SM permissions and member access before cracking.
3661             try {
3662                 checkAccess(refKind, defc, member);
3663                 checkSecurityManager(defc, member);
3664             } catch (IllegalAccessException ex) {
3665                 throw new IllegalArgumentException(ex);
3666             }
3667             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3668                 Class<?> callerClass = target.internalCallerClass();
3669                 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3670                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3671             }
3672             // Produce the handle to the results.
3673             return new InfoFromMemberName(this, member, refKind);
3674         }
3675 
3676         /// Helper methods, all package-private.
3677 
3678         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3679             checkSymbolicClass(refc);  // do this before attempting to resolve
3680             Objects.requireNonNull(name);
3681             Objects.requireNonNull(type);
3682             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3683                                             NoSuchFieldException.class);
3684         }
3685 
3686         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3687             checkSymbolicClass(refc);  // do this before attempting to resolve
3688             Objects.requireNonNull(type);
3689             checkMethodName(refKind, name);  // implicit null-check of name
3690             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3691                                             NoSuchMethodException.class);
3692         }
3693 
3694         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3695             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3696             Objects.requireNonNull(member.getName());
3697             Objects.requireNonNull(member.getType());
3698             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3699                                             ReflectiveOperationException.class);
3700         }
3701 
3702         MemberName resolveOrNull(byte refKind, MemberName member) {
3703             // do this before attempting to resolve
3704             if (!isClassAccessible(member.getDeclaringClass())) {
3705                 return null;
3706             }
3707             Objects.requireNonNull(member.getName());
3708             Objects.requireNonNull(member.getType());
3709             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3710         }
3711 
3712         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3713             // do this before attempting to resolve
3714             if (!isClassAccessible(refc)) {
3715                 return null;
3716             }
3717             Objects.requireNonNull(type);
3718             // implicit null-check of name
3719             if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3720                 return null;
3721             }
3722             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3723         }
3724 
3725         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3726             if (!isClassAccessible(refc)) {
3727                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3728             }
3729         }
3730 
3731         boolean isClassAccessible(Class<?> refc) {
3732             Objects.requireNonNull(refc);
3733             Class<?> caller = lookupClassOrNull();
3734             Class<?> type = refc;
3735             while (type.isArray()) {
3736                 type = type.getComponentType();
3737             }
3738             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3739         }
3740 
3741         /** Check name for an illegal leading "&lt;" character. */
3742         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3743             // "<init>" can only be invoked via invokespecial or it's a static init factory
3744             if (name.startsWith("<") && refKind != REF_newInvokeSpecial &&
3745                     !(refKind == REF_invokeStatic && name.equals("<init>"))) {
3746                     throw new NoSuchMethodException("illegal method name: " + name);
3747             }
3748         }
3749 
3750         /**
3751          * Find my trustable caller class if m is a caller sensitive method.
3752          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3753          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3754          */
3755         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3756             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3757                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3758                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3759             }
3760             return this;
3761         }
3762 
3763         /**
3764          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3765          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3766          *
3767          * @deprecated This method was originally designed to test {@code PRIVATE} access
3768          * that implies full privilege access but {@code MODULE} access has since become
3769          * independent of {@code PRIVATE} access.  It is recommended to call
3770          * {@link #hasFullPrivilegeAccess()} instead.
3771          * @since 9
3772          */
3773         @Deprecated(since="14")
3774         public boolean hasPrivateAccess() {
3775             return hasFullPrivilegeAccess();
3776         }
3777 
3778         /**
3779          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3780          * i.e. {@code PRIVATE} and {@code MODULE} access.
3781          * A {@code Lookup} object must have full privilege access in order to
3782          * access all members that are allowed to the
3783          * {@linkplain #lookupClass() lookup class}.
3784          *
3785          * @return {@code true} if this lookup has full privilege access.
3786          * @since 14
3787          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3788          */
3789         public boolean hasFullPrivilegeAccess() {
3790             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3791         }
3792 
3793         /**
3794          * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a>
3795          * for ensureInitialzed, findClass or accessClass.
3796          */
3797         void checkSecurityManager(Class<?> refc) {
3798             if (allowedModes == TRUSTED)  return;
3799 
3800             @SuppressWarnings("removal")
3801             SecurityManager smgr = System.getSecurityManager();
3802             if (smgr == null)  return;
3803 
3804             // Step 1:
3805             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3806             if (!fullPrivilegeLookup ||
3807                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3808                 ReflectUtil.checkPackageAccess(refc);
3809             }
3810 
3811             // Step 2b:
3812             if (!fullPrivilegeLookup) {
3813                 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
3814             }
3815         }
3816 
3817         /**
3818          * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
3819          * Determines a trustable caller class to compare with refc, the symbolic reference class.
3820          * If this lookup object has full privilege access except original access,
3821          * then the caller class is the lookupClass.
3822          *
3823          * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)}
3824          * from the same module skips the security permission check.
3825          */
3826         void checkSecurityManager(Class<?> refc, MemberName m) {
3827             Objects.requireNonNull(refc);
3828             Objects.requireNonNull(m);
3829 
3830             if (allowedModes == TRUSTED)  return;
3831 
3832             @SuppressWarnings("removal")
3833             SecurityManager smgr = System.getSecurityManager();
3834             if (smgr == null)  return;
3835 
3836             // Step 1:
3837             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3838             if (!fullPrivilegeLookup ||
3839                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3840                 ReflectUtil.checkPackageAccess(refc);
3841             }
3842 
3843             // Step 2a:
3844             if (m.isPublic()) return;
3845             if (!fullPrivilegeLookup) {
3846                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3847             }
3848 
3849             // Step 3:
3850             Class<?> defc = m.getDeclaringClass();
3851             if (!fullPrivilegeLookup && PrimitiveClass.asPrimaryType(defc) != PrimitiveClass.asPrimaryType(refc)) {
3852                 ReflectUtil.checkPackageAccess(defc);
3853             }
3854         }
3855 
3856         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3857             boolean wantStatic = (refKind == REF_invokeStatic);
3858             String message;
3859             if (m.isObjectConstructor())
3860                 message = "expected a method, not a constructor";
3861             else if (!m.isMethod())
3862                 message = "expected a method";
3863             else if (wantStatic != m.isStatic())
3864                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3865             else
3866                 { checkAccess(refKind, refc, m); return; }
3867             throw m.makeAccessException(message, this);
3868         }
3869 
3870         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3871             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3872             String message;
3873             if (wantStatic != m.isStatic())
3874                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3875             else
3876                 { checkAccess(refKind, refc, m); return; }
3877             throw m.makeAccessException(message, this);
3878         }
3879 
3880         /** Check public/protected/private bits on the symbolic reference class and its member. */
3881         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3882             assert(m.referenceKindIsConsistentWith(refKind) &&
3883                    MethodHandleNatives.refKindIsValid(refKind) &&
3884                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3885             int allowedModes = this.allowedModes;
3886             if (allowedModes == TRUSTED)  return;
3887             int mods = m.getModifiers();
3888             if (Modifier.isProtected(mods) &&
3889                     refKind == REF_invokeVirtual &&
3890                     m.getDeclaringClass() == Object.class &&
3891                     m.getName().equals("clone") &&
3892                     refc.isArray()) {
3893                 // The JVM does this hack also.
3894                 // (See ClassVerifier::verify_invoke_instructions
3895                 // and LinkResolver::check_method_accessability.)
3896                 // Because the JVM does not allow separate methods on array types,
3897                 // there is no separate method for int[].clone.
3898                 // All arrays simply inherit Object.clone.
3899                 // But for access checking logic, we make Object.clone
3900                 // (normally protected) appear to be public.
3901                 // Later on, when the DirectMethodHandle is created,
3902                 // its leading argument will be restricted to the
3903                 // requested array type.
3904                 // N.B. The return type is not adjusted, because
3905                 // that is *not* the bytecode behavior.
3906                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3907             }
3908             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3909                 // cannot "new" a protected ctor in a different package
3910                 mods ^= Modifier.PROTECTED;
3911             }
3912             if (Modifier.isFinal(mods) &&
3913                     MethodHandleNatives.refKindIsSetter(refKind))
3914                 throw m.makeAccessException("unexpected set of a final field", this);
3915             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3916             if ((requestedModes & allowedModes) != 0) {
3917                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3918                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3919                     return;
3920             } else {
3921                 // Protected members can also be checked as if they were package-private.
3922                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
3923                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
3924                     return;
3925             }
3926             throw m.makeAccessException(accessFailedMessage(refc, m), this);
3927         }
3928 
3929         String accessFailedMessage(Class<?> refc, MemberName m) {
3930             Class<?> defc = m.getDeclaringClass();
3931             int mods = m.getModifiers();
3932             // check the class first:
3933             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
3934                                (PrimitiveClass.asPrimaryType(defc) == PrimitiveClass.asPrimaryType(refc) ||
3935                                 Modifier.isPublic(refc.getModifiers())));
3936             if (!classOK && (allowedModes & PACKAGE) != 0) {
3937                 // ignore previous lookup class to check if default package access
3938                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
3939                            (PrimitiveClass.asPrimaryType(defc) == PrimitiveClass.asPrimaryType(refc) ||
3940                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
3941             }
3942             if (!classOK)
3943                 return "class is not public";
3944             if (Modifier.isPublic(mods))
3945                 return "access to public member failed";  // (how?, module not readable?)
3946             if (Modifier.isPrivate(mods))
3947                 return "member is private";
3948             if (Modifier.isProtected(mods))
3949                 return "member is protected";
3950             return "member is private to package";
3951         }
3952 
3953         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
3954             int allowedModes = this.allowedModes;
3955             if (allowedModes == TRUSTED)  return;
3956             if ((lookupModes() & PRIVATE) == 0
3957                 || (specialCaller != lookupClass()
3958                        // ensure non-abstract methods in superinterfaces can be special-invoked
3959                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
3960                 throw new MemberName(specialCaller).
3961                     makeAccessException("no private access for invokespecial", this);
3962         }
3963 
3964         private boolean restrictProtectedReceiver(MemberName method) {
3965             // The accessing class only has the right to use a protected member
3966             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
3967             if (!method.isProtected() || method.isStatic()
3968                 || allowedModes == TRUSTED
3969                 || method.getDeclaringClass() == lookupClass()
3970                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
3971                 return false;
3972             return true;
3973         }
3974         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
3975             assert(!method.isStatic());
3976             // receiver type of mh is too wide; narrow to caller
3977             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
3978                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
3979             }
3980             MethodType rawType = mh.type();
3981             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
3982             MethodType narrowType = rawType.changeParameterType(0, caller);
3983             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
3984             assert(mh.viewAsTypeChecks(narrowType, true));
3985             return mh.copyWith(narrowType, mh.form);
3986         }
3987 
3988         /** Check access and get the requested method. */
3989         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3990             final boolean doRestrict    = true;
3991             final boolean checkSecurity = true;
3992             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3993         }
3994         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
3995         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3996             final boolean doRestrict    = false;
3997             final boolean checkSecurity = true;
3998             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
3999         }
4000         /** Check access and get the requested method, eliding security manager checks. */
4001         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4002             final boolean doRestrict    = true;
4003             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4004             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4005         }
4006         /** Common code for all methods; do not call directly except from immediately above. */
4007         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
4008                                                    boolean checkSecurity,
4009                                                    boolean doRestrict,
4010                                                    Lookup boundCaller) throws IllegalAccessException {
4011             checkMethod(refKind, refc, method);
4012             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4013             if (checkSecurity)
4014                 checkSecurityManager(refc, method);
4015             assert(!method.isMethodHandleInvoke());
4016             if (refKind == REF_invokeSpecial &&
4017                 refc != lookupClass() &&
4018                 !refc.isInterface() &&
4019                 refc != lookupClass().getSuperclass() &&
4020                 refc.isAssignableFrom(lookupClass())) {
4021                 assert(!method.getName().equals("<init>"));  // not this code path
4022 
4023                 // Per JVMS 6.5, desc. of invokespecial instruction:
4024                 // If the method is in a superclass of the LC,
4025                 // and if our original search was above LC.super,
4026                 // repeat the search (symbolic lookup) from LC.super
4027                 // and continue with the direct superclass of that class,
4028                 // and so forth, until a match is found or no further superclasses exist.
4029                 // FIXME: MemberName.resolve should handle this instead.
4030                 Class<?> refcAsSuper = lookupClass();
4031                 MemberName m2;
4032                 do {
4033                     refcAsSuper = refcAsSuper.getSuperclass();
4034                     m2 = new MemberName(refcAsSuper,
4035                                         method.getName(),
4036                                         method.getMethodType(),
4037                                         REF_invokeSpecial);
4038                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
4039                 } while (m2 == null &&         // no method is found yet
4040                          refc != refcAsSuper); // search up to refc
4041                 if (m2 == null)  throw new InternalError(method.toString());
4042                 method = m2;
4043                 refc = refcAsSuper;
4044                 // redo basic checks
4045                 checkMethod(refKind, refc, method);
4046             }
4047             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
4048             MethodHandle mh = dmh;
4049             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
4050             if ((doRestrict && refKind == REF_invokeSpecial) ||
4051                     (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method))) {
4052                 mh = restrictReceiver(method, dmh, lookupClass());
4053             }
4054             mh = maybeBindCaller(method, mh, boundCaller);
4055             mh = mh.setVarargs(method);
4056             return mh;
4057         }
4058         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
4059                                              throws IllegalAccessException {
4060             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
4061                 return mh;
4062 
4063             // boundCaller must have full privilege access.
4064             // It should have been checked by findBoundCallerLookup. Safe to check this again.
4065             if ((boundCaller.lookupModes() & ORIGINAL) == 0)
4066                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
4067 
4068             assert boundCaller.hasFullPrivilegeAccess();
4069 
4070             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
4071             // Note: caller will apply varargs after this step happens.
4072             return cbmh;
4073         }
4074 
4075         /** Check access and get the requested field. */
4076         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4077             final boolean checkSecurity = true;
4078             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4079         }
4080         /** Check access and get the requested field, eliding security manager checks. */
4081         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4082             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4083             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4084         }
4085         /** Common code for all fields; do not call directly except from immediately above. */
4086         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
4087                                                   boolean checkSecurity) throws IllegalAccessException {
4088             checkField(refKind, refc, field);
4089             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4090             if (checkSecurity)
4091                 checkSecurityManager(refc, field);
4092             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
4093             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
4094                                     restrictProtectedReceiver(field));
4095             if (doRestrict)
4096                 return restrictReceiver(field, dmh, lookupClass());
4097             return dmh;
4098         }
4099         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
4100                                             Class<?> refc, MemberName getField, MemberName putField)
4101                 throws IllegalAccessException {
4102             final boolean checkSecurity = true;
4103             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4104         }
4105         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
4106                                                              Class<?> refc, MemberName getField, MemberName putField)
4107                 throws IllegalAccessException {
4108             final boolean checkSecurity = false;
4109             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4110         }
4111         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
4112                                                   Class<?> refc, MemberName getField, MemberName putField,
4113                                                   boolean checkSecurity) throws IllegalAccessException {
4114             assert getField.isStatic() == putField.isStatic();
4115             assert getField.isGetter() && putField.isSetter();
4116             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
4117             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
4118 
4119             checkField(getRefKind, refc, getField);
4120             if (checkSecurity)
4121                 checkSecurityManager(refc, getField);
4122 
4123             if (!putField.isFinal()) {
4124                 // A VarHandle does not support updates to final fields, any
4125                 // such VarHandle to a final field will be read-only and
4126                 // therefore the following write-based accessibility checks are
4127                 // only required for non-final fields
4128                 checkField(putRefKind, refc, putField);
4129                 if (checkSecurity)
4130                     checkSecurityManager(refc, putField);
4131             }
4132 
4133             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
4134                                   restrictProtectedReceiver(getField));
4135             if (doRestrict) {
4136                 assert !getField.isStatic();
4137                 // receiver type of VarHandle is too wide; narrow to caller
4138                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
4139                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4140                 }
4141                 refc = lookupClass();
4142             }
4143             return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(),
4144                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4145         }
4146         /** Check access and get the requested constructor. */
4147         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4148             final boolean checkSecurity = true;
4149             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4150         }
4151         /** Check access and get the requested constructor, eliding security manager checks. */
4152         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4153             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4154             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4155         }
4156         /** Common code for all constructors; do not call directly except from immediately above. */
4157         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4158                                                   boolean checkSecurity) throws IllegalAccessException {
4159             assert(ctor.isObjectConstructor());
4160             checkAccess(REF_newInvokeSpecial, refc, ctor);
4161             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4162             if (checkSecurity)
4163                 checkSecurityManager(refc, ctor);
4164             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4165             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4166         }
4167 
4168         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4169          */
4170         /*non-public*/
4171         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4172                 throws ReflectiveOperationException {
4173             if (!(type instanceof Class || type instanceof MethodType))
4174                 throw new InternalError("unresolved MemberName");
4175             MemberName member = new MemberName(refKind, defc, name, type);
4176             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4177             if (mh != null) {
4178                 checkSymbolicClass(defc);
4179                 return mh;
4180             }
4181             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
4182                 // Treat MethodHandle.invoke and invokeExact specially.
4183                 mh = findVirtualForMH(member.getName(), member.getMethodType());
4184                 if (mh != null) {
4185                     return mh;
4186                 }
4187             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4188                 // Treat signature-polymorphic methods on VarHandle specially.
4189                 mh = findVirtualForVH(member.getName(), member.getMethodType());
4190                 if (mh != null) {
4191                     return mh;
4192                 }
4193             }
4194             MemberName resolved = resolveOrFail(refKind, member);
4195             mh = getDirectMethodForConstant(refKind, defc, resolved);
4196             if (mh instanceof DirectMethodHandle
4197                     && canBeCached(refKind, defc, resolved)) {
4198                 MemberName key = mh.internalMemberName();
4199                 if (key != null) {
4200                     key = key.asNormalOriginal();
4201                 }
4202                 if (member.equals(key)) {  // better safe than sorry
4203                     LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
4204                 }
4205             }
4206             return mh;
4207         }
4208         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4209             if (refKind == REF_invokeSpecial) {
4210                 return false;
4211             }
4212             if (!Modifier.isPublic(defc.getModifiers()) ||
4213                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4214                     !member.isPublic() ||
4215                     member.isCallerSensitive()) {
4216                 return false;
4217             }
4218             ClassLoader loader = defc.getClassLoader();
4219             if (loader != null) {
4220                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4221                 boolean found = false;
4222                 while (sysl != null) {
4223                     if (loader == sysl) { found = true; break; }
4224                     sysl = sysl.getParent();
4225                 }
4226                 if (!found) {
4227                     return false;
4228                 }
4229             }
4230             try {
4231                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4232                     new MemberName(refKind, defc, member.getName(), member.getType()));
4233                 if (resolved2 == null) {
4234                     return false;
4235                 }
4236                 checkSecurityManager(defc, resolved2);
4237             } catch (SecurityException ex) {
4238                 return false;
4239             }
4240             return true;
4241         }
4242         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4243                 throws ReflectiveOperationException {
4244             if (MethodHandleNatives.refKindIsField(refKind)) {
4245                 return getDirectFieldNoSecurityManager(refKind, defc, member);
4246             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4247                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
4248             } else if (refKind == REF_newInvokeSpecial) {
4249                 return getDirectConstructorNoSecurityManager(defc, member);
4250             }
4251             // oops
4252             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4253         }
4254 
4255         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4256     }
4257 
4258     /**
4259      * Produces a method handle constructing arrays of a desired type,
4260      * as if by the {@code anewarray} bytecode.
4261      * The return type of the method handle will be the array type.
4262      * The type of its sole argument will be {@code int}, which specifies the size of the array.
4263      *
4264      * <p> If the returned method handle is invoked with a negative
4265      * array size, a {@code NegativeArraySizeException} will be thrown.
4266      *
4267      * @param arrayClass an array type
4268      * @return a method handle which can create arrays of the given type
4269      * @throws NullPointerException if the argument is {@code null}
4270      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4271      * @see java.lang.reflect.Array#newInstance(Class, int)
4272      * @jvms 6.5 {@code anewarray} Instruction
4273      * @since 9
4274      */
4275     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4276         if (!arrayClass.isArray()) {
4277             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4278         }
4279         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4280                 bindTo(arrayClass.getComponentType());
4281         return ani.asType(ani.type().changeReturnType(arrayClass));
4282     }
4283 
4284     /**
4285      * Produces a method handle returning the length of an array,
4286      * as if by the {@code arraylength} bytecode.
4287      * The type of the method handle will have {@code int} as return type,
4288      * and its sole argument will be the array type.
4289      *
4290      * <p> If the returned method handle is invoked with a {@code null}
4291      * array reference, a {@code NullPointerException} will be thrown.
4292      *
4293      * @param arrayClass an array type
4294      * @return a method handle which can retrieve the length of an array of the given array type
4295      * @throws NullPointerException if the argument is {@code null}
4296      * @throws IllegalArgumentException if arrayClass is not an array type
4297      * @jvms 6.5 {@code arraylength} Instruction
4298      * @since 9
4299      */
4300     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4301         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4302     }
4303 
4304     /**
4305      * Produces a method handle giving read access to elements of an array,
4306      * as if by the {@code aaload} bytecode.
4307      * The type of the method handle will have a return type of the array's
4308      * element type.  Its first argument will be the array type,
4309      * and the second will be {@code int}.
4310      *
4311      * <p> When the returned method handle is invoked,
4312      * the array reference and array index are checked.
4313      * A {@code NullPointerException} will be thrown if the array reference
4314      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4315      * thrown if the index is negative or if it is greater than or equal to
4316      * the length of the array.
4317      *
4318      * @param arrayClass an array type
4319      * @return a method handle which can load values from the given array type
4320      * @throws NullPointerException if the argument is null
4321      * @throws  IllegalArgumentException if arrayClass is not an array type
4322      * @jvms 6.5 {@code aaload} Instruction
4323      */
4324     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4325         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4326     }
4327 
4328     /**
4329      * Produces a method handle giving write access to elements of an array,
4330      * as if by the {@code astore} bytecode.
4331      * The type of the method handle will have a void return type.
4332      * Its last argument will be the array's element type.
4333      * The first and second arguments will be the array type and int.
4334      *
4335      * <p> When the returned method handle is invoked,
4336      * the array reference and array index are checked.
4337      * A {@code NullPointerException} will be thrown if the array reference
4338      * is {@code null} or if the array's element type is a {@link Class#isPrimitiveValueType()
4339      * a primitive value type} and attempts to set {@code null} in the
4340      * array element.  An {@code ArrayIndexOutOfBoundsException} will be
4341      * thrown if the index is negative or if it is greater than or equal to
4342      * the length of the array.
4343      *
4344      * @param arrayClass the class of an array
4345      * @return a method handle which can store values into the array type
4346      * @throws NullPointerException if the argument is null
4347      * @throws IllegalArgumentException if arrayClass is not an array type
4348      * @jvms 6.5 {@code aastore} Instruction
4349      */
4350     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4351         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4352     }
4353 
4354     /**
4355      * Produces a VarHandle giving access to elements of an array of type
4356      * {@code arrayClass}.  The VarHandle's variable type is the component type
4357      * of {@code arrayClass} and the list of coordinate types is
4358      * {@code (arrayClass, int)}, where the {@code int} coordinate type
4359      * corresponds to an argument that is an index into an array.
4360      * <p>
4361      * Certain access modes of the returned VarHandle are unsupported under
4362      * the following conditions:
4363      * <ul>
4364      * <li>if the component type is anything other than {@code byte},
4365      *     {@code short}, {@code char}, {@code int}, {@code long},
4366      *     {@code float}, or {@code double} then numeric atomic update access
4367      *     modes are unsupported.
4368      * <li>if the component type is anything other than {@code boolean},
4369      *     {@code byte}, {@code short}, {@code char}, {@code int} or
4370      *     {@code long} then bitwise atomic update access modes are
4371      *     unsupported.
4372      * </ul>
4373      * <p>
4374      * If the component type is {@code float} or {@code double} then numeric
4375      * and atomic update access modes compare values using their bitwise
4376      * representation (see {@link Float#floatToRawIntBits} and
4377      * {@link Double#doubleToRawLongBits}, respectively).
4378      *
4379      * <p> When the returned {@code VarHandle} is invoked,
4380      * the array reference and array index are checked.
4381      * A {@code NullPointerException} will be thrown if the array reference
4382      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4383      * thrown if the index is negative or if it is greater than or equal to
4384      * the length of the array.
4385      *
4386      * @apiNote
4387      * Bitwise comparison of {@code float} values or {@code double} values,
4388      * as performed by the numeric and atomic update access modes, differ
4389      * from the primitive {@code ==} operator and the {@link Float#equals}
4390      * and {@link Double#equals} methods, specifically with respect to
4391      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4392      * Care should be taken when performing a compare and set or a compare
4393      * and exchange operation with such values since the operation may
4394      * unexpectedly fail.
4395      * There are many possible NaN values that are considered to be
4396      * {@code NaN} in Java, although no IEEE 754 floating-point operation
4397      * provided by Java can distinguish between them.  Operation failure can
4398      * occur if the expected or witness value is a NaN value and it is
4399      * transformed (perhaps in a platform specific manner) into another NaN
4400      * value, and thus has a different bitwise representation (see
4401      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4402      * details).
4403      * The values {@code -0.0} and {@code +0.0} have different bitwise
4404      * representations but are considered equal when using the primitive
4405      * {@code ==} operator.  Operation failure can occur if, for example, a
4406      * numeric algorithm computes an expected value to be say {@code -0.0}
4407      * and previously computed the witness value to be say {@code +0.0}.
4408      * @param arrayClass the class of an array, of type {@code T[]}
4409      * @return a VarHandle giving access to elements of an array
4410      * @throws NullPointerException if the arrayClass is null
4411      * @throws IllegalArgumentException if arrayClass is not an array type
4412      * @since 9
4413      */
4414     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4415         return VarHandles.makeArrayElementHandle(arrayClass);
4416     }
4417 
4418     /**
4419      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4420      * viewed as if it were a different primitive array type, such as
4421      * {@code int[]} or {@code long[]}.
4422      * The VarHandle's variable type is the component type of
4423      * {@code viewArrayClass} and the list of coordinate types is
4424      * {@code (byte[], int)}, where the {@code int} coordinate type
4425      * corresponds to an argument that is an index into a {@code byte[]} array.
4426      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4427      * array, composing bytes to or from a value of the component type of
4428      * {@code viewArrayClass} according to the given endianness.
4429      * <p>
4430      * The supported component types (variables types) are {@code short},
4431      * {@code char}, {@code int}, {@code long}, {@code float} and
4432      * {@code double}.
4433      * <p>
4434      * Access of bytes at a given index will result in an
4435      * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4436      * or greater than the {@code byte[]} array length minus the size (in bytes)
4437      * of {@code T}.
4438      * <p>
4439      * Access of bytes at an index may be aligned or misaligned for {@code T},
4440      * with respect to the underlying memory address, {@code A} say, associated
4441      * with the array and index.
4442      * If access is misaligned then access for anything other than the
4443      * {@code get} and {@code set} access modes will result in an
4444      * {@code IllegalStateException}.  In such cases atomic access is only
4445      * guaranteed with respect to the largest power of two that divides the GCD
4446      * of {@code A} and the size (in bytes) of {@code T}.
4447      * If access is aligned then following access modes are supported and are
4448      * guaranteed to support atomic access:
4449      * <ul>
4450      * <li>read write access modes for all {@code T}, with the exception of
4451      *     access modes {@code get} and {@code set} for {@code long} and
4452      *     {@code double} on 32-bit platforms.
4453      * <li>atomic update access modes for {@code int}, {@code long},
4454      *     {@code float} or {@code double}.
4455      *     (Future major platform releases of the JDK may support additional
4456      *     types for certain currently unsupported access modes.)
4457      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4458      *     (Future major platform releases of the JDK may support additional
4459      *     numeric types for certain currently unsupported access modes.)
4460      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4461      *     (Future major platform releases of the JDK may support additional
4462      *     numeric types for certain currently unsupported access modes.)
4463      * </ul>
4464      * <p>
4465      * Misaligned access, and therefore atomicity guarantees, may be determined
4466      * for {@code byte[]} arrays without operating on a specific array.  Given
4467      * an {@code index}, {@code T} and its corresponding boxed type,
4468      * {@code T_BOX}, misalignment may be determined as follows:
4469      * <pre>{@code
4470      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4471      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
4472      *     alignmentOffset(0, sizeOfT);
4473      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
4474      * boolean isMisaligned = misalignedAtIndex != 0;
4475      * }</pre>
4476      * <p>
4477      * If the variable type is {@code float} or {@code double} then atomic
4478      * update access modes compare values using their bitwise representation
4479      * (see {@link Float#floatToRawIntBits} and
4480      * {@link Double#doubleToRawLongBits}, respectively).
4481      * @param viewArrayClass the view array class, with a component type of
4482      * type {@code T}
4483      * @param byteOrder the endianness of the view array elements, as
4484      * stored in the underlying {@code byte} array
4485      * @return a VarHandle giving access to elements of a {@code byte[]} array
4486      * viewed as if elements corresponding to the components type of the view
4487      * array class
4488      * @throws NullPointerException if viewArrayClass or byteOrder is null
4489      * @throws IllegalArgumentException if viewArrayClass is not an array type
4490      * @throws UnsupportedOperationException if the component type of
4491      * viewArrayClass is not supported as a variable type
4492      * @since 9
4493      */
4494     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4495                                      ByteOrder byteOrder) throws IllegalArgumentException {
4496         Objects.requireNonNull(byteOrder);
4497         return VarHandles.byteArrayViewHandle(viewArrayClass,
4498                                               byteOrder == ByteOrder.BIG_ENDIAN);
4499     }
4500 
4501     /**
4502      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4503      * viewed as if it were an array of elements of a different primitive
4504      * component type to that of {@code byte}, such as {@code int[]} or
4505      * {@code long[]}.
4506      * The VarHandle's variable type is the component type of
4507      * {@code viewArrayClass} and the list of coordinate types is
4508      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4509      * corresponds to an argument that is an index into a {@code byte[]} array.
4510      * The returned VarHandle accesses bytes at an index in a
4511      * {@code ByteBuffer}, composing bytes to or from a value of the component
4512      * type of {@code viewArrayClass} according to the given endianness.
4513      * <p>
4514      * The supported component types (variables types) are {@code short},
4515      * {@code char}, {@code int}, {@code long}, {@code float} and
4516      * {@code double}.
4517      * <p>
4518      * Access will result in a {@code ReadOnlyBufferException} for anything
4519      * other than the read access modes if the {@code ByteBuffer} is read-only.
4520      * <p>
4521      * Access of bytes at a given index will result in an
4522      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4523      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4524      * {@code T}.
4525      * <p>
4526      * Access of bytes at an index may be aligned or misaligned for {@code T},
4527      * with respect to the underlying memory address, {@code A} say, associated
4528      * with the {@code ByteBuffer} and index.
4529      * If access is misaligned then access for anything other than the
4530      * {@code get} and {@code set} access modes will result in an
4531      * {@code IllegalStateException}.  In such cases atomic access is only
4532      * guaranteed with respect to the largest power of two that divides the GCD
4533      * of {@code A} and the size (in bytes) of {@code T}.
4534      * If access is aligned then following access modes are supported and are
4535      * guaranteed to support atomic access:
4536      * <ul>
4537      * <li>read write access modes for all {@code T}, with the exception of
4538      *     access modes {@code get} and {@code set} for {@code long} and
4539      *     {@code double} on 32-bit platforms.
4540      * <li>atomic update access modes for {@code int}, {@code long},
4541      *     {@code float} or {@code double}.
4542      *     (Future major platform releases of the JDK may support additional
4543      *     types for certain currently unsupported access modes.)
4544      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4545      *     (Future major platform releases of the JDK may support additional
4546      *     numeric types for certain currently unsupported access modes.)
4547      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4548      *     (Future major platform releases of the JDK may support additional
4549      *     numeric types for certain currently unsupported access modes.)
4550      * </ul>
4551      * <p>
4552      * Misaligned access, and therefore atomicity guarantees, may be determined
4553      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4554      * {@code index}, {@code T} and its corresponding boxed type,
4555      * {@code T_BOX}, as follows:
4556      * <pre>{@code
4557      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4558      * ByteBuffer bb = ...
4559      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4560      * boolean isMisaligned = misalignedAtIndex != 0;
4561      * }</pre>
4562      * <p>
4563      * If the variable type is {@code float} or {@code double} then atomic
4564      * update access modes compare values using their bitwise representation
4565      * (see {@link Float#floatToRawIntBits} and
4566      * {@link Double#doubleToRawLongBits}, respectively).
4567      * @param viewArrayClass the view array class, with a component type of
4568      * type {@code T}
4569      * @param byteOrder the endianness of the view array elements, as
4570      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4571      * endianness of a {@code ByteBuffer})
4572      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4573      * viewed as if elements corresponding to the components type of the view
4574      * array class
4575      * @throws NullPointerException if viewArrayClass or byteOrder is null
4576      * @throws IllegalArgumentException if viewArrayClass is not an array type
4577      * @throws UnsupportedOperationException if the component type of
4578      * viewArrayClass is not supported as a variable type
4579      * @since 9
4580      */
4581     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4582                                       ByteOrder byteOrder) throws IllegalArgumentException {
4583         Objects.requireNonNull(byteOrder);
4584         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4585                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4586     }
4587 
4588 
4589     /// method handle invocation (reflective style)
4590 
4591     /**
4592      * Produces a method handle which will invoke any method handle of the
4593      * given {@code type}, with a given number of trailing arguments replaced by
4594      * a single trailing {@code Object[]} array.
4595      * The resulting invoker will be a method handle with the following
4596      * arguments:
4597      * <ul>
4598      * <li>a single {@code MethodHandle} target
4599      * <li>zero or more leading values (counted by {@code leadingArgCount})
4600      * <li>an {@code Object[]} array containing trailing arguments
4601      * </ul>
4602      * <p>
4603      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4604      * the indicated {@code type}.
4605      * That is, if the target is exactly of the given {@code type}, it will behave
4606      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4607      * is used to convert the target to the required {@code type}.
4608      * <p>
4609      * The type of the returned invoker will not be the given {@code type}, but rather
4610      * will have all parameters except the first {@code leadingArgCount}
4611      * replaced by a single array of type {@code Object[]}, which will be
4612      * the final parameter.
4613      * <p>
4614      * Before invoking its target, the invoker will spread the final array, apply
4615      * reference casts as necessary, and unbox and widen primitive arguments.
4616      * If, when the invoker is called, the supplied array argument does
4617      * not have the correct number of elements, the invoker will throw
4618      * an {@link IllegalArgumentException} instead of invoking the target.
4619      * <p>
4620      * This method is equivalent to the following code (though it may be more efficient):
4621      * {@snippet lang="java" :
4622 MethodHandle invoker = MethodHandles.invoker(type);
4623 int spreadArgCount = type.parameterCount() - leadingArgCount;
4624 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4625 return invoker;
4626      * }
4627      * This method throws no reflective or security exceptions.
4628      * @param type the desired target type
4629      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4630      * @return a method handle suitable for invoking any method handle of the given type
4631      * @throws NullPointerException if {@code type} is null
4632      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4633      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4634      *                  or if the resulting method handle's type would have
4635      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4636      */
4637     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4638         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4639             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4640         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4641         return type.invokers().spreadInvoker(leadingArgCount);
4642     }
4643 
4644     /**
4645      * Produces a special <em>invoker method handle</em> which can be used to
4646      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4647      * The resulting invoker will have a type which is
4648      * exactly equal to the desired type, except that it will accept
4649      * an additional leading argument of type {@code MethodHandle}.
4650      * <p>
4651      * This method is equivalent to the following code (though it may be more efficient):
4652      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4653      *
4654      * <p style="font-size:smaller;">
4655      * <em>Discussion:</em>
4656      * Invoker method handles can be useful when working with variable method handles
4657      * of unknown types.
4658      * For example, to emulate an {@code invokeExact} call to a variable method
4659      * handle {@code M}, extract its type {@code T},
4660      * look up the invoker method {@code X} for {@code T},
4661      * and call the invoker method, as {@code X.invoke(T, A...)}.
4662      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4663      * is unknown.)
4664      * If spreading, collecting, or other argument transformations are required,
4665      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4666      * method handle values, as long as they are compatible with the type of {@code X}.
4667      * <p style="font-size:smaller;">
4668      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4669      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4670      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4671      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4672      * <p>
4673      * This method throws no reflective or security exceptions.
4674      * @param type the desired target type
4675      * @return a method handle suitable for invoking any method handle of the given type
4676      * @throws IllegalArgumentException if the resulting method handle's type would have
4677      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4678      */
4679     public static MethodHandle exactInvoker(MethodType type) {
4680         return type.invokers().exactInvoker();
4681     }
4682 
4683     /**
4684      * Produces a special <em>invoker method handle</em> which can be used to
4685      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4686      * The resulting invoker will have a type which is
4687      * exactly equal to the desired type, except that it will accept
4688      * an additional leading argument of type {@code MethodHandle}.
4689      * <p>
4690      * Before invoking its target, if the target differs from the expected type,
4691      * the invoker will apply reference casts as
4692      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4693      * Similarly, the return value will be converted as necessary.
4694      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4695      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4696      * <p>
4697      * This method is equivalent to the following code (though it may be more efficient):
4698      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4699      * <p style="font-size:smaller;">
4700      * <em>Discussion:</em>
4701      * A {@linkplain MethodType#genericMethodType general method type} is one which
4702      * mentions only {@code Object} arguments and return values.
4703      * An invoker for such a type is capable of calling any method handle
4704      * of the same arity as the general type.
4705      * <p style="font-size:smaller;">
4706      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4707      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4708      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4709      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4710      * <p>
4711      * This method throws no reflective or security exceptions.
4712      * @param type the desired target type
4713      * @return a method handle suitable for invoking any method handle convertible to the given type
4714      * @throws IllegalArgumentException if the resulting method handle's type would have
4715      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4716      */
4717     public static MethodHandle invoker(MethodType type) {
4718         return type.invokers().genericInvoker();
4719     }
4720 
4721     /**
4722      * Produces a special <em>invoker method handle</em> which can be used to
4723      * invoke a signature-polymorphic access mode method on any VarHandle whose
4724      * associated access mode type is compatible with the given type.
4725      * The resulting invoker will have a type which is exactly equal to the
4726      * desired given type, except that it will accept an additional leading
4727      * argument of type {@code VarHandle}.
4728      *
4729      * @param accessMode the VarHandle access mode
4730      * @param type the desired target type
4731      * @return a method handle suitable for invoking an access mode method of
4732      *         any VarHandle whose access mode type is of the given type.
4733      * @since 9
4734      */
4735     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4736         return type.invokers().varHandleMethodExactInvoker(accessMode);
4737     }
4738 
4739     /**
4740      * Produces a special <em>invoker method handle</em> which can be used to
4741      * invoke a signature-polymorphic access mode method on any VarHandle whose
4742      * associated access mode type is compatible with the given type.
4743      * The resulting invoker will have a type which is exactly equal to the
4744      * desired given type, except that it will accept an additional leading
4745      * argument of type {@code VarHandle}.
4746      * <p>
4747      * Before invoking its target, if the access mode type differs from the
4748      * desired given type, the invoker will apply reference casts as necessary
4749      * and box, unbox, or widen primitive values, as if by
4750      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4751      * converted as necessary.
4752      * <p>
4753      * This method is equivalent to the following code (though it may be more
4754      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4755      *
4756      * @param accessMode the VarHandle access mode
4757      * @param type the desired target type
4758      * @return a method handle suitable for invoking an access mode method of
4759      *         any VarHandle whose access mode type is convertible to the given
4760      *         type.
4761      * @since 9
4762      */
4763     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4764         return type.invokers().varHandleMethodInvoker(accessMode);
4765     }
4766 
4767     /*non-public*/
4768     static MethodHandle basicInvoker(MethodType type) {
4769         return type.invokers().basicInvoker();
4770     }
4771 
4772      /// method handle modification (creation from other method handles)
4773 
4774     /**
4775      * Produces a method handle which adapts the type of the
4776      * given method handle to a new type by pairwise argument and return type conversion.
4777      * The original type and new type must have the same number of arguments.
4778      * The resulting method handle is guaranteed to report a type
4779      * which is equal to the desired new type.
4780      * <p>
4781      * If the original type and new type are equal, returns target.
4782      * <p>
4783      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4784      * and some additional conversions are also applied if those conversions fail.
4785      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4786      * if possible, before or instead of any conversions done by {@code asType}:
4787      * <ul>
4788      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4789      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4790      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4791      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4792      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4793      *     (This treatment follows the usage of the bytecode verifier.)
4794      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4795      *     <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}),
4796      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4797      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4798      *     then a Java casting conversion (JLS {@jls 5.5}) is applied.
4799      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4800      *     widening and/or narrowing.)
4801      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4802      *     conversion will be applied at runtime, possibly followed
4803      *     by a Java casting conversion (JLS {@jls 5.5}) on the primitive value,
4804      *     possibly followed by a conversion from byte to boolean by testing
4805      *     the low-order bit.
4806      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4807      *     and if the reference is null at runtime, a zero value is introduced.
4808      * </ul>
4809      * @param target the method handle to invoke after arguments are retyped
4810      * @param newType the expected type of the new method handle
4811      * @return a method handle which delegates to the target after performing
4812      *           any necessary argument conversions, and arranges for any
4813      *           necessary return value conversions
4814      * @throws NullPointerException if either argument is null
4815      * @throws WrongMethodTypeException if the conversion cannot be made
4816      * @see MethodHandle#asType
4817      */
4818     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4819         explicitCastArgumentsChecks(target, newType);
4820         // use the asTypeCache when possible:
4821         MethodType oldType = target.type();
4822         if (oldType == newType)  return target;
4823         if (oldType.explicitCastEquivalentToAsType(newType)) {
4824             return target.asFixedArity().asType(newType);
4825         }
4826         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4827     }
4828 
4829     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4830         if (target.type().parameterCount() != newType.parameterCount()) {
4831             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4832         }
4833     }
4834 
4835     /**
4836      * Produces a method handle which adapts the calling sequence of the
4837      * given method handle to a new type, by reordering the arguments.
4838      * The resulting method handle is guaranteed to report a type
4839      * which is equal to the desired new type.
4840      * <p>
4841      * The given array controls the reordering.
4842      * Call {@code #I} the number of incoming parameters (the value
4843      * {@code newType.parameterCount()}, and call {@code #O} the number
4844      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4845      * Then the length of the reordering array must be {@code #O},
4846      * and each element must be a non-negative number less than {@code #I}.
4847      * For every {@code N} less than {@code #O}, the {@code N}-th
4848      * outgoing argument will be taken from the {@code I}-th incoming
4849      * argument, where {@code I} is {@code reorder[N]}.
4850      * <p>
4851      * No argument or return value conversions are applied.
4852      * The type of each incoming argument, as determined by {@code newType},
4853      * must be identical to the type of the corresponding outgoing parameter
4854      * or parameters in the target method handle.
4855      * The return type of {@code newType} must be identical to the return
4856      * type of the original target.
4857      * <p>
4858      * The reordering array need not specify an actual permutation.
4859      * An incoming argument will be duplicated if its index appears
4860      * more than once in the array, and an incoming argument will be dropped
4861      * if its index does not appear in the array.
4862      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4863      * incoming arguments which are not mentioned in the reordering array
4864      * may be of any type, as determined only by {@code newType}.
4865      * {@snippet lang="java" :
4866 import static java.lang.invoke.MethodHandles.*;
4867 import static java.lang.invoke.MethodType.*;
4868 ...
4869 MethodType intfn1 = methodType(int.class, int.class);
4870 MethodType intfn2 = methodType(int.class, int.class, int.class);
4871 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4872 assert(sub.type().equals(intfn2));
4873 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4874 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4875 assert((int)rsub.invokeExact(1, 100) == 99);
4876 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4877 assert(add.type().equals(intfn2));
4878 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4879 assert(twice.type().equals(intfn1));
4880 assert((int)twice.invokeExact(21) == 42);
4881      * }
4882      * <p>
4883      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4884      * variable-arity method handle}, even if the original target method handle was.
4885      * @param target the method handle to invoke after arguments are reordered
4886      * @param newType the expected type of the new method handle
4887      * @param reorder an index array which controls the reordering
4888      * @return a method handle which delegates to the target after it
4889      *           drops unused arguments and moves and/or duplicates the other arguments
4890      * @throws NullPointerException if any argument is null
4891      * @throws IllegalArgumentException if the index array length is not equal to
4892      *                  the arity of the target, or if any index array element
4893      *                  not a valid index for a parameter of {@code newType},
4894      *                  or if two corresponding parameter types in
4895      *                  {@code target.type()} and {@code newType} are not identical,
4896      */
4897     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4898         reorder = reorder.clone();  // get a private copy
4899         MethodType oldType = target.type();
4900         permuteArgumentChecks(reorder, newType, oldType);
4901         // first detect dropped arguments and handle them separately
4902         int[] originalReorder = reorder;
4903         BoundMethodHandle result = target.rebind();
4904         LambdaForm form = result.form;
4905         int newArity = newType.parameterCount();
4906         // Normalize the reordering into a real permutation,
4907         // by removing duplicates and adding dropped elements.
4908         // This somewhat improves lambda form caching, as well
4909         // as simplifying the transform by breaking it up into steps.
4910         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4911             if (ddIdx > 0) {
4912                 // We found a duplicated entry at reorder[ddIdx].
4913                 // Example:  (x,y,z)->asList(x,y,z)
4914                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4915                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4916                 // The starred element corresponds to the argument
4917                 // deleted by the dupArgumentForm transform.
4918                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
4919                 boolean killFirst = false;
4920                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
4921                     // Set killFirst if the dup is larger than an intervening position.
4922                     // This will remove at least one inversion from the permutation.
4923                     if (dupVal > val) killFirst = true;
4924                 }
4925                 if (!killFirst) {
4926                     srcPos = dstPos;
4927                     dstPos = ddIdx;
4928                 }
4929                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
4930                 assert (reorder[srcPos] == reorder[dstPos]);
4931                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
4932                 // contract the reordering by removing the element at dstPos
4933                 int tailPos = dstPos + 1;
4934                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
4935                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
4936             } else {
4937                 int dropVal = ~ddIdx, insPos = 0;
4938                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
4939                     // Find first element of reorder larger than dropVal.
4940                     // This is where we will insert the dropVal.
4941                     insPos += 1;
4942                 }
4943                 Class<?> ptype = newType.parameterType(dropVal);
4944                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
4945                 oldType = oldType.insertParameterTypes(insPos, ptype);
4946                 // expand the reordering by inserting an element at insPos
4947                 int tailPos = insPos + 1;
4948                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
4949                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
4950                 reorder[insPos] = dropVal;
4951             }
4952             assert (permuteArgumentChecks(reorder, newType, oldType));
4953         }
4954         assert (reorder.length == newArity);  // a perfect permutation
4955         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
4956         form = form.editor().permuteArgumentsForm(1, reorder);
4957         if (newType == result.type() && form == result.internalForm())
4958             return result;
4959         return result.copyWith(newType, form);
4960     }
4961 
4962     /**
4963      * Return an indication of any duplicate or omission in reorder.
4964      * If the reorder contains a duplicate entry, return the index of the second occurrence.
4965      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
4966      * Otherwise, return zero.
4967      * If an element not in [0..newArity-1] is encountered, return reorder.length.
4968      */
4969     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
4970         final int BIT_LIMIT = 63;  // max number of bits in bit mask
4971         if (newArity < BIT_LIMIT) {
4972             long mask = 0;
4973             for (int i = 0; i < reorder.length; i++) {
4974                 int arg = reorder[i];
4975                 if (arg >= newArity) {
4976                     return reorder.length;
4977                 }
4978                 long bit = 1L << arg;
4979                 if ((mask & bit) != 0) {
4980                     return i;  // >0 indicates a dup
4981                 }
4982                 mask |= bit;
4983             }
4984             if (mask == (1L << newArity) - 1) {
4985                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
4986                 return 0;
4987             }
4988             // find first zero
4989             long zeroBit = Long.lowestOneBit(~mask);
4990             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
4991             assert(zeroPos <= newArity);
4992             if (zeroPos == newArity) {
4993                 return 0;
4994             }
4995             return ~zeroPos;
4996         } else {
4997             // same algorithm, different bit set
4998             BitSet mask = new BitSet(newArity);
4999             for (int i = 0; i < reorder.length; i++) {
5000                 int arg = reorder[i];
5001                 if (arg >= newArity) {
5002                     return reorder.length;
5003                 }
5004                 if (mask.get(arg)) {
5005                     return i;  // >0 indicates a dup
5006                 }
5007                 mask.set(arg);
5008             }
5009             int zeroPos = mask.nextClearBit(0);
5010             assert(zeroPos <= newArity);
5011             if (zeroPos == newArity) {
5012                 return 0;
5013             }
5014             return ~zeroPos;
5015         }
5016     }
5017 
5018     static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
5019         if (newType.returnType() != oldType.returnType())
5020             throw newIllegalArgumentException("return types do not match",
5021                     oldType, newType);
5022         if (reorder.length != oldType.parameterCount())
5023             throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
5024                     oldType, Arrays.toString(reorder));
5025 
5026         int limit = newType.parameterCount();
5027         for (int j = 0; j < reorder.length; j++) {
5028             int i = reorder[j];
5029             if (i < 0 || i >= limit) {
5030                 throw newIllegalArgumentException("index is out of bounds for new type",
5031                         i, newType);
5032             }
5033             Class<?> src = newType.parameterType(i);
5034             Class<?> dst = oldType.parameterType(j);
5035             if (src != dst)
5036                 throw newIllegalArgumentException("parameter types do not match after reorder",
5037                         oldType, newType);
5038         }
5039         return true;
5040     }
5041 
5042     /**
5043      * Produces a method handle of the requested return type which returns the given
5044      * constant value every time it is invoked.
5045      * <p>
5046      * Before the method handle is returned, the passed-in value is converted to the requested type.
5047      * If the requested type is primitive, widening primitive conversions are attempted,
5048      * else reference conversions are attempted.
5049      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5050      * @param type the return type of the desired method handle
5051      * @param value the value to return
5052      * @return a method handle of the given return type and no arguments, which always returns the given value
5053      * @throws NullPointerException if the given {@code type} is null, or
5054      *         if the given {@code type} is primitive or a primitive value type
5055      *         and the given value is null
5056      * @throws ClassCastException if the value cannot be converted to the required return type
5057      * @throws IllegalArgumentException if the given type is {@code void.class}
5058      */
5059     public static MethodHandle constant(Class<?> type, Object value) {
5060         if (type.isPrimitive()) {
5061             if (type == void.class)
5062                 throw newIllegalArgumentException("void type");
5063             Wrapper w = Wrapper.forPrimitiveType(type);
5064             value = w.convert(value, type);
5065             if (w.zero().equals(value))
5066                 return zero(w, type);
5067             return insertArguments(identity(type), 0, value);
5068         } else {
5069             if (!PrimitiveClass.isPrimitiveValueType(type) && value == null)
5070                 return zero(Wrapper.OBJECT, type);
5071             return identity(type).bindTo(value);
5072         }
5073     }
5074 
5075     /**
5076      * Produces a method handle which returns its sole argument when invoked.
5077      * @param type the type of the sole parameter and return value of the desired method handle
5078      * @return a unary method handle which accepts and returns the given type
5079      * @throws NullPointerException if the argument is null
5080      * @throws IllegalArgumentException if the given type is {@code void.class}
5081      */
5082     public static MethodHandle identity(Class<?> type) {
5083         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5084         int pos = btw.ordinal();
5085         MethodHandle ident = IDENTITY_MHS[pos];
5086         if (ident == null) {
5087             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5088         }
5089         if (ident.type().returnType() == type)
5090             return ident;
5091         // something like identity(Foo.class); do not bother to intern these
5092         assert (btw == Wrapper.OBJECT);
5093         return makeIdentity(type);
5094     }
5095 
5096     /**
5097      * Produces a constant method handle of the requested return type which
5098      * returns the default value for that type every time it is invoked.
5099      * The resulting constant method handle will have no side effects.
5100      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5101      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5102      * since {@code explicitCastArguments} converts {@code null} to default values.
5103      * @param type the expected return type of the desired method handle
5104      * @return a constant method handle that takes no arguments
5105      *         and returns the default value of the given type (or void, if the type is void)
5106      * @throws NullPointerException if the argument is null
5107      * @see MethodHandles#constant
5108      * @see MethodHandles#empty
5109      * @see MethodHandles#explicitCastArguments
5110      * @since 9
5111      */
5112     public static MethodHandle zero(Class<?> type) {
5113         Objects.requireNonNull(type);
5114         if (type.isPrimitive()) {
5115             return zero(Wrapper.forPrimitiveType(type), type);
5116         } else if (PrimitiveClass.isPrimitiveValueType(type)) {
5117             // singleton default value
5118             Object value = UNSAFE.uninitializedDefaultValue(type);
5119             return identity(type).bindTo(value);
5120         } else {
5121             return zero(Wrapper.OBJECT, type);
5122         }
5123     }
5124 
5125     private static MethodHandle identityOrVoid(Class<?> type) {
5126         return type == void.class ? zero(type) : identity(type);
5127     }
5128 
5129     /**
5130      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5131      * and returns a suitable default depending on the return type.
5132      * If the requested type is a primitive type or {@code void}, it returns
5133      * a zero primitive value or {@code void}.
5134      * If the requested type is a {@linkplain Class#isPrimitiveValueType() primitive value type},
5135      * it returns a primitive object with the default value.
5136      * If the requested type is a reference type, it returns {@code null}.
5137      * <p>The returned method handle is equivalent to
5138      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5139      *
5140      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5141      * {@code guardWithTest(pred, target, empty(target.type())}.
5142      * @param type the type of the desired method handle
5143      * @return a constant method handle of the given type, which returns a default value of the given return type
5144      * @throws NullPointerException if the argument is null
5145      * @see MethodHandles#zero
5146      * @see MethodHandles#constant
5147      * @since 9
5148      */
5149     public static  MethodHandle empty(MethodType type) {
5150         Objects.requireNonNull(type);
5151         return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes());
5152     }
5153 
5154     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5155     private static MethodHandle makeIdentity(Class<?> ptype) {
5156         MethodType mtype = MethodType.methodType(ptype, ptype);
5157         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5158         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5159     }
5160 
5161     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5162         int pos = btw.ordinal();
5163         MethodHandle zero = ZERO_MHS[pos];
5164         if (zero == null) {
5165             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5166         }
5167         if (zero.type().returnType() == rtype)
5168             return zero;
5169         assert(btw == Wrapper.OBJECT);
5170         return makeZero(rtype);
5171     }
5172     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5173     private static MethodHandle makeZero(Class<?> rtype) {
5174         MethodType mtype = methodType(rtype);
5175         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5176         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
5177     }
5178 
5179     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
5180         // Simulate a CAS, to avoid racy duplication of results.
5181         MethodHandle prev = cache[pos];
5182         if (prev != null) return prev;
5183         return cache[pos] = value;
5184     }
5185 
5186     /**
5187      * Provides a target method handle with one or more <em>bound arguments</em>
5188      * in advance of the method handle's invocation.
5189      * The formal parameters to the target corresponding to the bound
5190      * arguments are called <em>bound parameters</em>.
5191      * Returns a new method handle which saves away the bound arguments.
5192      * When it is invoked, it receives arguments for any non-bound parameters,
5193      * binds the saved arguments to their corresponding parameters,
5194      * and calls the original target.
5195      * <p>
5196      * The type of the new method handle will drop the types for the bound
5197      * parameters from the original target type, since the new method handle
5198      * will no longer require those arguments to be supplied by its callers.
5199      * <p>
5200      * Each given argument object must match the corresponding bound parameter type.
5201      * If a bound parameter type is a primitive, the argument object
5202      * must be a wrapper, and will be unboxed to produce the primitive value.
5203      * <p>
5204      * The {@code pos} argument selects which parameters are to be bound.
5205      * It may range between zero and <i>N-L</i> (inclusively),
5206      * where <i>N</i> is the arity of the target method handle
5207      * and <i>L</i> is the length of the values array.
5208      * <p>
5209      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5210      * variable-arity method handle}, even if the original target method handle was.
5211      * @param target the method handle to invoke after the argument is inserted
5212      * @param pos where to insert the argument (zero for the first)
5213      * @param values the series of arguments to insert
5214      * @return a method handle which inserts an additional argument,
5215      *         before calling the original method handle
5216      * @throws NullPointerException if the target or the {@code values} array is null
5217      * @throws IllegalArgumentException if (@code pos) is less than {@code 0} or greater than
5218      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
5219      *         is the length of the values array.
5220      * @throws ClassCastException if an argument does not match the corresponding bound parameter
5221      *         type.
5222      * @see MethodHandle#bindTo
5223      */
5224     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
5225         int insCount = values.length;
5226         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
5227         if (insCount == 0)  return target;
5228         BoundMethodHandle result = target.rebind();
5229         for (int i = 0; i < insCount; i++) {
5230             Object value = values[i];
5231             Class<?> ptype = ptypes[pos+i];
5232             if (ptype.isPrimitive()) {
5233                 result = insertArgumentPrimitive(result, pos, ptype, value);
5234             } else {
5235                 value = ptype.cast(value);  // throw CCE if needed
5236                 result = result.bindArgumentL(pos, value);
5237             }
5238         }
5239         return result;
5240     }
5241 
5242     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5243                                                              Class<?> ptype, Object value) {
5244         Wrapper w = Wrapper.forPrimitiveType(ptype);
5245         // perform unboxing and/or primitive conversion
5246         value = w.convert(value, ptype);
5247         return switch (w) {
5248             case INT    -> result.bindArgumentI(pos, (int) value);
5249             case LONG   -> result.bindArgumentJ(pos, (long) value);
5250             case FLOAT  -> result.bindArgumentF(pos, (float) value);
5251             case DOUBLE -> result.bindArgumentD(pos, (double) value);
5252             default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5253         };
5254     }
5255 
5256     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5257         MethodType oldType = target.type();
5258         int outargs = oldType.parameterCount();
5259         int inargs  = outargs - insCount;
5260         if (inargs < 0)
5261             throw newIllegalArgumentException("too many values to insert");
5262         if (pos < 0 || pos > inargs)
5263             throw newIllegalArgumentException("no argument type to append");
5264         return oldType.ptypes();
5265     }
5266 
5267     /**
5268      * Produces a method handle which will discard some dummy arguments
5269      * before calling some other specified <i>target</i> method handle.
5270      * The type of the new method handle will be the same as the target's type,
5271      * except it will also include the dummy argument types,
5272      * at some given position.
5273      * <p>
5274      * The {@code pos} argument may range between zero and <i>N</i>,
5275      * where <i>N</i> is the arity of the target.
5276      * If {@code pos} is zero, the dummy arguments will precede
5277      * the target's real arguments; if {@code pos} is <i>N</i>
5278      * they will come after.
5279      * <p>
5280      * <b>Example:</b>
5281      * {@snippet lang="java" :
5282 import static java.lang.invoke.MethodHandles.*;
5283 import static java.lang.invoke.MethodType.*;
5284 ...
5285 MethodHandle cat = lookup().findVirtual(String.class,
5286   "concat", methodType(String.class, String.class));
5287 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5288 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5289 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5290 assertEquals(bigType, d0.type());
5291 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5292      * }
5293      * <p>
5294      * This method is also equivalent to the following code:
5295      * <blockquote><pre>
5296      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5297      * </pre></blockquote>
5298      * @param target the method handle to invoke after the arguments are dropped
5299      * @param pos position of first argument to drop (zero for the leftmost)
5300      * @param valueTypes the type(s) of the argument(s) to drop
5301      * @return a method handle which drops arguments of the given types,
5302      *         before calling the original method handle
5303      * @throws NullPointerException if the target is null,
5304      *                              or if the {@code valueTypes} list or any of its elements is null
5305      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5306      *                  or if {@code pos} is negative or greater than the arity of the target,
5307      *                  or if the new method handle's type would have too many parameters
5308      */
5309     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5310         return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone());
5311     }
5312 
5313     static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) {
5314         MethodType oldType = target.type();  // get NPE
5315         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5316         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5317         if (dropped == 0)  return target;
5318         BoundMethodHandle result = target.rebind();
5319         LambdaForm lform = result.form;
5320         int insertFormArg = 1 + pos;
5321         for (Class<?> ptype : valueTypes) {
5322             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5323         }
5324         result = result.copyWith(newType, lform);
5325         return result;
5326     }
5327 
5328     private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) {
5329         int dropped = valueTypes.length;
5330         MethodType.checkSlotCount(dropped);
5331         int outargs = oldType.parameterCount();
5332         int inargs  = outargs + dropped;
5333         if (pos < 0 || pos > outargs)
5334             throw newIllegalArgumentException("no argument type to remove"
5335                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5336                     );
5337         return dropped;
5338     }
5339 
5340     /**
5341      * Produces a method handle which will discard some dummy arguments
5342      * before calling some other specified <i>target</i> method handle.
5343      * The type of the new method handle will be the same as the target's type,
5344      * except it will also include the dummy argument types,
5345      * at some given position.
5346      * <p>
5347      * The {@code pos} argument may range between zero and <i>N</i>,
5348      * where <i>N</i> is the arity of the target.
5349      * If {@code pos} is zero, the dummy arguments will precede
5350      * the target's real arguments; if {@code pos} is <i>N</i>
5351      * they will come after.
5352      * @apiNote
5353      * {@snippet lang="java" :
5354 import static java.lang.invoke.MethodHandles.*;
5355 import static java.lang.invoke.MethodType.*;
5356 ...
5357 MethodHandle cat = lookup().findVirtual(String.class,
5358   "concat", methodType(String.class, String.class));
5359 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5360 MethodHandle d0 = dropArguments(cat, 0, String.class);
5361 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5362 MethodHandle d1 = dropArguments(cat, 1, String.class);
5363 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5364 MethodHandle d2 = dropArguments(cat, 2, String.class);
5365 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5366 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5367 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5368      * }
5369      * <p>
5370      * This method is also equivalent to the following code:
5371      * <blockquote><pre>
5372      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5373      * </pre></blockquote>
5374      * @param target the method handle to invoke after the arguments are dropped
5375      * @param pos position of first argument to drop (zero for the leftmost)
5376      * @param valueTypes the type(s) of the argument(s) to drop
5377      * @return a method handle which drops arguments of the given types,
5378      *         before calling the original method handle
5379      * @throws NullPointerException if the target is null,
5380      *                              or if the {@code valueTypes} array or any of its elements is null
5381      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5382      *                  or if {@code pos} is negative or greater than the arity of the target,
5383      *                  or if the new method handle's type would have
5384      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
5385      */
5386     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5387         return dropArgumentsTrusted(target, pos, valueTypes.clone());
5388     }
5389 
5390     /* Convenience overloads for trusting internal low-arity call-sites */
5391     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) {
5392         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 });
5393     }
5394     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) {
5395         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 });
5396     }
5397 
5398     // private version which allows caller some freedom with error handling
5399     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos,
5400                                       boolean nullOnFailure) {
5401         Class<?>[] oldTypes = target.type().ptypes();
5402         int match = oldTypes.length;
5403         if (skip != 0) {
5404             if (skip < 0 || skip > match) {
5405                 throw newIllegalArgumentException("illegal skip", skip, target);
5406             }
5407             oldTypes = Arrays.copyOfRange(oldTypes, skip, match);
5408             match -= skip;
5409         }
5410         Class<?>[] addTypes = newTypes;
5411         int add = addTypes.length;
5412         if (pos != 0) {
5413             if (pos < 0 || pos > add) {
5414                 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes));
5415             }
5416             addTypes = Arrays.copyOfRange(addTypes, pos, add);
5417             add -= pos;
5418             assert(addTypes.length == add);
5419         }
5420         // Do not add types which already match the existing arguments.
5421         if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) {
5422             if (nullOnFailure) {
5423                 return null;
5424             }
5425             throw newIllegalArgumentException("argument lists do not match",
5426                 Arrays.toString(oldTypes), Arrays.toString(newTypes));
5427         }
5428         addTypes = Arrays.copyOfRange(addTypes, match, add);
5429         add -= match;
5430         assert(addTypes.length == add);
5431         // newTypes:     (   P*[pos], M*[match], A*[add] )
5432         // target: ( S*[skip],        M*[match]  )
5433         MethodHandle adapter = target;
5434         if (add > 0) {
5435             adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes);
5436         }
5437         // adapter: (S*[skip],        M*[match], A*[add] )
5438         if (pos > 0) {
5439             adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos));
5440         }
5441         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5442         return adapter;
5443     }
5444 
5445     /**
5446      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5447      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5448      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5449      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5450      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5451      * {@link #dropArguments(MethodHandle, int, Class[])}.
5452      * <p>
5453      * The resulting handle will have the same return type as the target handle.
5454      * <p>
5455      * In more formal terms, assume these two type lists:<ul>
5456      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5457      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5458      * {@code newTypes}.
5459      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5460      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5461      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5462      * sub-list.
5463      * </ul>
5464      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5465      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5466      * {@link #dropArguments(MethodHandle, int, Class[])}.
5467      *
5468      * @apiNote
5469      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5470      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5471      * {@snippet lang="java" :
5472 import static java.lang.invoke.MethodHandles.*;
5473 import static java.lang.invoke.MethodType.*;
5474 ...
5475 ...
5476 MethodHandle h0 = constant(boolean.class, true);
5477 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5478 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5479 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5480 if (h1.type().parameterCount() < h2.type().parameterCount())
5481     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5482 else
5483     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5484 MethodHandle h3 = guardWithTest(h0, h1, h2);
5485 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5486      * }
5487      * @param target the method handle to adapt
5488      * @param skip number of targets parameters to disregard (they will be unchanged)
5489      * @param newTypes the list of types to match {@code target}'s parameter type list to
5490      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5491      * @return a possibly adapted method handle
5492      * @throws NullPointerException if either argument is null
5493      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5494      *         or if {@code skip} is negative or greater than the arity of the target,
5495      *         or if {@code pos} is negative or greater than the newTypes list size,
5496      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5497      *         {@code pos}.
5498      * @since 9
5499      */
5500     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5501         Objects.requireNonNull(target);
5502         Objects.requireNonNull(newTypes);
5503         return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false);
5504     }
5505 
5506     /**
5507      * Drop the return value of the target handle (if any).
5508      * The returned method handle will have a {@code void} return type.
5509      *
5510      * @param target the method handle to adapt
5511      * @return a possibly adapted method handle
5512      * @throws NullPointerException if {@code target} is null
5513      * @since 16
5514      */
5515     public static MethodHandle dropReturn(MethodHandle target) {
5516         Objects.requireNonNull(target);
5517         MethodType oldType = target.type();
5518         Class<?> oldReturnType = oldType.returnType();
5519         if (oldReturnType == void.class)
5520             return target;
5521         MethodType newType = oldType.changeReturnType(void.class);
5522         BoundMethodHandle result = target.rebind();
5523         LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5524         result = result.copyWith(newType, lform);
5525         return result;
5526     }
5527 
5528     /**
5529      * Adapts a target method handle by pre-processing
5530      * one or more of its arguments, each with its own unary filter function,
5531      * and then calling the target with each pre-processed argument
5532      * replaced by the result of its corresponding filter function.
5533      * <p>
5534      * The pre-processing is performed by one or more method handles,
5535      * specified in the elements of the {@code filters} array.
5536      * The first element of the filter array corresponds to the {@code pos}
5537      * argument of the target, and so on in sequence.
5538      * The filter functions are invoked in left to right order.
5539      * <p>
5540      * Null arguments in the array are treated as identity functions,
5541      * and the corresponding arguments left unchanged.
5542      * (If there are no non-null elements in the array, the original target is returned.)
5543      * Each filter is applied to the corresponding argument of the adapter.
5544      * <p>
5545      * If a filter {@code F} applies to the {@code N}th argument of
5546      * the target, then {@code F} must be a method handle which
5547      * takes exactly one argument.  The type of {@code F}'s sole argument
5548      * replaces the corresponding argument type of the target
5549      * in the resulting adapted method handle.
5550      * The return type of {@code F} must be identical to the corresponding
5551      * parameter type of the target.
5552      * <p>
5553      * It is an error if there are elements of {@code filters}
5554      * (null or not)
5555      * which do not correspond to argument positions in the target.
5556      * <p><b>Example:</b>
5557      * {@snippet lang="java" :
5558 import static java.lang.invoke.MethodHandles.*;
5559 import static java.lang.invoke.MethodType.*;
5560 ...
5561 MethodHandle cat = lookup().findVirtual(String.class,
5562   "concat", methodType(String.class, String.class));
5563 MethodHandle upcase = lookup().findVirtual(String.class,
5564   "toUpperCase", methodType(String.class));
5565 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5566 MethodHandle f0 = filterArguments(cat, 0, upcase);
5567 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5568 MethodHandle f1 = filterArguments(cat, 1, upcase);
5569 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5570 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5571 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5572      * }
5573      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5574      * denotes the return type of both the {@code target} and resulting adapter.
5575      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5576      * of the parameters and arguments that precede and follow the filter position
5577      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5578      * values of the filtered parameters and arguments; they also represent the
5579      * return types of the {@code filter[i]} handles. The latter accept arguments
5580      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5581      * the resulting adapter.
5582      * {@snippet lang="java" :
5583      * T target(P... p, A[i]... a[i], B... b);
5584      * A[i] filter[i](V[i]);
5585      * T adapter(P... p, V[i]... v[i], B... b) {
5586      *   return target(p..., filter[i](v[i])..., b...);
5587      * }
5588      * }
5589      * <p>
5590      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5591      * variable-arity method handle}, even if the original target method handle was.
5592      *
5593      * @param target the method handle to invoke after arguments are filtered
5594      * @param pos the position of the first argument to filter
5595      * @param filters method handles to call initially on filtered arguments
5596      * @return method handle which incorporates the specified argument filtering logic
5597      * @throws NullPointerException if the target is null
5598      *                              or if the {@code filters} array is null
5599      * @throws IllegalArgumentException if a non-null element of {@code filters}
5600      *          does not match a corresponding argument type of target as described above,
5601      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5602      *          or if the resulting method handle's type would have
5603      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5604      */
5605     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5606         // In method types arguments start at index 0, while the LF
5607         // editor have the MH receiver at position 0 - adjust appropriately.
5608         final int MH_RECEIVER_OFFSET = 1;
5609         filterArgumentsCheckArity(target, pos, filters);
5610         MethodHandle adapter = target;
5611 
5612         // keep track of currently matched filters, as to optimize repeated filters
5613         int index = 0;
5614         int[] positions = new int[filters.length];
5615         MethodHandle filter = null;
5616 
5617         // process filters in reverse order so that the invocation of
5618         // the resulting adapter will invoke the filters in left-to-right order
5619         for (int i = filters.length - 1; i >= 0; --i) {
5620             MethodHandle newFilter = filters[i];
5621             if (newFilter == null) continue;  // ignore null elements of filters
5622 
5623             // flush changes on update
5624             if (filter != newFilter) {
5625                 if (filter != null) {
5626                     if (index > 1) {
5627                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5628                     } else {
5629                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5630                     }
5631                 }
5632                 filter = newFilter;
5633                 index = 0;
5634             }
5635 
5636             filterArgumentChecks(target, pos + i, newFilter);
5637             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5638         }
5639         if (index > 1) {
5640             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5641         } else if (index == 1) {
5642             adapter = filterArgument(adapter, positions[0] - 1, filter);
5643         }
5644         return adapter;
5645     }
5646 
5647     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5648         MethodType targetType = adapter.type();
5649         MethodType filterType = filter.type();
5650         BoundMethodHandle result = adapter.rebind();
5651         Class<?> newParamType = filterType.parameterType(0);
5652 
5653         Class<?>[] ptypes = targetType.ptypes().clone();
5654         for (int pos : positions) {
5655             ptypes[pos - 1] = newParamType;
5656         }
5657         MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true);
5658 
5659         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5660         return result.copyWithExtendL(newType, lform, filter);
5661     }
5662 
5663     /*non-public*/
5664     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5665         filterArgumentChecks(target, pos, filter);
5666         MethodType targetType = target.type();
5667         MethodType filterType = filter.type();
5668         BoundMethodHandle result = target.rebind();
5669         Class<?> newParamType = filterType.parameterType(0);
5670         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5671         MethodType newType = targetType.changeParameterType(pos, newParamType);
5672         result = result.copyWithExtendL(newType, lform, filter);
5673         return result;
5674     }
5675 
5676     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5677         MethodType targetType = target.type();
5678         int maxPos = targetType.parameterCount();
5679         if (pos + filters.length > maxPos)
5680             throw newIllegalArgumentException("too many filters");
5681     }
5682 
5683     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5684         MethodType targetType = target.type();
5685         MethodType filterType = filter.type();
5686         if (filterType.parameterCount() != 1
5687             || filterType.returnType() != targetType.parameterType(pos))
5688             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5689     }
5690 
5691     /**
5692      * Adapts a target method handle by pre-processing
5693      * a sub-sequence of its arguments with a filter (another method handle).
5694      * The pre-processed arguments are replaced by the result (if any) of the
5695      * filter function.
5696      * The target is then called on the modified (usually shortened) argument list.
5697      * <p>
5698      * If the filter returns a value, the target must accept that value as
5699      * its argument in position {@code pos}, preceded and/or followed by
5700      * any arguments not passed to the filter.
5701      * If the filter returns void, the target must accept all arguments
5702      * not passed to the filter.
5703      * No arguments are reordered, and a result returned from the filter
5704      * replaces (in order) the whole subsequence of arguments originally
5705      * passed to the adapter.
5706      * <p>
5707      * The argument types (if any) of the filter
5708      * replace zero or one argument types of the target, at position {@code pos},
5709      * in the resulting adapted method handle.
5710      * The return type of the filter (if any) must be identical to the
5711      * argument type of the target at position {@code pos}, and that target argument
5712      * is supplied by the return value of the filter.
5713      * <p>
5714      * In all cases, {@code pos} must be greater than or equal to zero, and
5715      * {@code pos} must also be less than or equal to the target's arity.
5716      * <p><b>Example:</b>
5717      * {@snippet lang="java" :
5718 import static java.lang.invoke.MethodHandles.*;
5719 import static java.lang.invoke.MethodType.*;
5720 ...
5721 MethodHandle deepToString = publicLookup()
5722   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5723 
5724 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5725 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5726 
5727 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5728 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5729 
5730 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5731 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5732 assertEquals("[top, [up, down], strange]",
5733              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5734 
5735 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5736 assertEquals("[top, [up, down], [strange]]",
5737              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5738 
5739 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5740 assertEquals("[top, [[up, down, strange], charm], bottom]",
5741              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5742      * }
5743      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5744      * represents the return type of the {@code target} and resulting adapter.
5745      * {@code V}/{@code v} stand for the return type and value of the
5746      * {@code filter}, which are also found in the signature and arguments of
5747      * the {@code target}, respectively, unless {@code V} is {@code void}.
5748      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5749      * and values preceding and following the collection position, {@code pos},
5750      * in the {@code target}'s signature. They also turn up in the resulting
5751      * adapter's signature and arguments, where they surround
5752      * {@code B}/{@code b}, which represent the parameter types and arguments
5753      * to the {@code filter} (if any).
5754      * {@snippet lang="java" :
5755      * T target(A...,V,C...);
5756      * V filter(B...);
5757      * T adapter(A... a,B... b,C... c) {
5758      *   V v = filter(b...);
5759      *   return target(a...,v,c...);
5760      * }
5761      * // and if the filter has no arguments:
5762      * T target2(A...,V,C...);
5763      * V filter2();
5764      * T adapter2(A... a,C... c) {
5765      *   V v = filter2();
5766      *   return target2(a...,v,c...);
5767      * }
5768      * // and if the filter has a void return:
5769      * T target3(A...,C...);
5770      * void filter3(B...);
5771      * T adapter3(A... a,B... b,C... c) {
5772      *   filter3(b...);
5773      *   return target3(a...,c...);
5774      * }
5775      * }
5776      * <p>
5777      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5778      * one which first "folds" the affected arguments, and then drops them, in separate
5779      * steps as follows:
5780      * {@snippet lang="java" :
5781      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5782      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5783      * }
5784      * If the target method handle consumes no arguments besides than the result
5785      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5786      * is equivalent to {@code filterReturnValue(coll, mh)}.
5787      * If the filter method handle {@code coll} consumes one argument and produces
5788      * a non-void result, then {@code collectArguments(mh, N, coll)}
5789      * is equivalent to {@code filterArguments(mh, N, coll)}.
5790      * Other equivalences are possible but would require argument permutation.
5791      * <p>
5792      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5793      * variable-arity method handle}, even if the original target method handle was.
5794      *
5795      * @param target the method handle to invoke after filtering the subsequence of arguments
5796      * @param pos the position of the first adapter argument to pass to the filter,
5797      *            and/or the target argument which receives the result of the filter
5798      * @param filter method handle to call on the subsequence of arguments
5799      * @return method handle which incorporates the specified argument subsequence filtering logic
5800      * @throws NullPointerException if either argument is null
5801      * @throws IllegalArgumentException if the return type of {@code filter}
5802      *          is non-void and is not the same as the {@code pos} argument of the target,
5803      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5804      *          or if the resulting method handle's type would have
5805      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5806      * @see MethodHandles#foldArguments
5807      * @see MethodHandles#filterArguments
5808      * @see MethodHandles#filterReturnValue
5809      */
5810     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5811         MethodType newType = collectArgumentsChecks(target, pos, filter);
5812         MethodType collectorType = filter.type();
5813         BoundMethodHandle result = target.rebind();
5814         LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5815         return result.copyWithExtendL(newType, lform, filter);
5816     }
5817 
5818     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5819         MethodType targetType = target.type();
5820         MethodType filterType = filter.type();
5821         Class<?> rtype = filterType.returnType();
5822         Class<?>[] filterArgs = filterType.ptypes();
5823         if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5824                        (rtype != void.class && pos >= targetType.parameterCount())) {
5825             throw newIllegalArgumentException("position is out of range for target", target, pos);
5826         }
5827         if (rtype == void.class) {
5828             return targetType.insertParameterTypes(pos, filterArgs);
5829         }
5830         if (rtype != targetType.parameterType(pos)) {
5831             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5832         }
5833         return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs);
5834     }
5835 
5836     /**
5837      * Adapts a target method handle by post-processing
5838      * its return value (if any) with a filter (another method handle).
5839      * The result of the filter is returned from the adapter.
5840      * <p>
5841      * If the target returns a value, the filter must accept that value as
5842      * its only argument.
5843      * If the target returns void, the filter must accept no arguments.
5844      * <p>
5845      * The return type of the filter
5846      * replaces the return type of the target
5847      * in the resulting adapted method handle.
5848      * The argument type of the filter (if any) must be identical to the
5849      * return type of the target.
5850      * <p><b>Example:</b>
5851      * {@snippet lang="java" :
5852 import static java.lang.invoke.MethodHandles.*;
5853 import static java.lang.invoke.MethodType.*;
5854 ...
5855 MethodHandle cat = lookup().findVirtual(String.class,
5856   "concat", methodType(String.class, String.class));
5857 MethodHandle length = lookup().findVirtual(String.class,
5858   "length", methodType(int.class));
5859 System.out.println((String) cat.invokeExact("x", "y")); // xy
5860 MethodHandle f0 = filterReturnValue(cat, length);
5861 System.out.println((int) f0.invokeExact("x", "y")); // 2
5862      * }
5863      * <p>Here is pseudocode for the resulting adapter. In the code,
5864      * {@code T}/{@code t} represent the result type and value of the
5865      * {@code target}; {@code V}, the result type of the {@code filter}; and
5866      * {@code A}/{@code a}, the types and values of the parameters and arguments
5867      * of the {@code target} as well as the resulting adapter.
5868      * {@snippet lang="java" :
5869      * T target(A...);
5870      * V filter(T);
5871      * V adapter(A... a) {
5872      *   T t = target(a...);
5873      *   return filter(t);
5874      * }
5875      * // and if the target has a void return:
5876      * void target2(A...);
5877      * V filter2();
5878      * V adapter2(A... a) {
5879      *   target2(a...);
5880      *   return filter2();
5881      * }
5882      * // and if the filter has a void return:
5883      * T target3(A...);
5884      * void filter3(V);
5885      * void adapter3(A... a) {
5886      *   T t = target3(a...);
5887      *   filter3(t);
5888      * }
5889      * }
5890      * <p>
5891      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5892      * variable-arity method handle}, even if the original target method handle was.
5893      * @param target the method handle to invoke before filtering the return value
5894      * @param filter method handle to call on the return value
5895      * @return method handle which incorporates the specified return value filtering logic
5896      * @throws NullPointerException if either argument is null
5897      * @throws IllegalArgumentException if the argument list of {@code filter}
5898      *          does not match the return type of target as described above
5899      */
5900     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5901         MethodType targetType = target.type();
5902         MethodType filterType = filter.type();
5903         filterReturnValueChecks(targetType, filterType);
5904         BoundMethodHandle result = target.rebind();
5905         BasicType rtype = BasicType.basicType(filterType.returnType());
5906         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5907         MethodType newType = targetType.changeReturnType(filterType.returnType());
5908         result = result.copyWithExtendL(newType, lform, filter);
5909         return result;
5910     }
5911 
5912     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5913         Class<?> rtype = targetType.returnType();
5914         int filterValues = filterType.parameterCount();
5915         if (filterValues == 0
5916                 ? (rtype != void.class)
5917                 : (rtype != filterType.parameterType(0) || filterValues != 1))
5918             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5919     }
5920 
5921     /**
5922      * Filter the return value of a target method handle with a filter function. The filter function is
5923      * applied to the return value of the original handle; if the filter specifies more than one parameters,
5924      * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5925      * as follows:
5926      * {@snippet lang="java" :
5927      * T target(A...)
5928      * V filter(B... , T)
5929      * V adapter(A... a, B... b) {
5930      *     T t = target(a...);
5931      *     return filter(b..., t);
5932      * }
5933      * }
5934      * <p>
5935      * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
5936      *
5937      * @param target the target method handle
5938      * @param filter the filter method handle
5939      * @return the adapter method handle
5940      */
5941     /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
5942         MethodType targetType = target.type();
5943         MethodType filterType = filter.type();
5944         BoundMethodHandle result = target.rebind();
5945         LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
5946         MethodType newType = targetType.changeReturnType(filterType.returnType());
5947         if (filterType.parameterCount() > 1) {
5948             for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
5949                 newType = newType.appendParameterTypes(filterType.parameterType(i));
5950             }
5951         }
5952         result = result.copyWithExtendL(newType, lform, filter);
5953         return result;
5954     }
5955 
5956     /**
5957      * Adapts a target method handle by pre-processing
5958      * some of its arguments, and then calling the target with
5959      * the result of the pre-processing, inserted into the original
5960      * sequence of arguments.
5961      * <p>
5962      * The pre-processing is performed by {@code combiner}, a second method handle.
5963      * Of the arguments passed to the adapter, the first {@code N} arguments
5964      * are copied to the combiner, which is then called.
5965      * (Here, {@code N} is defined as the parameter count of the combiner.)
5966      * After this, control passes to the target, with any result
5967      * from the combiner inserted before the original {@code N} incoming
5968      * arguments.
5969      * <p>
5970      * If the combiner returns a value, the first parameter type of the target
5971      * must be identical with the return type of the combiner, and the next
5972      * {@code N} parameter types of the target must exactly match the parameters
5973      * of the combiner.
5974      * <p>
5975      * If the combiner has a void return, no result will be inserted,
5976      * and the first {@code N} parameter types of the target
5977      * must exactly match the parameters of the combiner.
5978      * <p>
5979      * The resulting adapter is the same type as the target, except that the
5980      * first parameter type is dropped,
5981      * if it corresponds to the result of the combiner.
5982      * <p>
5983      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
5984      * that either the combiner or the target does not wish to receive.
5985      * If some of the incoming arguments are destined only for the combiner,
5986      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
5987      * arguments will not need to be live on the stack on entry to the
5988      * target.)
5989      * <p><b>Example:</b>
5990      * {@snippet lang="java" :
5991 import static java.lang.invoke.MethodHandles.*;
5992 import static java.lang.invoke.MethodType.*;
5993 ...
5994 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5995   "println", methodType(void.class, String.class))
5996     .bindTo(System.out);
5997 MethodHandle cat = lookup().findVirtual(String.class,
5998   "concat", methodType(String.class, String.class));
5999 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6000 MethodHandle catTrace = foldArguments(cat, trace);
6001 // also prints "boo":
6002 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6003      * }
6004      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6005      * represents the result type of the {@code target} and resulting adapter.
6006      * {@code V}/{@code v} represent the type and value of the parameter and argument
6007      * of {@code target} that precedes the folding position; {@code V} also is
6008      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6009      * types and values of the {@code N} parameters and arguments at the folding
6010      * position. {@code B}/{@code b} represent the types and values of the
6011      * {@code target} parameters and arguments that follow the folded parameters
6012      * and arguments.
6013      * {@snippet lang="java" :
6014      * // there are N arguments in A...
6015      * T target(V, A[N]..., B...);
6016      * V combiner(A...);
6017      * T adapter(A... a, B... b) {
6018      *   V v = combiner(a...);
6019      *   return target(v, a..., b...);
6020      * }
6021      * // and if the combiner has a void return:
6022      * T target2(A[N]..., B...);
6023      * void combiner2(A...);
6024      * T adapter2(A... a, B... b) {
6025      *   combiner2(a...);
6026      *   return target2(a..., b...);
6027      * }
6028      * }
6029      * <p>
6030      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6031      * variable-arity method handle}, even if the original target method handle was.
6032      * @param target the method handle to invoke after arguments are combined
6033      * @param combiner method handle to call initially on the incoming arguments
6034      * @return method handle which incorporates the specified argument folding logic
6035      * @throws NullPointerException if either argument is null
6036      * @throws IllegalArgumentException if {@code combiner}'s return type
6037      *          is non-void and not the same as the first argument type of
6038      *          the target, or if the initial {@code N} argument types
6039      *          of the target
6040      *          (skipping one matching the {@code combiner}'s return type)
6041      *          are not identical with the argument types of {@code combiner}
6042      */
6043     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
6044         return foldArguments(target, 0, combiner);
6045     }
6046 
6047     /**
6048      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
6049      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
6050      * before the folded arguments.
6051      * <p>
6052      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
6053      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
6054      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
6055      * 0.
6056      *
6057      * @apiNote Example:
6058      * {@snippet lang="java" :
6059     import static java.lang.invoke.MethodHandles.*;
6060     import static java.lang.invoke.MethodType.*;
6061     ...
6062     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6063     "println", methodType(void.class, String.class))
6064     .bindTo(System.out);
6065     MethodHandle cat = lookup().findVirtual(String.class,
6066     "concat", methodType(String.class, String.class));
6067     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6068     MethodHandle catTrace = foldArguments(cat, 1, trace);
6069     // also prints "jum":
6070     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6071      * }
6072      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6073      * represents the result type of the {@code target} and resulting adapter.
6074      * {@code V}/{@code v} represent the type and value of the parameter and argument
6075      * of {@code target} that precedes the folding position; {@code V} also is
6076      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6077      * types and values of the {@code N} parameters and arguments at the folding
6078      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
6079      * and values of the {@code target} parameters and arguments that precede and
6080      * follow the folded parameters and arguments starting at {@code pos},
6081      * respectively.
6082      * {@snippet lang="java" :
6083      * // there are N arguments in A...
6084      * T target(Z..., V, A[N]..., B...);
6085      * V combiner(A...);
6086      * T adapter(Z... z, A... a, B... b) {
6087      *   V v = combiner(a...);
6088      *   return target(z..., v, a..., b...);
6089      * }
6090      * // and if the combiner has a void return:
6091      * T target2(Z..., A[N]..., B...);
6092      * void combiner2(A...);
6093      * T adapter2(Z... z, A... a, B... b) {
6094      *   combiner2(a...);
6095      *   return target2(z..., 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      *
6102      * @param target the method handle to invoke after arguments are combined
6103      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
6104      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6105      * @param combiner method handle to call initially on the incoming arguments
6106      * @return method handle which incorporates the specified argument folding logic
6107      * @throws NullPointerException if either argument is null
6108      * @throws IllegalArgumentException if either of the following two conditions holds:
6109      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6110      *              {@code pos} of the target signature;
6111      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
6112      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
6113      *
6114      * @see #foldArguments(MethodHandle, MethodHandle)
6115      * @since 9
6116      */
6117     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
6118         MethodType targetType = target.type();
6119         MethodType combinerType = combiner.type();
6120         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
6121         BoundMethodHandle result = target.rebind();
6122         boolean dropResult = rtype == void.class;
6123         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
6124         MethodType newType = targetType;
6125         if (!dropResult) {
6126             newType = newType.dropParameterTypes(pos, pos + 1);
6127         }
6128         result = result.copyWithExtendL(newType, lform, combiner);
6129         return result;
6130     }
6131 
6132     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
6133         int foldArgs   = combinerType.parameterCount();
6134         Class<?> rtype = combinerType.returnType();
6135         int foldVals = rtype == void.class ? 0 : 1;
6136         int afterInsertPos = foldPos + foldVals;
6137         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
6138         if (ok) {
6139             for (int i = 0; i < foldArgs; i++) {
6140                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
6141                     ok = false;
6142                     break;
6143                 }
6144             }
6145         }
6146         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
6147             ok = false;
6148         if (!ok)
6149             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6150         return rtype;
6151     }
6152 
6153     /**
6154      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
6155      * of the pre-processing replacing the argument at the given position.
6156      *
6157      * @param target the method handle to invoke after arguments are combined
6158      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6159      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6160      * @param combiner method handle to call initially on the incoming arguments
6161      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6162      * @return method handle which incorporates the specified argument folding logic
6163      * @throws NullPointerException if either argument is null
6164      * @throws IllegalArgumentException if either of the following two conditions holds:
6165      *          (1) {@code combiner}'s return type is not the same as the argument type at position
6166      *              {@code pos} of the target signature;
6167      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
6168      *              not identical with the argument types of {@code combiner}.
6169      */
6170     /*non-public*/
6171     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6172         return argumentsWithCombiner(true, target, position, combiner, argPositions);
6173     }
6174 
6175     /**
6176      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
6177      * the pre-processing inserted into the original sequence of arguments at the given position.
6178      *
6179      * @param target the method handle to invoke after arguments are combined
6180      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6181      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6182      * @param combiner method handle to call initially on the incoming arguments
6183      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6184      * @return method handle which incorporates the specified argument folding logic
6185      * @throws NullPointerException if either argument is null
6186      * @throws IllegalArgumentException if either of the following two conditions holds:
6187      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6188      *              {@code pos} of the target signature;
6189      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
6190      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
6191      *              with the argument types of {@code combiner}.
6192      */
6193     /*non-public*/
6194     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6195         return argumentsWithCombiner(false, target, position, combiner, argPositions);
6196     }
6197 
6198     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6199         MethodType targetType = target.type();
6200         MethodType combinerType = combiner.type();
6201         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
6202         BoundMethodHandle result = target.rebind();
6203 
6204         MethodType newType = targetType;
6205         LambdaForm lform;
6206         if (filter) {
6207             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
6208         } else {
6209             boolean dropResult = rtype == void.class;
6210             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
6211             if (!dropResult) {
6212                 newType = newType.dropParameterTypes(position, position + 1);
6213             }
6214         }
6215         result = result.copyWithExtendL(newType, lform, combiner);
6216         return result;
6217     }
6218 
6219     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
6220         int combinerArgs = combinerType.parameterCount();
6221         if (argPos.length != combinerArgs) {
6222             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
6223         }
6224         Class<?> rtype = combinerType.returnType();
6225 
6226         for (int i = 0; i < combinerArgs; i++) {
6227             int arg = argPos[i];
6228             if (arg < 0 || arg > targetType.parameterCount()) {
6229                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
6230             }
6231             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
6232                 throw newIllegalArgumentException("target argument type at position " + arg
6233                         + " must match combiner argument type at index " + i + ": " + targetType
6234                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6235             }
6236         }
6237         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6238             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6239         }
6240         return rtype;
6241     }
6242 
6243     /**
6244      * Makes a method handle which adapts a target method handle,
6245      * by guarding it with a test, a boolean-valued method handle.
6246      * If the guard fails, a fallback handle is called instead.
6247      * All three method handles must have the same corresponding
6248      * argument and return types, except that the return type
6249      * of the test must be boolean, and the test is allowed
6250      * to have fewer arguments than the other two method handles.
6251      * <p>
6252      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6253      * represents the uniform result type of the three involved handles;
6254      * {@code A}/{@code a}, the types and values of the {@code target}
6255      * parameters and arguments that are consumed by the {@code test}; and
6256      * {@code B}/{@code b}, those types and values of the {@code target}
6257      * parameters and arguments that are not consumed by the {@code test}.
6258      * {@snippet lang="java" :
6259      * boolean test(A...);
6260      * T target(A...,B...);
6261      * T fallback(A...,B...);
6262      * T adapter(A... a,B... b) {
6263      *   if (test(a...))
6264      *     return target(a..., b...);
6265      *   else
6266      *     return fallback(a..., b...);
6267      * }
6268      * }
6269      * Note that the test arguments ({@code a...} in the pseudocode) cannot
6270      * be modified by execution of the test, and so are passed unchanged
6271      * from the caller to the target or fallback as appropriate.
6272      * @param test method handle used for test, must return boolean
6273      * @param target method handle to call if test passes
6274      * @param fallback method handle to call if test fails
6275      * @return method handle which incorporates the specified if/then/else logic
6276      * @throws NullPointerException if any argument is null
6277      * @throws IllegalArgumentException if {@code test} does not return boolean,
6278      *          or if all three method types do not match (with the return
6279      *          type of {@code test} changed to match that of the target).
6280      */
6281     public static MethodHandle guardWithTest(MethodHandle test,
6282                                MethodHandle target,
6283                                MethodHandle fallback) {
6284         MethodType gtype = test.type();
6285         MethodType ttype = target.type();
6286         MethodType ftype = fallback.type();
6287         if (!ttype.equals(ftype))
6288             throw misMatchedTypes("target and fallback types", ttype, ftype);
6289         if (gtype.returnType() != boolean.class)
6290             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6291 
6292         test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true);
6293         if (test == null) {
6294             throw misMatchedTypes("target and test types", ttype, gtype);
6295         }
6296         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6297     }
6298 
6299     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6300         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6301     }
6302 
6303     /**
6304      * Makes a method handle which adapts a target method handle,
6305      * by running it inside an exception handler.
6306      * If the target returns normally, the adapter returns that value.
6307      * If an exception matching the specified type is thrown, the fallback
6308      * handle is called instead on the exception, plus the original arguments.
6309      * <p>
6310      * The target and handler must have the same corresponding
6311      * argument and return types, except that handler may omit trailing arguments
6312      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6313      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6314      * <p>
6315      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6316      * represents the return type of the {@code target} and {@code handler},
6317      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6318      * the types and values of arguments to the resulting handle consumed by
6319      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6320      * resulting handle discarded by {@code handler}.
6321      * {@snippet lang="java" :
6322      * T target(A..., B...);
6323      * T handler(ExType, A...);
6324      * T adapter(A... a, B... b) {
6325      *   try {
6326      *     return target(a..., b...);
6327      *   } catch (ExType ex) {
6328      *     return handler(ex, a...);
6329      *   }
6330      * }
6331      * }
6332      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6333      * be modified by execution of the target, and so are passed unchanged
6334      * from the caller to the handler, if the handler is invoked.
6335      * <p>
6336      * The target and handler must return the same type, even if the handler
6337      * always throws.  (This might happen, for instance, because the handler
6338      * is simulating a {@code finally} clause).
6339      * To create such a throwing handler, compose the handler creation logic
6340      * with {@link #throwException throwException},
6341      * in order to create a method handle of the correct return type.
6342      * @param target method handle to call
6343      * @param exType the type of exception which the handler will catch
6344      * @param handler method handle to call if a matching exception is thrown
6345      * @return method handle which incorporates the specified try/catch logic
6346      * @throws NullPointerException if any argument is null
6347      * @throws IllegalArgumentException if {@code handler} does not accept
6348      *          the given exception type, or if the method handle types do
6349      *          not match in their return types and their
6350      *          corresponding parameters
6351      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6352      */
6353     public static MethodHandle catchException(MethodHandle target,
6354                                 Class<? extends Throwable> exType,
6355                                 MethodHandle handler) {
6356         MethodType ttype = target.type();
6357         MethodType htype = handler.type();
6358         if (!Throwable.class.isAssignableFrom(exType))
6359             throw new ClassCastException(exType.getName());
6360         if (htype.parameterCount() < 1 ||
6361             !htype.parameterType(0).isAssignableFrom(exType))
6362             throw newIllegalArgumentException("handler does not accept exception type "+exType);
6363         if (htype.returnType() != ttype.returnType())
6364             throw misMatchedTypes("target and handler return types", ttype, htype);
6365         handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true);
6366         if (handler == null) {
6367             throw misMatchedTypes("target and handler types", ttype, htype);
6368         }
6369         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6370     }
6371 
6372     /**
6373      * Produces a method handle which will throw exceptions of the given {@code exType}.
6374      * The method handle will accept a single argument of {@code exType},
6375      * and immediately throw it as an exception.
6376      * The method type will nominally specify a return of {@code returnType}.
6377      * The return type may be anything convenient:  It doesn't matter to the
6378      * method handle's behavior, since it will never return normally.
6379      * @param returnType the return type of the desired method handle
6380      * @param exType the parameter type of the desired method handle
6381      * @return method handle which can throw the given exceptions
6382      * @throws NullPointerException if either argument is null
6383      */
6384     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6385         if (!Throwable.class.isAssignableFrom(exType))
6386             throw new ClassCastException(exType.getName());
6387         return MethodHandleImpl.throwException(methodType(returnType, exType));
6388     }
6389 
6390     /**
6391      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6392      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6393      * delivers the loop's result, which is the return value of the resulting handle.
6394      * <p>
6395      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6396      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6397      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6398      * terms of method handles, each clause will specify up to four independent actions:<ul>
6399      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6400      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6401      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6402      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6403      * </ul>
6404      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6405      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
6406      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6407      * <p>
6408      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6409      * this case. See below for a detailed description.
6410      * <p>
6411      * <em>Parameters optional everywhere:</em>
6412      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6413      * As an exception, the init functions cannot take any {@code v} parameters,
6414      * because those values are not yet computed when the init functions are executed.
6415      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6416      * In fact, any clause function may take no arguments at all.
6417      * <p>
6418      * <em>Loop parameters:</em>
6419      * A clause function may take all the iteration variable values it is entitled to, in which case
6420      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6421      * with their types and values notated as {@code (A...)} and {@code (a...)}.
6422      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6423      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6424      * init function is automatically a loop parameter {@code a}.)
6425      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6426      * These loop parameters act as loop-invariant values visible across the whole loop.
6427      * <p>
6428      * <em>Parameters visible everywhere:</em>
6429      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6430      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6431      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6432      * Most clause functions will not need all of this information, but they will be formally connected to it
6433      * as if by {@link #dropArguments}.
6434      * <a id="astar"></a>
6435      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6436      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6437      * In that notation, the general form of an init function parameter list
6438      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6439      * <p>
6440      * <em>Checking clause structure:</em>
6441      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6442      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6443      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6444      * met by the inputs to the loop combinator.
6445      * <p>
6446      * <em>Effectively identical sequences:</em>
6447      * <a id="effid"></a>
6448      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6449      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6450      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6451      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6452      * that longest list.
6453      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6454      * and the same is true if more sequences of the form {@code (V... A*)} are added.
6455      * <p>
6456      * <em>Step 0: Determine clause structure.</em><ol type="a">
6457      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6458      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6459      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6460      * four. Padding takes place by appending elements to the array.
6461      * <li>Clauses with all {@code null}s are disregarded.
6462      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6463      * </ol>
6464      * <p>
6465      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6466      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6467      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6468      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6469      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6470      * iteration variable type.
6471      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6472      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6473      * </ol>
6474      * <p>
6475      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6476      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6477      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6478      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6479      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6480      * (These types will be checked in step 2, along with all the clause function types.)
6481      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6482      * <li>All of the collected parameter lists must be effectively identical.
6483      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6484      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6485      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6486      * the "internal parameter list".
6487      * </ul>
6488      * <p>
6489      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6490      * <li>Examine fini function return types, disregarding omitted fini functions.
6491      * <li>If there are no fini functions, the loop return type is {@code void}.
6492      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6493      * type.
6494      * </ol>
6495      * <p>
6496      * <em>Step 1D: Check other types.</em><ol type="a">
6497      * <li>There must be at least one non-omitted pred function.
6498      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6499      * </ol>
6500      * <p>
6501      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6502      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6503      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6504      * (Note that their parameter lists are already effectively identical to this list.)
6505      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6506      * effectively identical to the internal parameter list {@code (V... A...)}.
6507      * </ol>
6508      * <p>
6509      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6510      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6511      * type.
6512      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6513      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6514      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6515      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6516      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6517      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6518      * loop return type.
6519      * </ol>
6520      * <p>
6521      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6522      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6523      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6524      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6525      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6526      * pad out the end of the list.
6527      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6528      * </ol>
6529      * <p>
6530      * <em>Final observations.</em><ol type="a">
6531      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6532      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6533      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6534      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6535      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6536      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6537      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6538      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6539      * </ol>
6540      * <p>
6541      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6542      * <ul>
6543      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6544      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6545      * (Only one {@code Pn} has to be non-{@code null}.)
6546      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6547      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6548      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6549      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6550      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6551      * the resulting loop handle's parameter types {@code (A...)}.
6552      * </ul>
6553      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6554      * which is natural if most of the loop computation happens in the steps.  For some loops,
6555      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6556      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6557      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6558      * where the init functions will need the extra parameters.  For such reasons, the rules for
6559      * determining these parameters are as symmetric as possible, across all clause parts.
6560      * In general, the loop parameters function as common invariant values across the whole
6561      * loop, while the iteration variables function as common variant values, or (if there is
6562      * no step function) as internal loop invariant temporaries.
6563      * <p>
6564      * <em>Loop execution.</em><ol type="a">
6565      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6566      * every clause function. These locals are loop invariant.
6567      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6568      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6569      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6570      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6571      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6572      * (in argument order).
6573      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6574      * returns {@code false}.
6575      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6576      * sequence {@code (v...)} of loop variables.
6577      * The updated value is immediately visible to all subsequent function calls.
6578      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6579      * (of type {@code R}) is returned from the loop as a whole.
6580      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6581      * except by throwing an exception.
6582      * </ol>
6583      * <p>
6584      * <em>Usage tips.</em>
6585      * <ul>
6586      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6587      * sometimes a step function only needs to observe the current value of its own variable.
6588      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6589      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6590      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6591      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6592      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6593      * <li>If some of the clause functions are virtual methods on an instance, the instance
6594      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6595      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6596      * will be the first iteration variable value, and it will be easy to use virtual
6597      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6598      * </ul>
6599      * <p>
6600      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6601      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6602      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6603      * {@snippet lang="java" :
6604      * V... init...(A...);
6605      * boolean pred...(V..., A...);
6606      * V... step...(V..., A...);
6607      * R fini...(V..., A...);
6608      * R loop(A... a) {
6609      *   V... v... = init...(a...);
6610      *   for (;;) {
6611      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6612      *       v = s(v..., a...);
6613      *       if (!p(v..., a...)) {
6614      *         return f(v..., a...);
6615      *       }
6616      *     }
6617      *   }
6618      * }
6619      * }
6620      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6621      * to their full length, even though individual clause functions may neglect to take them all.
6622      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6623      *
6624      * @apiNote Example:
6625      * {@snippet lang="java" :
6626      * // iterative implementation of the factorial function as a loop handle
6627      * static int one(int k) { return 1; }
6628      * static int inc(int i, int acc, int k) { return i + 1; }
6629      * static int mult(int i, int acc, int k) { return i * acc; }
6630      * static boolean pred(int i, int acc, int k) { return i < k; }
6631      * static int fin(int i, int acc, int k) { return acc; }
6632      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6633      * // null initializer for counter, should initialize to 0
6634      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6635      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6636      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6637      * assertEquals(120, loop.invoke(5));
6638      * }
6639      * The same example, dropping arguments and using combinators:
6640      * {@snippet lang="java" :
6641      * // simplified implementation of the factorial function as a loop handle
6642      * static int inc(int i) { return i + 1; } // drop acc, k
6643      * static int mult(int i, int acc) { return i * acc; } //drop k
6644      * static boolean cmp(int i, int k) { return i < k; }
6645      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6646      * // null initializer for counter, should initialize to 0
6647      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6648      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6649      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6650      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6651      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6652      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6653      * assertEquals(720, loop.invoke(6));
6654      * }
6655      * A similar example, using a helper object to hold a loop parameter:
6656      * {@snippet lang="java" :
6657      * // instance-based implementation of the factorial function as a loop handle
6658      * static class FacLoop {
6659      *   final int k;
6660      *   FacLoop(int k) { this.k = k; }
6661      *   int inc(int i) { return i + 1; }
6662      *   int mult(int i, int acc) { return i * acc; }
6663      *   boolean pred(int i) { return i < k; }
6664      *   int fin(int i, int acc) { return acc; }
6665      * }
6666      * // assume MH_FacLoop is a handle to the constructor
6667      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6668      * // null initializer for counter, should initialize to 0
6669      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6670      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6671      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6672      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6673      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6674      * assertEquals(5040, loop.invoke(7));
6675      * }
6676      *
6677      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6678      *
6679      * @return a method handle embodying the looping behavior as defined by the arguments.
6680      *
6681      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6682      *
6683      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6684      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6685      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6686      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6687      * @since 9
6688      */
6689     public static MethodHandle loop(MethodHandle[]... clauses) {
6690         // Step 0: determine clause structure.
6691         loopChecks0(clauses);
6692 
6693         List<MethodHandle> init = new ArrayList<>();
6694         List<MethodHandle> step = new ArrayList<>();
6695         List<MethodHandle> pred = new ArrayList<>();
6696         List<MethodHandle> fini = new ArrayList<>();
6697 
6698         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6699             init.add(clause[0]); // all clauses have at least length 1
6700             step.add(clause.length <= 1 ? null : clause[1]);
6701             pred.add(clause.length <= 2 ? null : clause[2]);
6702             fini.add(clause.length <= 3 ? null : clause[3]);
6703         });
6704 
6705         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6706         final int nclauses = init.size();
6707 
6708         // Step 1A: determine iteration variables (V...).
6709         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6710         for (int i = 0; i < nclauses; ++i) {
6711             MethodHandle in = init.get(i);
6712             MethodHandle st = step.get(i);
6713             if (in == null && st == null) {
6714                 iterationVariableTypes.add(void.class);
6715             } else if (in != null && st != null) {
6716                 loopChecks1a(i, in, st);
6717                 iterationVariableTypes.add(in.type().returnType());
6718             } else {
6719                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6720             }
6721         }
6722         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6723 
6724         // Step 1B: determine loop parameters (A...).
6725         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6726         loopChecks1b(init, commonSuffix);
6727 
6728         // Step 1C: determine loop return type.
6729         // Step 1D: check other types.
6730         // local variable required here; see JDK-8223553
6731         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6732                 .map(MethodType::returnType);
6733         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6734         loopChecks1cd(pred, fini, loopReturnType);
6735 
6736         // Step 2: determine parameter lists.
6737         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6738         commonParameterSequence.addAll(commonSuffix);
6739         loopChecks2(step, pred, fini, commonParameterSequence);
6740         // Step 3: fill in omitted functions.
6741         for (int i = 0; i < nclauses; ++i) {
6742             Class<?> t = iterationVariableTypes.get(i);
6743             if (init.get(i) == null) {
6744                 init.set(i, empty(methodType(t, commonSuffix)));
6745             }
6746             if (step.get(i) == null) {
6747                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6748             }
6749             if (pred.get(i) == null) {
6750                 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
6751             }
6752             if (fini.get(i) == null) {
6753                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6754             }
6755         }
6756 
6757         // Step 4: fill in missing parameter types.
6758         // Also convert all handles to fixed-arity handles.
6759         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6760         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6761         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6762         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6763 
6764         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6765                 allMatch(pl -> pl.equals(commonSuffix));
6766         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6767                 allMatch(pl -> pl.equals(commonParameterSequence));
6768 
6769         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6770     }
6771 
6772     private static void loopChecks0(MethodHandle[][] clauses) {
6773         if (clauses == null || clauses.length == 0) {
6774             throw newIllegalArgumentException("null or no clauses passed");
6775         }
6776         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6777             throw newIllegalArgumentException("null clauses are not allowed");
6778         }
6779         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6780             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6781         }
6782     }
6783 
6784     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6785         if (in.type().returnType() != st.type().returnType()) {
6786             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6787                     st.type().returnType());
6788         }
6789     }
6790 
6791     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6792         final List<Class<?>> empty = List.of();
6793         final List<Class<?>> longest = mhs.filter(Objects::nonNull).
6794                 // take only those that can contribute to a common suffix because they are longer than the prefix
6795                         map(MethodHandle::type).
6796                         filter(t -> t.parameterCount() > skipSize).
6797                         map(MethodType::parameterList).
6798                         reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6799         return longest.isEmpty() ? empty : longest.subList(skipSize, longest.size());
6800     }
6801 
6802     private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) {
6803         final List<Class<?>> empty = List.of();
6804         return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6805     }
6806 
6807     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6808         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6809         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6810         return longestParameterList(List.of(longest1, longest2));
6811     }
6812 
6813     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6814         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6815                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6816             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6817                     " (common suffix: " + commonSuffix + ")");
6818         }
6819     }
6820 
6821     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6822         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6823                 anyMatch(t -> t != loopReturnType)) {
6824             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6825                     loopReturnType + ")");
6826         }
6827 
6828         if (pred.stream().noneMatch(Objects::nonNull)) {
6829             throw newIllegalArgumentException("no predicate found", pred);
6830         }
6831         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6832                 anyMatch(t -> t != boolean.class)) {
6833             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6834         }
6835     }
6836 
6837     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6838         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6839                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6840             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6841                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6842         }
6843     }
6844 
6845     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6846         return hs.stream().map(h -> {
6847             int pc = h.type().parameterCount();
6848             int tpsize = targetParams.size();
6849             return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
6850         }).toList();
6851     }
6852 
6853     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6854         return hs.stream().map(MethodHandle::asFixedArity).toList();
6855     }
6856 
6857     /**
6858      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6859      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6860      * <p>
6861      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6862      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6863      * evaluates to {@code true}).
6864      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6865      * <p>
6866      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6867      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6868      * and updated with the value returned from its invocation. The result of loop execution will be
6869      * the final value of the additional loop-local variable (if present).
6870      * <p>
6871      * The following rules hold for these argument handles:<ul>
6872      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6873      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6874      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6875      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6876      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6877      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6878      * It will constrain the parameter lists of the other loop parts.
6879      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6880      * list {@code (A...)} is called the <em>external parameter list</em>.
6881      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6882      * additional state variable of the loop.
6883      * The body must both accept and return a value of this type {@code V}.
6884      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6885      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6886      * <a href="MethodHandles.html#effid">effectively identical</a>
6887      * to the external parameter list {@code (A...)}.
6888      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6889      * {@linkplain #empty default value}.
6890      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6891      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6892      * effectively identical to the internal parameter list.
6893      * </ul>
6894      * <p>
6895      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6896      * <li>The loop handle's result type is the result type {@code V} of the body.
6897      * <li>The loop handle's parameter types are the types {@code (A...)},
6898      * from the external parameter list.
6899      * </ul>
6900      * <p>
6901      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6902      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6903      * passed to the loop.
6904      * {@snippet lang="java" :
6905      * V init(A...);
6906      * boolean pred(V, A...);
6907      * V body(V, A...);
6908      * V whileLoop(A... a...) {
6909      *   V v = init(a...);
6910      *   while (pred(v, a...)) {
6911      *     v = body(v, a...);
6912      *   }
6913      *   return v;
6914      * }
6915      * }
6916      *
6917      * @apiNote Example:
6918      * {@snippet lang="java" :
6919      * // implement the zip function for lists as a loop handle
6920      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6921      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6922      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6923      *   zip.add(a.next());
6924      *   zip.add(b.next());
6925      *   return zip;
6926      * }
6927      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6928      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6929      * List<String> a = Arrays.asList("a", "b", "c", "d");
6930      * List<String> b = Arrays.asList("e", "f", "g", "h");
6931      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6932      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6933      * }
6934      *
6935      *
6936      * @apiNote The implementation of this method can be expressed as follows:
6937      * {@snippet lang="java" :
6938      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6939      *     MethodHandle fini = (body.type().returnType() == void.class
6940      *                         ? null : identity(body.type().returnType()));
6941      *     MethodHandle[]
6942      *         checkExit = { null, null, pred, fini },
6943      *         varBody   = { init, body };
6944      *     return loop(checkExit, varBody);
6945      * }
6946      * }
6947      *
6948      * @param init optional initializer, providing the initial value of the loop variable.
6949      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6950      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6951      *             above for other constraints.
6952      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6953      *             See above for other constraints.
6954      *
6955      * @return a method handle implementing the {@code while} loop as described by the arguments.
6956      * @throws IllegalArgumentException if the rules for the arguments are violated.
6957      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6958      *
6959      * @see #loop(MethodHandle[][])
6960      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6961      * @since 9
6962      */
6963     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6964         whileLoopChecks(init, pred, body);
6965         MethodHandle fini = identityOrVoid(body.type().returnType());
6966         MethodHandle[] checkExit = { null, null, pred, fini };
6967         MethodHandle[] varBody = { init, body };
6968         return loop(checkExit, varBody);
6969     }
6970 
6971     /**
6972      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
6973      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6974      * <p>
6975      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6976      * method will, in each iteration, first execute its body and then evaluate the predicate.
6977      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
6978      * <p>
6979      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6980      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6981      * and updated with the value returned from its invocation. The result of loop execution will be
6982      * the final value of the additional loop-local variable (if present).
6983      * <p>
6984      * The following rules hold for these argument handles:<ul>
6985      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6986      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6987      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6988      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6989      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6990      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6991      * It will constrain the parameter lists of the other loop parts.
6992      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6993      * list {@code (A...)} is called the <em>external parameter list</em>.
6994      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6995      * additional state variable of the loop.
6996      * The body must both accept and return a value of this type {@code V}.
6997      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6998      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6999      * <a href="MethodHandles.html#effid">effectively identical</a>
7000      * to the external parameter list {@code (A...)}.
7001      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7002      * {@linkplain #empty default value}.
7003      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
7004      * Its parameter list (either empty or of the form {@code (V A*)}) must be
7005      * effectively identical to the internal parameter list.
7006      * </ul>
7007      * <p>
7008      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7009      * <li>The loop handle's result type is the result type {@code V} of the body.
7010      * <li>The loop handle's parameter types are the types {@code (A...)},
7011      * from the external parameter list.
7012      * </ul>
7013      * <p>
7014      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7015      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
7016      * passed to the loop.
7017      * {@snippet lang="java" :
7018      * V init(A...);
7019      * boolean pred(V, A...);
7020      * V body(V, A...);
7021      * V doWhileLoop(A... a...) {
7022      *   V v = init(a...);
7023      *   do {
7024      *     v = body(v, a...);
7025      *   } while (pred(v, a...));
7026      *   return v;
7027      * }
7028      * }
7029      *
7030      * @apiNote Example:
7031      * {@snippet lang="java" :
7032      * // int i = 0; while (i < limit) { ++i; } return i; => limit
7033      * static int zero(int limit) { return 0; }
7034      * static int step(int i, int limit) { return i + 1; }
7035      * static boolean pred(int i, int limit) { return i < limit; }
7036      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
7037      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
7038      * assertEquals(23, loop.invoke(23));
7039      * }
7040      *
7041      *
7042      * @apiNote The implementation of this method can be expressed as follows:
7043      * {@snippet lang="java" :
7044      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7045      *     MethodHandle fini = (body.type().returnType() == void.class
7046      *                         ? null : identity(body.type().returnType()));
7047      *     MethodHandle[] clause = { init, body, pred, fini };
7048      *     return loop(clause);
7049      * }
7050      * }
7051      *
7052      * @param init optional initializer, providing the initial value of the loop variable.
7053      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7054      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7055      *             See above for other constraints.
7056      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7057      *             above for other constraints.
7058      *
7059      * @return a method handle implementing the {@code while} loop as described by the arguments.
7060      * @throws IllegalArgumentException if the rules for the arguments are violated.
7061      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7062      *
7063      * @see #loop(MethodHandle[][])
7064      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
7065      * @since 9
7066      */
7067     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7068         whileLoopChecks(init, pred, body);
7069         MethodHandle fini = identityOrVoid(body.type().returnType());
7070         MethodHandle[] clause = {init, body, pred, fini };
7071         return loop(clause);
7072     }
7073 
7074     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
7075         Objects.requireNonNull(pred);
7076         Objects.requireNonNull(body);
7077         MethodType bodyType = body.type();
7078         Class<?> returnType = bodyType.returnType();
7079         List<Class<?>> innerList = bodyType.parameterList();
7080         List<Class<?>> outerList = innerList;
7081         if (returnType == void.class) {
7082             // OK
7083         } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
7084             // leading V argument missing => error
7085             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7086             throw misMatchedTypes("body function", bodyType, expected);
7087         } else {
7088             outerList = innerList.subList(1, innerList.size());
7089         }
7090         MethodType predType = pred.type();
7091         if (predType.returnType() != boolean.class ||
7092                 !predType.effectivelyIdenticalParameters(0, innerList)) {
7093             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
7094         }
7095         if (init != null) {
7096             MethodType initType = init.type();
7097             if (initType.returnType() != returnType ||
7098                     !initType.effectivelyIdenticalParameters(0, outerList)) {
7099                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7100             }
7101         }
7102     }
7103 
7104     /**
7105      * Constructs a loop that runs a given number of iterations.
7106      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7107      * <p>
7108      * The number of iterations is determined by the {@code iterations} handle evaluation result.
7109      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
7110      * It will be initialized to 0 and incremented by 1 in each iteration.
7111      * <p>
7112      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7113      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7114      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7115      * <p>
7116      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7117      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7118      * iteration variable.
7119      * The result of the loop handle execution will be the final {@code V} value of that variable
7120      * (or {@code void} if there is no {@code V} variable).
7121      * <p>
7122      * The following rules hold for the argument handles:<ul>
7123      * <li>The {@code iterations} handle must not be {@code null}, and must return
7124      * the type {@code int}, referred to here as {@code I} in parameter type lists.
7125      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7126      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7127      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7128      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7129      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7130      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7131      * of types called the <em>internal parameter list</em>.
7132      * It will constrain the parameter lists of the other loop parts.
7133      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7134      * with no additional {@code A} types, then the internal parameter list is extended by
7135      * the argument types {@code A...} of the {@code iterations} handle.
7136      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7137      * list {@code (A...)} is called the <em>external parameter list</em>.
7138      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7139      * additional state variable of the loop.
7140      * The body must both accept a leading parameter and return a value of this type {@code V}.
7141      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7142      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7143      * <a href="MethodHandles.html#effid">effectively identical</a>
7144      * to the external parameter list {@code (A...)}.
7145      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7146      * {@linkplain #empty default value}.
7147      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
7148      * effectively identical to the external parameter list {@code (A...)}.
7149      * </ul>
7150      * <p>
7151      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7152      * <li>The loop handle's result type is the result type {@code V} of the body.
7153      * <li>The loop handle's parameter types are the types {@code (A...)},
7154      * from the external parameter list.
7155      * </ul>
7156      * <p>
7157      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7158      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7159      * arguments passed to the loop.
7160      * {@snippet lang="java" :
7161      * int iterations(A...);
7162      * V init(A...);
7163      * V body(V, int, A...);
7164      * V countedLoop(A... a...) {
7165      *   int end = iterations(a...);
7166      *   V v = init(a...);
7167      *   for (int i = 0; i < end; ++i) {
7168      *     v = body(v, i, a...);
7169      *   }
7170      *   return v;
7171      * }
7172      * }
7173      *
7174      * @apiNote Example with a fully conformant body method:
7175      * {@snippet lang="java" :
7176      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7177      * // => a variation on a well known theme
7178      * static String step(String v, int counter, String init) { return "na " + v; }
7179      * // assume MH_step is a handle to the method above
7180      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
7181      * MethodHandle start = MethodHandles.identity(String.class);
7182      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
7183      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
7184      * }
7185      *
7186      * @apiNote Example with the simplest possible body method type,
7187      * and passing the number of iterations to the loop invocation:
7188      * {@snippet lang="java" :
7189      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7190      * // => a variation on a well known theme
7191      * static String step(String v, int counter ) { return "na " + v; }
7192      * // assume MH_step is a handle to the method above
7193      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
7194      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
7195      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
7196      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
7197      * }
7198      *
7199      * @apiNote Example that treats the number of iterations, string to append to, and string to append
7200      * as loop parameters:
7201      * {@snippet lang="java" :
7202      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7203      * // => a variation on a well known theme
7204      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
7205      * // assume MH_step is a handle to the method above
7206      * MethodHandle count = MethodHandles.identity(int.class);
7207      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
7208      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
7209      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
7210      * }
7211      *
7212      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
7213      * to enforce a loop type:
7214      * {@snippet lang="java" :
7215      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7216      * // => a variation on a well known theme
7217      * static String step(String v, int counter, String pre) { return pre + " " + v; }
7218      * // assume MH_step is a handle to the method above
7219      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
7220      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
7221      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
7222      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
7223      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
7224      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
7225      * }
7226      *
7227      * @apiNote The implementation of this method can be expressed as follows:
7228      * {@snippet lang="java" :
7229      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7230      *     return countedLoop(empty(iterations.type()), iterations, init, body);
7231      * }
7232      * }
7233      *
7234      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
7235      *                   result type must be {@code int}. See above for other constraints.
7236      * @param init optional initializer, providing the initial value of the loop variable.
7237      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7238      * @param body body of the loop, which may not be {@code null}.
7239      *             It controls the loop parameters and result type in the standard case (see above for details).
7240      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7241      *             and may accept any number of additional types.
7242      *             See above for other constraints.
7243      *
7244      * @return a method handle representing the loop.
7245      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7246      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7247      *
7248      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7249      * @since 9
7250      */
7251     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7252         return countedLoop(empty(iterations.type()), iterations, init, body);
7253     }
7254 
7255     /**
7256      * Constructs a loop that counts over a range of numbers.
7257      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7258      * <p>
7259      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7260      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7261      * values of the loop counter.
7262      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7263      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7264      * <p>
7265      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7266      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7267      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7268      * <p>
7269      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7270      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7271      * iteration variable.
7272      * The result of the loop handle execution will be the final {@code V} value of that variable
7273      * (or {@code void} if there is no {@code V} variable).
7274      * <p>
7275      * The following rules hold for the argument handles:<ul>
7276      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7277      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7278      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7279      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7280      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7281      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7282      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7283      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7284      * of types called the <em>internal parameter list</em>.
7285      * It will constrain the parameter lists of the other loop parts.
7286      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7287      * with no additional {@code A} types, then the internal parameter list is extended by
7288      * the argument types {@code A...} of the {@code end} handle.
7289      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7290      * list {@code (A...)} is called the <em>external parameter list</em>.
7291      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7292      * additional state variable of the loop.
7293      * The body must both accept a leading parameter and return a value of this type {@code V}.
7294      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7295      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7296      * <a href="MethodHandles.html#effid">effectively identical</a>
7297      * to the external parameter list {@code (A...)}.
7298      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7299      * {@linkplain #empty default value}.
7300      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7301      * effectively identical to the external parameter list {@code (A...)}.
7302      * <li>Likewise, the parameter list of {@code end} must be effectively identical
7303      * to the external parameter list.
7304      * </ul>
7305      * <p>
7306      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7307      * <li>The loop handle's result type is the result type {@code V} of the body.
7308      * <li>The loop handle's parameter types are the types {@code (A...)},
7309      * from the external parameter list.
7310      * </ul>
7311      * <p>
7312      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7313      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7314      * arguments passed to the loop.
7315      * {@snippet lang="java" :
7316      * int start(A...);
7317      * int end(A...);
7318      * V init(A...);
7319      * V body(V, int, A...);
7320      * V countedLoop(A... a...) {
7321      *   int e = end(a...);
7322      *   int s = start(a...);
7323      *   V v = init(a...);
7324      *   for (int i = s; i < e; ++i) {
7325      *     v = body(v, i, a...);
7326      *   }
7327      *   return v;
7328      * }
7329      * }
7330      *
7331      * @apiNote The implementation of this method can be expressed as follows:
7332      * {@snippet lang="java" :
7333      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7334      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7335      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7336      *     // the following semantics:
7337      *     // MH_increment: (int limit, int counter) -> counter + 1
7338      *     // MH_predicate: (int limit, int counter) -> counter < limit
7339      *     Class<?> counterType = start.type().returnType();  // int
7340      *     Class<?> returnType = body.type().returnType();
7341      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7342      *     if (returnType != void.class) {  // ignore the V variable
7343      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7344      *         pred = dropArguments(pred, 1, returnType);  // ditto
7345      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7346      *     }
7347      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
7348      *     MethodHandle[]
7349      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7350      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
7351      *         indexVar   = { start, incr };           // i = start(); i = i + 1
7352      *     return loop(loopLimit, bodyClause, indexVar);
7353      * }
7354      * }
7355      *
7356      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7357      *              See above for other constraints.
7358      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7359      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
7360      * @param init optional initializer, providing the initial value of the loop variable.
7361      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7362      * @param body body of the loop, which may not be {@code null}.
7363      *             It controls the loop parameters and result type in the standard case (see above for details).
7364      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7365      *             and may accept any number of additional types.
7366      *             See above for other constraints.
7367      *
7368      * @return a method handle representing the loop.
7369      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7370      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7371      *
7372      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7373      * @since 9
7374      */
7375     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7376         countedLoopChecks(start, end, init, body);
7377         Class<?> counterType = start.type().returnType();  // int, but who's counting?
7378         Class<?> limitType   = end.type().returnType();    // yes, int again
7379         Class<?> returnType  = body.type().returnType();
7380         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7381         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7382         MethodHandle retv = null;
7383         if (returnType != void.class) {
7384             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7385             pred = dropArguments(pred, 1, returnType);  // ditto
7386             retv = dropArguments(identity(returnType), 0, counterType);
7387         }
7388         body = dropArguments(body, 0, counterType);  // ignore the limit variable
7389         MethodHandle[]
7390             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7391             bodyClause = { init, body },            // v = init(); v = body(v, i)
7392             indexVar   = { start, incr };           // i = start(); i = i + 1
7393         return loop(loopLimit, bodyClause, indexVar);
7394     }
7395 
7396     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7397         Objects.requireNonNull(start);
7398         Objects.requireNonNull(end);
7399         Objects.requireNonNull(body);
7400         Class<?> counterType = start.type().returnType();
7401         if (counterType != int.class) {
7402             MethodType expected = start.type().changeReturnType(int.class);
7403             throw misMatchedTypes("start function", start.type(), expected);
7404         } else if (end.type().returnType() != counterType) {
7405             MethodType expected = end.type().changeReturnType(counterType);
7406             throw misMatchedTypes("end function", end.type(), expected);
7407         }
7408         MethodType bodyType = body.type();
7409         Class<?> returnType = bodyType.returnType();
7410         List<Class<?>> innerList = bodyType.parameterList();
7411         // strip leading V value if present
7412         int vsize = (returnType == void.class ? 0 : 1);
7413         if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7414             // argument list has no "V" => error
7415             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7416             throw misMatchedTypes("body function", bodyType, expected);
7417         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7418             // missing I type => error
7419             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7420             throw misMatchedTypes("body function", bodyType, expected);
7421         }
7422         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7423         if (outerList.isEmpty()) {
7424             // special case; take lists from end handle
7425             outerList = end.type().parameterList();
7426             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7427         }
7428         MethodType expected = methodType(counterType, outerList);
7429         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7430             throw misMatchedTypes("start parameter types", start.type(), expected);
7431         }
7432         if (end.type() != start.type() &&
7433             !end.type().effectivelyIdenticalParameters(0, outerList)) {
7434             throw misMatchedTypes("end parameter types", end.type(), expected);
7435         }
7436         if (init != null) {
7437             MethodType initType = init.type();
7438             if (initType.returnType() != returnType ||
7439                 !initType.effectivelyIdenticalParameters(0, outerList)) {
7440                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7441             }
7442         }
7443     }
7444 
7445     /**
7446      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7447      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7448      * <p>
7449      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7450      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7451      * <p>
7452      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7453      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7454      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7455      * <p>
7456      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7457      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7458      * iteration variable.
7459      * The result of the loop handle execution will be the final {@code V} value of that variable
7460      * (or {@code void} if there is no {@code V} variable).
7461      * <p>
7462      * The following rules hold for the argument handles:<ul>
7463      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7464      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7465      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7466      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7467      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7468      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7469      * of types called the <em>internal parameter list</em>.
7470      * It will constrain the parameter lists of the other loop parts.
7471      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7472      * with no additional {@code A} types, then the internal parameter list is extended by
7473      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7474      * single type {@code Iterable} is added and constitutes the {@code A...} list.
7475      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7476      * list {@code (A...)} is called the <em>external parameter list</em>.
7477      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7478      * additional state variable of the loop.
7479      * The body must both accept a leading parameter and return a value of this type {@code V}.
7480      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7481      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7482      * <a href="MethodHandles.html#effid">effectively identical</a>
7483      * to the external parameter list {@code (A...)}.
7484      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7485      * {@linkplain #empty default value}.
7486      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7487      * type {@code java.util.Iterator} or a subtype thereof.
7488      * The iterator it produces when the loop is executed will be assumed
7489      * to yield values which can be converted to type {@code T}.
7490      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7491      * effectively identical to the external parameter list {@code (A...)}.
7492      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7493      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7494      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7495      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7496      * the {@link MethodHandle#asType asType} conversion method.
7497      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7498      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7499      * </ul>
7500      * <p>
7501      * The type {@code T} may be either a primitive or reference.
7502      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7503      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7504      * as if by the {@link MethodHandle#asType asType} conversion method.
7505      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7506      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7507      * <p>
7508      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7509      * <li>The loop handle's result type is the result type {@code V} of the body.
7510      * <li>The loop handle's parameter types are the types {@code (A...)},
7511      * from the external parameter list.
7512      * </ul>
7513      * <p>
7514      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7515      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7516      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7517      * {@snippet lang="java" :
7518      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7519      * V init(A...);
7520      * V body(V,T,A...);
7521      * V iteratedLoop(A... a...) {
7522      *   Iterator<T> it = iterator(a...);
7523      *   V v = init(a...);
7524      *   while (it.hasNext()) {
7525      *     T t = it.next();
7526      *     v = body(v, t, a...);
7527      *   }
7528      *   return v;
7529      * }
7530      * }
7531      *
7532      * @apiNote Example:
7533      * {@snippet lang="java" :
7534      * // get an iterator from a list
7535      * static List<String> reverseStep(List<String> r, String e) {
7536      *   r.add(0, e);
7537      *   return r;
7538      * }
7539      * static List<String> newArrayList() { return new ArrayList<>(); }
7540      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7541      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7542      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7543      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7544      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7545      * }
7546      *
7547      * @apiNote The implementation of this method can be expressed approximately as follows:
7548      * {@snippet lang="java" :
7549      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7550      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7551      *     Class<?> returnType = body.type().returnType();
7552      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7553      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7554      *     MethodHandle retv = null, step = body, startIter = iterator;
7555      *     if (returnType != void.class) {
7556      *         // the simple thing first:  in (I V A...), drop the I to get V
7557      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7558      *         // body type signature (V T A...), internal loop types (I V A...)
7559      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7560      *     }
7561      *     if (startIter == null)  startIter = MH_getIter;
7562      *     MethodHandle[]
7563      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7564      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7565      *     return loop(iterVar, bodyClause);
7566      * }
7567      * }
7568      *
7569      * @param iterator an optional handle to return the iterator to start the loop.
7570      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7571      *                 See above for other constraints.
7572      * @param init optional initializer, providing the initial value of the loop variable.
7573      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7574      * @param body body of the loop, which may not be {@code null}.
7575      *             It controls the loop parameters and result type in the standard case (see above for details).
7576      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7577      *             and may accept any number of additional types.
7578      *             See above for other constraints.
7579      *
7580      * @return a method handle embodying the iteration loop functionality.
7581      * @throws NullPointerException if the {@code body} handle is {@code null}.
7582      * @throws IllegalArgumentException if any argument violates the above requirements.
7583      *
7584      * @since 9
7585      */
7586     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7587         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7588         Class<?> returnType = body.type().returnType();
7589         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7590         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7591         MethodHandle startIter;
7592         MethodHandle nextVal;
7593         {
7594             MethodType iteratorType;
7595             if (iterator == null) {
7596                 // derive argument type from body, if available, else use Iterable
7597                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7598                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7599             } else {
7600                 // force return type to the internal iterator class
7601                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7602                 startIter = iterator;
7603             }
7604             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7605             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7606 
7607             // perform the asType transforms under an exception transformer, as per spec.:
7608             try {
7609                 startIter = startIter.asType(iteratorType);
7610                 nextVal = nextRaw.asType(nextValType);
7611             } catch (WrongMethodTypeException ex) {
7612                 throw new IllegalArgumentException(ex);
7613             }
7614         }
7615 
7616         MethodHandle retv = null, step = body;
7617         if (returnType != void.class) {
7618             // the simple thing first:  in (I V A...), drop the I to get V
7619             retv = dropArguments(identity(returnType), 0, Iterator.class);
7620             // body type signature (V T A...), internal loop types (I V A...)
7621             step = swapArguments(body, 0, 1);  // swap V <-> T
7622         }
7623 
7624         MethodHandle[]
7625             iterVar    = { startIter, null, hasNext, retv },
7626             bodyClause = { init, filterArgument(step, 0, nextVal) };
7627         return loop(iterVar, bodyClause);
7628     }
7629 
7630     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7631         Objects.requireNonNull(body);
7632         MethodType bodyType = body.type();
7633         Class<?> returnType = bodyType.returnType();
7634         List<Class<?>> internalParamList = bodyType.parameterList();
7635         // strip leading V value if present
7636         int vsize = (returnType == void.class ? 0 : 1);
7637         if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7638             // argument list has no "V" => error
7639             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7640             throw misMatchedTypes("body function", bodyType, expected);
7641         } else if (internalParamList.size() <= vsize) {
7642             // missing T type => error
7643             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7644             throw misMatchedTypes("body function", bodyType, expected);
7645         }
7646         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7647         Class<?> iterableType = null;
7648         if (iterator != null) {
7649             // special case; if the body handle only declares V and T then
7650             // the external parameter list is obtained from iterator handle
7651             if (externalParamList.isEmpty()) {
7652                 externalParamList = iterator.type().parameterList();
7653             }
7654             MethodType itype = iterator.type();
7655             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7656                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7657             }
7658             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7659                 MethodType expected = methodType(itype.returnType(), externalParamList);
7660                 throw misMatchedTypes("iterator parameters", itype, expected);
7661             }
7662         } else {
7663             if (externalParamList.isEmpty()) {
7664                 // special case; if the iterator handle is null and the body handle
7665                 // only declares V and T then the external parameter list consists
7666                 // of Iterable
7667                 externalParamList = List.of(Iterable.class);
7668                 iterableType = Iterable.class;
7669             } else {
7670                 // special case; if the iterator handle is null and the external
7671                 // parameter list is not empty then the first parameter must be
7672                 // assignable to Iterable
7673                 iterableType = externalParamList.get(0);
7674                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7675                     throw newIllegalArgumentException(
7676                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7677                 }
7678             }
7679         }
7680         if (init != null) {
7681             MethodType initType = init.type();
7682             if (initType.returnType() != returnType ||
7683                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7684                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7685             }
7686         }
7687         return iterableType;  // help the caller a bit
7688     }
7689 
7690     /*non-public*/
7691     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7692         // there should be a better way to uncross my wires
7693         int arity = mh.type().parameterCount();
7694         int[] order = new int[arity];
7695         for (int k = 0; k < arity; k++)  order[k] = k;
7696         order[i] = j; order[j] = i;
7697         Class<?>[] types = mh.type().parameterArray();
7698         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7699         MethodType swapType = methodType(mh.type().returnType(), types);
7700         return permuteArguments(mh, swapType, order);
7701     }
7702 
7703     /**
7704      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7705      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7706      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7707      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7708      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7709      * {@code try-finally} handle.
7710      * <p>
7711      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7712      * The first is the exception thrown during the
7713      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7714      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7715      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7716      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7717      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7718      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7719      * <p>
7720      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7721      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7722      * two extra leading parameters:<ul>
7723      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7724      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7725      * the result from the execution of the {@code target} handle.
7726      * This parameter is not present if the {@code target} returns {@code void}.
7727      * </ul>
7728      * <p>
7729      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7730      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7731      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7732      * the cleanup.
7733      * {@snippet lang="java" :
7734      * V target(A..., B...);
7735      * V cleanup(Throwable, V, A...);
7736      * V adapter(A... a, B... b) {
7737      *   V result = (zero value for V);
7738      *   Throwable throwable = null;
7739      *   try {
7740      *     result = target(a..., b...);
7741      *   } catch (Throwable t) {
7742      *     throwable = t;
7743      *     throw t;
7744      *   } finally {
7745      *     result = cleanup(throwable, result, a...);
7746      *   }
7747      *   return result;
7748      * }
7749      * }
7750      * <p>
7751      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7752      * be modified by execution of the target, and so are passed unchanged
7753      * from the caller to the cleanup, if it is invoked.
7754      * <p>
7755      * The target and cleanup must return the same type, even if the cleanup
7756      * always throws.
7757      * To create such a throwing cleanup, compose the cleanup logic
7758      * with {@link #throwException throwException},
7759      * in order to create a method handle of the correct return type.
7760      * <p>
7761      * Note that {@code tryFinally} never converts exceptions into normal returns.
7762      * In rare cases where exceptions must be converted in that way, first wrap
7763      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7764      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7765      * <p>
7766      * It is recommended that the first parameter type of {@code cleanup} be
7767      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7768      * {@code cleanup} will always be invoked with whatever exception that
7769      * {@code target} throws.  Declaring a narrower type may result in a
7770      * {@code ClassCastException} being thrown by the {@code try-finally}
7771      * handle if the type of the exception thrown by {@code target} is not
7772      * assignable to the first parameter type of {@code cleanup}.  Note that
7773      * various exception types of {@code VirtualMachineError},
7774      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7775      * thrown by almost any kind of Java code, and a finally clause that
7776      * catches (say) only {@code IOException} would mask any of the others
7777      * behind a {@code ClassCastException}.
7778      *
7779      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7780      * @param cleanup the handle that is invoked in the finally block.
7781      *
7782      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7783      * @throws NullPointerException if any argument is null
7784      * @throws IllegalArgumentException if {@code cleanup} does not accept
7785      *          the required leading arguments, or if the method handle types do
7786      *          not match in their return types and their
7787      *          corresponding trailing parameters
7788      *
7789      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7790      * @since 9
7791      */
7792     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7793         Class<?>[] targetParamTypes = target.type().ptypes();
7794         Class<?> rtype = target.type().returnType();
7795 
7796         tryFinallyChecks(target, cleanup);
7797 
7798         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7799         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7800         // target parameter list.
7801         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false);
7802 
7803         // Ensure that the intrinsic type checks the instance thrown by the
7804         // target against the first parameter of cleanup
7805         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7806 
7807         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7808         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7809     }
7810 
7811     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7812         Class<?> rtype = target.type().returnType();
7813         if (rtype != cleanup.type().returnType()) {
7814             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7815         }
7816         MethodType cleanupType = cleanup.type();
7817         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7818             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7819         }
7820         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7821             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7822         }
7823         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7824         // target parameter list.
7825         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7826         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7827             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7828                     cleanup.type(), target.type());
7829         }
7830     }
7831 
7832     /**
7833      * Creates a table switch method handle, which can be used to switch over a set of target
7834      * method handles, based on a given target index, called selector.
7835      * <p>
7836      * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7837      * and where {@code N} is the number of target method handles, the table switch method
7838      * handle will invoke the n-th target method handle from the list of target method handles.
7839      * <p>
7840      * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7841      * method handle will invoke the given fallback method handle.
7842      * <p>
7843      * All method handles passed to this method must have the same type, with the additional
7844      * requirement that the leading parameter be of type {@code int}. The leading parameter
7845      * represents the selector.
7846      * <p>
7847      * Any trailing parameters present in the type will appear on the returned table switch
7848      * method handle as well. Any arguments assigned to these parameters will be forwarded,
7849      * together with the selector value, to the selected method handle when invoking it.
7850      *
7851      * @apiNote Example:
7852      * The cases each drop the {@code selector} value they are given, and take an additional
7853      * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7854      * to a specific constant label string for each case:
7855      * {@snippet lang="java" :
7856      * MethodHandles.Lookup lookup = MethodHandles.lookup();
7857      * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7858      *         MethodType.methodType(String.class, String.class));
7859      * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7860      *
7861      * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7862      * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7863      * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7864      *
7865      * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7866      *     caseDefault,
7867      *     case0,
7868      *     case1
7869      * );
7870      *
7871      * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7872      * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7873      * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7874      * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7875      * }
7876      *
7877      * @param fallback the fallback method handle that is called when the selector is not
7878      *                 within the range {@code [0, N)}.
7879      * @param targets array of target method handles.
7880      * @return the table switch method handle.
7881      * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7882      *                              any of the elements of the {@code targets} array are
7883      *                              {@code null}.
7884      * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7885      *                                  parameter of the fallback handle or any of the target
7886      *                                  handles is not {@code int}, or if the types of
7887      *                                  the fallback handle and all of target handles are
7888      *                                  not the same.
7889      */
7890     public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7891         Objects.requireNonNull(fallback);
7892         Objects.requireNonNull(targets);
7893         targets = targets.clone();
7894         MethodType type = tableSwitchChecks(fallback, targets);
7895         return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7896     }
7897 
7898     private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7899         if (caseActions.length == 0)
7900             throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7901 
7902         MethodType expectedType = defaultCase.type();
7903 
7904         if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7905             throw new IllegalArgumentException(
7906                 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7907 
7908         for (MethodHandle mh : caseActions) {
7909             Objects.requireNonNull(mh);
7910             if (mh.type() != expectedType)
7911                 throw new IllegalArgumentException(
7912                     "Case actions must have the same type: " + Arrays.toString(caseActions));
7913         }
7914 
7915         return expectedType;
7916     }
7917 
7918     /**
7919      * Creates a var handle object, which can be used to dereference a {@linkplain java.lang.foreign.MemorySegment memory segment}
7920      * by viewing its contents as a sequence of the provided value layout.
7921      *
7922      * <p>The provided layout specifies the {@linkplain ValueLayout#carrier() carrier type},
7923      * the {@linkplain ValueLayout#byteSize() byte size},
7924      * the {@linkplain ValueLayout#byteAlignment() byte alignment} and the {@linkplain ValueLayout#order() byte order}
7925      * associated with the returned var handle.
7926      *
7927      * <p>The returned var handle's type is {@code carrier} and the list of coordinate types is
7928      * {@code (MemorySegment, long)}, where the {@code long} coordinate type corresponds to byte offset into
7929      * a given memory segment. The returned var handle accesses bytes at an offset in a given
7930      * memory segment, composing bytes to or from a value of the type {@code carrier} according to the given endianness;
7931      * the alignment constraint (in bytes) for the resulting var handle is given by {@code alignmentBytes}.
7932      *
7933      * <p>As an example, consider the memory layout expressed by a {@link GroupLayout} instance constructed as follows:
7934      * {@snippet lang="java" :
7935      *     GroupLayout seq = java.lang.foreign.MemoryLayout.structLayout(
7936      *             MemoryLayout.paddingLayout(32),
7937      *             ValueLayout.JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN).withName("value")
7938      *     );
7939      * }
7940      * To access the member layout named {@code value}, we can construct a memory segment view var handle as follows:
7941      * {@snippet lang="java" :
7942      *     VarHandle handle = MethodHandles.memorySegmentViewVarHandle(ValueLayout.JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN)); //(MemorySegment, long) -> int
7943      *     handle = MethodHandles.insertCoordinates(handle, 1, 4); //(MemorySegment) -> int
7944      * }
7945      *
7946      * @apiNote The resulting var handle features certain <i>access mode restrictions</i>,
7947      * which are common to all memory segment view var handles. A memory segment view var handle is associated
7948      * with an access size {@code S} and an alignment constraint {@code B}
7949      * (both expressed in bytes). We say that a memory access operation is <em>fully aligned</em> if it occurs
7950      * at a memory address {@code A} which is compatible with both alignment constraints {@code S} and {@code B}.
7951      * If access is fully aligned then following access modes are supported and are
7952      * guaranteed to support atomic access:
7953      * <ul>
7954      * <li>read write access modes for all {@code T}, with the exception of
7955      *     access modes {@code get} and {@code set} for {@code long} and
7956      *     {@code double} on 32-bit platforms.
7957      * <li>atomic update access modes for {@code int}, {@code long},
7958      *     {@code float}, {@code double} or {@link MemoryAddress}.
7959      *     (Future major platform releases of the JDK may support additional
7960      *     types for certain currently unsupported access modes.)
7961      * <li>numeric atomic update access modes for {@code int}, {@code long} and {@link MemoryAddress}.
7962      *     (Future major platform releases of the JDK may support additional
7963      *     numeric types for certain currently unsupported access modes.)
7964      * <li>bitwise atomic update access modes for {@code int}, {@code long} and {@link MemoryAddress}.
7965      *     (Future major platform releases of the JDK may support additional
7966      *     numeric types for certain currently unsupported access modes.)
7967      * </ul>
7968      *
7969      * If {@code T} is {@code float}, {@code double} or {@link MemoryAddress} then atomic
7970      * update access modes compare values using their bitwise representation
7971      * (see {@link Float#floatToRawIntBits},
7972      * {@link Double#doubleToRawLongBits} and {@link MemoryAddress#toRawLongValue()}, respectively).
7973      * <p>
7974      * Alternatively, a memory access operation is <em>partially aligned</em> if it occurs at a memory address {@code A}
7975      * which is only compatible with the alignment constraint {@code B}; in such cases, access for anything other than the
7976      * {@code get} and {@code set} access modes will result in an {@code IllegalStateException}. If access is partially aligned,
7977      * atomic access is only guaranteed with respect to the largest power of two that divides the GCD of {@code A} and {@code S}.
7978      * <p>
7979      * Finally, in all other cases, we say that a memory access operation is <em>misaligned</em>; in such cases an
7980      * {@code IllegalStateException} is thrown, irrespective of the access mode being used.
7981      *
7982      * @param layout the value layout for which a memory access handle is to be obtained.
7983      * @return the new memory segment view var handle.
7984      * @throws IllegalArgumentException if an illegal carrier type is used, or if {@code alignmentBytes} is not a power of two.
7985      * @throws NullPointerException if {@code layout} is {@code null}.
7986      * @see MemoryLayout#varHandle(MemoryLayout.PathElement...)
7987      * @since 19
7988      */
7989     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
7990     public static VarHandle memorySegmentViewVarHandle(ValueLayout layout) {
7991         Objects.requireNonNull(layout);
7992         return Utils.makeSegmentViewVarHandle(layout);
7993     }
7994 
7995     /**
7996      * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions.
7997      * <p>
7998      * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where
7999      * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed
8000      * to the target var handle.
8001      * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from
8002      * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function)
8003      * is processed using the second filter and returned to the caller. More advanced access mode types, such as
8004      * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time.
8005      * <p>
8006      * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and
8007      * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case,
8008      * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which
8009      * will be appended to the coordinates of the target var handle).
8010      * <p>
8011      * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will
8012      * throw an {@link IllegalStateException}.
8013      * <p>
8014      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8015      * atomic access guarantees as those featured by the target var handle.
8016      *
8017      * @param target the target var handle
8018      * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target}
8019      * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S}
8020      * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions.
8021      * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types
8022      * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle,
8023      * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions.
8024      * @throws NullPointerException if any of the arguments is {@code null}.
8025      * @since 19
8026      */
8027     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8028     public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
8029         return VarHandles.filterValue(target, filterToTarget, filterFromTarget);
8030     }
8031 
8032     /**
8033      * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions.
8034      * <p>
8035      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values
8036      * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types
8037      * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the
8038      * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered
8039      * by the adaptation) to the target var handle.
8040      * <p>
8041      * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn},
8042      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
8043      * <p>
8044      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8045      * throw an {@link IllegalStateException}.
8046      * <p>
8047      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8048      * atomic access guarantees as those featured by the target var handle.
8049      *
8050      * @param target the target var handle
8051      * @param pos the position of the first coordinate to be transformed
8052      * @param filters the unary functions which are used to transform coordinates starting at position {@code pos}
8053      * @return an adapter var handle which accepts new coordinate types, applying the provided transformation
8054      * to the new coordinate values.
8055      * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types
8056      * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting
8057      * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8058      * or if more filters are provided than the actual number of coordinate types available starting at {@code pos},
8059      * or if it's determined that any of the filters throws any checked exceptions.
8060      * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}.
8061      * @since 19
8062      */
8063     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8064     public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
8065         return VarHandles.filterCoordinates(target, pos, filters);
8066     }
8067 
8068     /**
8069      * Provides a target var handle with one or more <em>bound coordinates</em>
8070      * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less
8071      * coordinate types than the target var handle.
8072      * <p>
8073      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values
8074      * are joined with bound coordinate values, and then passed to the target var handle.
8075      * <p>
8076      * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn },
8077      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
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 var handle to invoke after the bound coordinates are inserted
8083      * @param pos the position of the first coordinate to be inserted
8084      * @param values the series of bound coordinates to insert
8085      * @return an adapter var handle which inserts additional coordinates,
8086      *         before calling the target var handle
8087      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8088      * or if more values are provided than the actual number of coordinate types available starting at {@code pos}.
8089      * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types
8090      * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos}
8091      * of the target var handle.
8092      * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}.
8093      * @since 19
8094      */
8095     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8096     public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
8097         return VarHandles.insertCoordinates(target, pos, values);
8098     }
8099 
8100     /**
8101      * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them
8102      * so that the new coordinates match the provided ones.
8103      * <p>
8104      * The given array controls the reordering.
8105      * Call {@code #I} the number of incoming coordinates (the value
8106      * {@code newCoordinates.size()}), and call {@code #O} the number
8107      * of outgoing coordinates (the number of coordinates associated with the target var handle).
8108      * Then the length of the reordering array must be {@code #O},
8109      * and each element must be a non-negative number less than {@code #I}.
8110      * For every {@code N} less than {@code #O}, the {@code N}-th
8111      * outgoing coordinate will be taken from the {@code I}-th incoming
8112      * coordinate, where {@code I} is {@code reorder[N]}.
8113      * <p>
8114      * No coordinate value conversions are applied.
8115      * The type of each incoming coordinate, as determined by {@code newCoordinates},
8116      * must be identical to the type of the corresponding outgoing coordinate
8117      * in the target var handle.
8118      * <p>
8119      * The reordering array need not specify an actual permutation.
8120      * An incoming coordinate will be duplicated if its index appears
8121      * more than once in the array, and an incoming coordinate will be dropped
8122      * if its index does not appear in the array.
8123      * <p>
8124      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8125      * atomic access guarantees as those featured by the target var handle.
8126      * @param target the var handle to invoke after the coordinates have been reordered
8127      * @param newCoordinates the new coordinate types
8128      * @param reorder an index array which controls the reordering
8129      * @return an adapter var handle which re-arranges the incoming coordinate values,
8130      * before calling the target var handle
8131      * @throws IllegalArgumentException if the index array length is not equal to
8132      * the number of coordinates of the target var handle, or if any index array element is not a valid index for
8133      * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in
8134      * the target var handle and in {@code newCoordinates} are not identical.
8135      * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}.
8136      * @since 19
8137      */
8138     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8139     public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
8140         return VarHandles.permuteCoordinates(target, newCoordinates, reorder);
8141     }
8142 
8143     /**
8144      * Adapts a target var handle by pre-processing
8145      * a sub-sequence of its coordinate values with a filter (a method handle).
8146      * The pre-processed coordinates are replaced by the result (if any) of the
8147      * filter function and the target var handle is then called on the modified (usually shortened)
8148      * coordinate list.
8149      * <p>
8150      * If {@code R} is the return type of the filter (which cannot be void), the target var handle must accept a value of
8151      * type {@code R} as its coordinate in position {@code pos}, preceded and/or followed by
8152      * any coordinate not passed to the filter.
8153      * No coordinates are reordered, and the result returned from the filter
8154      * replaces (in order) the whole subsequence of coordinates originally
8155      * passed to the adapter.
8156      * <p>
8157      * The argument types (if any) of the filter
8158      * replace zero or one coordinate types of the target var handle, at position {@code pos},
8159      * in the resulting adapted var handle.
8160      * The return type of the filter must be identical to the
8161      * coordinate type of the target var handle at position {@code pos}, and that target var handle
8162      * coordinate is supplied by the return value of the filter.
8163      * <p>
8164      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8165      * throw an {@link IllegalStateException}.
8166      * <p>
8167      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8168      * atomic access guarantees as those featured by the target var handle.
8169      *
8170      * @param target the var handle to invoke after the coordinates have been filtered
8171      * @param pos the position of the coordinate to be filtered
8172      * @param filter the filter method handle
8173      * @return an adapter var handle which filters the incoming coordinate values,
8174      * before calling the target var handle
8175      * @throws IllegalArgumentException if the return type of {@code filter}
8176      * is void, or it is not the same as the {@code pos} coordinate of the target var handle,
8177      * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8178      * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>,
8179      * or if it's determined that {@code filter} throws any checked exceptions.
8180      * @throws NullPointerException if any of the arguments is {@code null}.
8181      * @since 19
8182      */
8183     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8184     public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
8185         return VarHandles.collectCoordinates(target, pos, filter);
8186     }
8187 
8188     /**
8189      * Returns a var handle which will discard some dummy coordinates before delegating to the
8190      * target var handle. As a consequence, the resulting var handle will feature more
8191      * coordinate types than the target var handle.
8192      * <p>
8193      * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the
8194      * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede
8195      * the target's real arguments; if {@code pos} is <i>N</i> they will come after.
8196      * <p>
8197      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8198      * atomic access guarantees as those featured by the target var handle.
8199      *
8200      * @param target the var handle to invoke after the dummy coordinates are dropped
8201      * @param pos position of the first coordinate to drop (zero for the leftmost)
8202      * @param valueTypes the type(s) of the coordinate(s) to drop
8203      * @return an adapter var handle which drops some dummy coordinates,
8204      *         before calling the target var handle
8205      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive.
8206      * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}.
8207      * @since 19
8208      */
8209     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8210     public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
8211         return VarHandles.dropCoordinates(target, pos, valueTypes);
8212     }
8213 }