1 /*
   2  * Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import jdk.internal.access.SharedSecrets;
  29 import jdk.internal.misc.Unsafe;
  30 import jdk.internal.misc.VM;
  31 import jdk.internal.org.objectweb.asm.ClassReader;
  32 import jdk.internal.org.objectweb.asm.Opcodes;
  33 import jdk.internal.org.objectweb.asm.Type;
  34 import jdk.internal.reflect.CallerSensitive;
  35 import jdk.internal.reflect.Reflection;
  36 import jdk.internal.vm.annotation.ForceInline;
  37 import sun.invoke.util.ValueConversions;
  38 import sun.invoke.util.VerifyAccess;
  39 import sun.invoke.util.Wrapper;
  40 import sun.reflect.misc.ReflectUtil;
  41 import sun.security.util.SecurityConstants;
  42 
  43 import java.lang.constant.ConstantDescs;
  44 import java.lang.invoke.LambdaForm.BasicType;
  45 import java.lang.reflect.Constructor;
  46 import java.lang.reflect.Field;
  47 import java.lang.reflect.Member;
  48 import java.lang.reflect.Method;
  49 import java.lang.reflect.Modifier;
  50 import java.lang.reflect.ReflectPermission;
  51 import java.nio.ByteOrder;
  52 import java.security.ProtectionDomain;
  53 import java.util.ArrayList;
  54 import java.util.Arrays;
  55 import java.util.BitSet;
  56 import java.util.Iterator;
  57 import java.util.List;
  58 import java.util.Objects;
  59 import java.util.Set;
  60 import java.util.concurrent.ConcurrentHashMap;
  61 import java.util.stream.Stream;
  62 
  63 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
  64 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  65 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  66 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  67 import static java.lang.invoke.MethodType.methodType;
  68 
  69 /**
  70  * This class consists exclusively of static methods that operate on or return
  71  * method handles. They fall into several categories:
  72  * <ul>
  73  * <li>Lookup methods which help create method handles for methods and fields.
  74  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  75  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  76  * </ul>
  77  * A lookup, combinator, or factory method will fail and throw an
  78  * {@code IllegalArgumentException} if the created method handle's type
  79  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  80  *
  81  * @author John Rose, JSR 292 EG
  82  * @since 1.7
  83  */
  84 public class MethodHandles {
  85 
  86     private MethodHandles() { }  // do not instantiate
  87 
  88     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  89 
  90     // See IMPL_LOOKUP below.
  91 
  92     //// Method handle creation from ordinary methods.
  93 
  94     /**
  95      * Returns a {@link Lookup lookup object} with
  96      * full capabilities to emulate all supported bytecode behaviors of the caller.
  97      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
  98      * Factory methods on the lookup object can create
  99      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
 100      * for any member that the caller has access to via bytecodes,
 101      * including protected and private fields and methods.
 102      * This lookup object is created by the original lookup class
 103      * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
 104      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 105      * Do not store it in place where untrusted code can access it.
 106      * <p>
 107      * This method is caller sensitive, which means that it may return different
 108      * values to different callers.
 109      * @return a lookup object for the caller of this method, with
 110      * {@linkplain Lookup#ORIGINAL original} and
 111      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
 112      */
 113     @CallerSensitive
 114     @ForceInline // to ensure Reflection.getCallerClass optimization
 115     public static Lookup lookup() {
 116         return new Lookup(Reflection.getCallerClass());
 117     }
 118 
 119     /**
 120      * This reflected$lookup method is the alternate implementation of
 121      * the lookup method when being invoked by reflection.
 122      */
 123     @CallerSensitive
 124     private static Lookup reflected$lookup() {
 125         Class<?> caller = Reflection.getCallerClass();
 126         if (caller.getClassLoader() == null) {
 127             throw newIllegalArgumentException("illegal lookupClass: "+caller);
 128         }
 129         return new Lookup(caller);
 130     }
 131 
 132     /**
 133      * Returns a {@link Lookup lookup object} which is trusted minimally.
 134      * The lookup has the {@code UNCONDITIONAL} mode.
 135      * It can only be used to create method handles to public members of
 136      * public classes in packages that are exported unconditionally.
 137      * <p>
 138      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 139      * of this lookup object will be {@link java.lang.Object}.
 140      *
 141      * @apiNote The use of Object is conventional, and because the lookup modes are
 142      * limited, there is no special access provided to the internals of Object, its package
 143      * or its module.  This public lookup object or other lookup object with
 144      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 145      * is not used to determine the lookup context.
 146      *
 147      * <p style="font-size:smaller;">
 148      * <em>Discussion:</em>
 149      * The lookup class can be changed to any other class {@code C} using an expression of the form
 150      * {@link Lookup#in publicLookup().in(C.class)}.
 151      * A public lookup object is always subject to
 152      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 153      * Also, it cannot access
 154      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 155      * @return a lookup object which is trusted minimally
 156      *
 157      * @revised 9
 158      */
 159     public static Lookup publicLookup() {
 160         return Lookup.PUBLIC_LOOKUP;
 161     }
 162 
 163     /**
 164      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 165      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 166      * The returned lookup object can provide access to classes in modules and packages,
 167      * and members of those classes, outside the normal rules of Java access control,
 168      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 169      * <p>
 170      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 171      * allowed to do deep reflection on module {@code M2} and package of the target class
 172      * if and only if all of the following conditions are {@code true}:
 173      * <ul>
 174      * <li>If there is a security manager, its {@code checkPermission} method is
 175      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 176      * that must return normally.
 177      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 178      * full privilege access}.  Specifically:
 179      *   <ul>
 180      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 181      *         (This is because otherwise there would be no way to ensure the original lookup
 182      *         creator was a member of any particular module, and so any subsequent checks
 183      *         for readability and qualified exports would become ineffective.)
 184      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 185      *         (This is because an application intending to share intra-module access
 186      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 187      *         deep reflection to its own module.)
 188      *   </ul>
 189      * <li>The target class must be a proper class, not a primitive or array class.
 190      * (Thus, {@code M2} is well-defined.)
 191      * <li>If the caller module {@code M1} differs from
 192      * the target module {@code M2} then both of the following must be true:
 193      *   <ul>
 194      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 195      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 196      *         containing the target class to at least {@code M1}.</li>
 197      *   </ul>
 198      * </ul>
 199      * <p>
 200      * If any of the above checks is violated, this method fails with an
 201      * exception.
 202      * <p>
 203      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 204      * returns a {@code Lookup} on {@code targetClass} with
 205      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 206      * with {@code null} previous lookup class.
 207      * <p>
 208      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 209      * returns a {@code Lookup} on {@code targetClass} that records
 210      * the lookup class of the caller as the new previous lookup class with
 211      * {@code PRIVATE} access but no {@code MODULE} access.
 212      * <p>
 213      * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
 214      *
 215      * @param targetClass the target class
 216      * @param caller the caller lookup object
 217      * @return a lookup object for the target class, with private access
 218      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 219      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 220      * @throws SecurityException if denied by the security manager
 221      * @throws IllegalAccessException if any of the other access checks specified above fails
 222      * @since 9
 223      * @see Lookup#dropLookupMode
 224      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 225      */
 226     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 227         if (caller.allowedModes == Lookup.TRUSTED) {
 228             return new Lookup(targetClass);
 229         }
 230 
 231         @SuppressWarnings("removal")
 232         SecurityManager sm = System.getSecurityManager();
 233         if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 234         if (targetClass.isPrimitive())
 235             throw new IllegalArgumentException(targetClass + " is a primitive class");
 236         if (targetClass.isArray())
 237             throw new IllegalArgumentException(targetClass + " is an array class");
 238         // Ensure that we can reason accurately about private and module access.
 239         int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
 240         if ((caller.lookupModes() & requireAccess) != requireAccess)
 241             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 242 
 243         // previous lookup class is never set if it has MODULE access
 244         assert caller.previousLookupClass() == null;
 245 
 246         Class<?> callerClass = caller.lookupClass();
 247         Module callerModule = callerClass.getModule();  // M1
 248         Module targetModule = targetClass.getModule();  // M2
 249         Class<?> newPreviousClass = null;
 250         int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
 251 
 252         if (targetModule != callerModule) {
 253             if (!callerModule.canRead(targetModule))
 254                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 255             if (targetModule.isNamed()) {
 256                 String pn = targetClass.getPackageName();
 257                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 258                 if (!targetModule.isOpen(pn, callerModule))
 259                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 260             }
 261 
 262             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 263             newPreviousClass = callerClass;
 264             newModes &= ~Lookup.MODULE;
 265         }
 266         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 267     }
 268 
 269     /**
 270      * Returns the <em>class data</em> associated with the lookup class
 271      * of the given {@code caller} lookup object, or {@code null}.
 272      *
 273      * <p> A hidden class with class data can be created by calling
 274      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 275      * Lookup::defineHiddenClassWithClassData}.
 276      * This method will cause the static class initializer of the lookup
 277      * class of the given {@code caller} lookup object be executed if
 278      * it has not been initialized.
 279      *
 280      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 281      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 282      * {@code null} is returned if this method is called on the lookup object
 283      * on these classes.
 284      *
 285      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 286      * must have {@linkplain Lookup#ORIGINAL original access}
 287      * in order to retrieve the class data.
 288      *
 289      * @apiNote
 290      * This method can be called as a bootstrap method for a dynamically computed
 291      * constant.  A framework can create a hidden class with class data, for
 292      * example that can be {@code Class} or {@code MethodHandle} object.
 293      * The class data is accessible only to the lookup object
 294      * created by the original caller but inaccessible to other members
 295      * in the same nest.  If a framework passes security sensitive objects
 296      * to a hidden class via class data, it is recommended to load the value
 297      * of class data as a dynamically computed constant instead of storing
 298      * the class data in private static field(s) which are accessible to
 299      * other nestmates.
 300      *
 301      * @param <T> the type to cast the class data object to
 302      * @param caller the lookup context describing the class performing the
 303      * operation (normally stacked by the JVM)
 304      * @param name must be {@link ConstantDescs#DEFAULT_NAME}
 305      *             ({@code "_"})
 306      * @param type the type of the class data
 307      * @return the value of the class data if present in the lookup class;
 308      * otherwise {@code null}
 309      * @throws IllegalArgumentException if name is not {@code "_"}
 310      * @throws IllegalAccessException if the lookup context does not have
 311      * {@linkplain Lookup#ORIGINAL original} access
 312      * @throws ClassCastException if the class data cannot be converted to
 313      * the given {@code type}
 314      * @throws NullPointerException if {@code caller} or {@code type} argument
 315      * is {@code null}
 316      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 317      * @see MethodHandles#classDataAt(Lookup, String, Class, int)
 318      * @since 16
 319      * @jvms 5.5 Initialization
 320      */
 321      public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 322          Objects.requireNonNull(caller);
 323          Objects.requireNonNull(type);
 324          if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
 325              throw new IllegalArgumentException("name must be \"_\": " + name);
 326          }
 327 
 328          if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL)  {
 329              throw new IllegalAccessException(caller + " does not have ORIGINAL access");
 330          }
 331 
 332          Object classdata = MethodHandleNatives.classData(caller.lookupClass());
 333          if (classdata == null) return null;
 334 
 335          try {
 336              return BootstrapMethodInvoker.widenAndCast(classdata, type);
 337          } catch (RuntimeException|Error e) {
 338              throw e; // let CCE and other runtime exceptions through
 339          } catch (Throwable e) {
 340              throw new InternalError(e);
 341          }
 342     }
 343 
 344     /**
 345      * Returns the element at the specified index in the
 346      * {@linkplain #classData(Lookup, String, Class) class data},
 347      * if the class data associated with the lookup class
 348      * of the given {@code caller} lookup object is a {@code List}.
 349      * If the class data is not present in this lookup class, this method
 350      * returns {@code null}.
 351      *
 352      * <p> A hidden class with class data can be created by calling
 353      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 354      * Lookup::defineHiddenClassWithClassData}.
 355      * This method will cause the static class initializer of the lookup
 356      * class of the given {@code caller} lookup object be executed if
 357      * it has not been initialized.
 358      *
 359      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 360      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 361      * {@code null} is returned if this method is called on the lookup object
 362      * on these classes.
 363      *
 364      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 365      * must have {@linkplain Lookup#ORIGINAL original access}
 366      * in order to retrieve the class data.
 367      *
 368      * @apiNote
 369      * This method can be called as a bootstrap method for a dynamically computed
 370      * constant.  A framework can create a hidden class with class data, for
 371      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 372      * one object and use this method to load one element at a specific index.
 373      * The class data is accessible only to the lookup object
 374      * created by the original caller but inaccessible to other members
 375      * in the same nest.  If a framework passes security sensitive objects
 376      * to a hidden class via class data, it is recommended to load the value
 377      * of class data as a dynamically computed constant instead of storing
 378      * the class data in private static field(s) which are accessible to other
 379      * nestmates.
 380      *
 381      * @param <T> the type to cast the result object to
 382      * @param caller the lookup context describing the class performing the
 383      * operation (normally stacked by the JVM)
 384      * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
 385      *             ({@code "_"})
 386      * @param type the type of the element at the given index in the class data
 387      * @param index index of the element in the class data
 388      * @return the element at the given index in the class data
 389      * if the class data is present; otherwise {@code null}
 390      * @throws IllegalArgumentException if name is not {@code "_"}
 391      * @throws IllegalAccessException if the lookup context does not have
 392      * {@linkplain Lookup#ORIGINAL original} access
 393      * @throws ClassCastException if the class data cannot be converted to {@code List}
 394      * or the element at the specified index cannot be converted to the given type
 395      * @throws IndexOutOfBoundsException if the index is out of range
 396      * @throws NullPointerException if {@code caller} or {@code type} argument is
 397      * {@code null}; or if unboxing operation fails because
 398      * the element at the given index is {@code null}
 399      *
 400      * @since 16
 401      * @see #classData(Lookup, String, Class)
 402      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 403      */
 404     public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
 405             throws IllegalAccessException
 406     {
 407         @SuppressWarnings("unchecked")
 408         List<Object> classdata = (List<Object>)classData(caller, name, List.class);
 409         if (classdata == null) return null;
 410 
 411         try {
 412             Object element = classdata.get(index);
 413             return BootstrapMethodInvoker.widenAndCast(element, type);
 414         } catch (RuntimeException|Error e) {
 415             throw e; // let specified exceptions and other runtime exceptions/errors through
 416         } catch (Throwable e) {
 417             throw new InternalError(e);
 418         }
 419     }
 420 
 421     /**
 422      * Performs an unchecked "crack" of a
 423      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 424      * The result is as if the user had obtained a lookup object capable enough
 425      * to crack the target method handle, called
 426      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 427      * on the target to obtain its symbolic reference, and then called
 428      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 429      * to resolve the symbolic reference to a member.
 430      * <p>
 431      * If there is a security manager, its {@code checkPermission} method
 432      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 433      * @param <T> the desired type of the result, either {@link Member} or a subtype
 434      * @param target a direct method handle to crack into symbolic reference components
 435      * @param expected a class object representing the desired result type {@code T}
 436      * @return a reference to the method, constructor, or field object
 437      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 438      * @throws    NullPointerException if either argument is {@code null}
 439      * @throws    IllegalArgumentException if the target is not a direct method handle
 440      * @throws    ClassCastException if the member is not of the expected type
 441      * @since 1.8
 442      */
 443     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 444         @SuppressWarnings("removal")
 445         SecurityManager smgr = System.getSecurityManager();
 446         if (smgr != null)  smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 447         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 448         return lookup.revealDirect(target).reflectAs(expected, lookup);
 449     }
 450 
 451     /**
 452      * A <em>lookup object</em> is a factory for creating method handles,
 453      * when the creation requires access checking.
 454      * Method handles do not perform
 455      * access checks when they are called, but rather when they are created.
 456      * Therefore, method handle access
 457      * restrictions must be enforced when a method handle is created.
 458      * The caller class against which those restrictions are enforced
 459      * is known as the {@linkplain #lookupClass() lookup class}.
 460      * <p>
 461      * A lookup class which needs to create method handles will call
 462      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 463      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 464      * determined, and securely stored in the {@code Lookup} object.
 465      * The lookup class (or its delegates) may then use factory methods
 466      * on the {@code Lookup} object to create method handles for access-checked members.
 467      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 468      * even private ones.
 469      *
 470      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 471      * The factory methods on a {@code Lookup} object correspond to all major
 472      * use cases for methods, constructors, and fields.
 473      * Each method handle created by a factory method is the functional
 474      * equivalent of a particular <em>bytecode behavior</em>.
 475      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 476      * the Java Virtual Machine Specification.)
 477      * Here is a summary of the correspondence between these factory methods and
 478      * the behavior of the resulting method handles:
 479      * <table class="striped">
 480      * <caption style="display:none">lookup method behaviors</caption>
 481      * <thead>
 482      * <tr>
 483      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 484      *     <th scope="col">member</th>
 485      *     <th scope="col">bytecode behavior</th>
 486      * </tr>
 487      * </thead>
 488      * <tbody>
 489      * <tr>
 490      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 491      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 492      * </tr>
 493      * <tr>
 494      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 495      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 496      * </tr>
 497      * <tr>
 498      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 499      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 500      * </tr>
 501      * <tr>
 502      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 503      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 504      * </tr>
 505      * <tr>
 506      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 507      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 508      * </tr>
 509      * <tr>
 510      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 511      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 512      * </tr>
 513      * <tr>
 514      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 515      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 516      * </tr>
 517      * <tr>
 518      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 519      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 520      * </tr>
 521      * <tr>
 522      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 523      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 524      * </tr>
 525      * <tr>
 526      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 527      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 528      * </tr>
 529      * <tr>
 530      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 531      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 532      * </tr>
 533      * <tr>
 534      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 535      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 536      * </tr>
 537      * <tr>
 538      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 539      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 540      * </tr>
 541      * <tr>
 542      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 543      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 544      * </tr>
 545      * </tbody>
 546      * </table>
 547      *
 548      * Here, the type {@code C} is the class or interface being searched for a member,
 549      * documented as a parameter named {@code refc} in the lookup methods.
 550      * The method type {@code MT} is composed from the return type {@code T}
 551      * and the sequence of argument types {@code A*}.
 552      * The constructor also has a sequence of argument types {@code A*} and
 553      * is deemed to return the newly-created object of type {@code C}.
 554      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 555      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 556      * if it is present, it is always the leading argument to the method handle invocation.
 557      * (In the case of some {@code protected} members, {@code this} may be
 558      * restricted in type to the lookup class; see below.)
 559      * The name {@code arg} stands for all the other method handle arguments.
 560      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 561      * stands for a null reference if the accessed method or field is static,
 562      * and {@code this} otherwise.
 563      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 564      * for reflective objects corresponding to the given members declared in type {@code C}.
 565      * <p>
 566      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 567      * as if by {@code ldc CONSTANT_Class}.
 568      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 569      * <p>
 570      * In cases where the given member is of variable arity (i.e., a method or constructor)
 571      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 572      * In all other cases, the returned method handle will be of fixed arity.
 573      * <p style="font-size:smaller;">
 574      * <em>Discussion:</em>
 575      * The equivalence between looked-up method handles and underlying
 576      * class members and bytecode behaviors
 577      * can break down in a few ways:
 578      * <ul style="font-size:smaller;">
 579      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 580      * the lookup can still succeed, even when there is no equivalent
 581      * Java expression or bytecoded constant.
 582      * <li>Likewise, if {@code T} or {@code MT}
 583      * is not symbolically accessible from the lookup class's loader,
 584      * the lookup can still succeed.
 585      * For example, lookups for {@code MethodHandle.invokeExact} and
 586      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 587      * <li>If there is a security manager installed, it can forbid the lookup
 588      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 589      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 590      * constant is not subject to security manager checks.
 591      * <li>If the looked-up method has a
 592      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 593      * the method handle creation may fail with an
 594      * {@code IllegalArgumentException}, due to the method handle type having
 595      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 596      * </ul>
 597      *
 598      * <h2><a id="access"></a>Access checking</h2>
 599      * Access checks are applied in the factory methods of {@code Lookup},
 600      * when a method handle is created.
 601      * This is a key difference from the Core Reflection API, since
 602      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 603      * performs access checking against every caller, on every call.
 604      * <p>
 605      * All access checks start from a {@code Lookup} object, which
 606      * compares its recorded lookup class against all requests to
 607      * create method handles.
 608      * A single {@code Lookup} object can be used to create any number
 609      * of access-checked method handles, all checked against a single
 610      * lookup class.
 611      * <p>
 612      * A {@code Lookup} object can be shared with other trusted code,
 613      * such as a metaobject protocol.
 614      * A shared {@code Lookup} object delegates the capability
 615      * to create method handles on private members of the lookup class.
 616      * Even if privileged code uses the {@code Lookup} object,
 617      * the access checking is confined to the privileges of the
 618      * original lookup class.
 619      * <p>
 620      * A lookup can fail, because
 621      * the containing class is not accessible to the lookup class, or
 622      * because the desired class member is missing, or because the
 623      * desired class member is not accessible to the lookup class, or
 624      * because the lookup object is not trusted enough to access the member.
 625      * In the case of a field setter function on a {@code final} field,
 626      * finality enforcement is treated as a kind of access control,
 627      * and the lookup will fail, except in special cases of
 628      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 629      * In any of these cases, a {@code ReflectiveOperationException} will be
 630      * thrown from the attempted lookup.  The exact class will be one of
 631      * the following:
 632      * <ul>
 633      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 634      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 635      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 636      * </ul>
 637      * <p>
 638      * In general, the conditions under which a method handle may be
 639      * looked up for a method {@code M} are no more restrictive than the conditions
 640      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 641      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 642      * a method handle lookup will generally raise a corresponding
 643      * checked exception, such as {@code NoSuchMethodException}.
 644      * And the effect of invoking the method handle resulting from the lookup
 645      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 646      * to executing the compiled, verified, and resolved call to {@code M}.
 647      * The same point is true of fields and constructors.
 648      * <p style="font-size:smaller;">
 649      * <em>Discussion:</em>
 650      * Access checks only apply to named and reflected methods,
 651      * constructors, and fields.
 652      * Other method handle creation methods, such as
 653      * {@link MethodHandle#asType MethodHandle.asType},
 654      * do not require any access checks, and are used
 655      * independently of any {@code Lookup} object.
 656      * <p>
 657      * If the desired member is {@code protected}, the usual JVM rules apply,
 658      * including the requirement that the lookup class must either be in the
 659      * same package as the desired member, or must inherit that member.
 660      * (See the Java Virtual Machine Specification, sections {@jvms
 661      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 662      * In addition, if the desired member is a non-static field or method
 663      * in a different package, the resulting method handle may only be applied
 664      * to objects of the lookup class or one of its subclasses.
 665      * This requirement is enforced by narrowing the type of the leading
 666      * {@code this} parameter from {@code C}
 667      * (which will necessarily be a superclass of the lookup class)
 668      * to the lookup class itself.
 669      * <p>
 670      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 671      * that the receiver argument must match both the resolved method <em>and</em>
 672      * the current class.  Again, this requirement is enforced by narrowing the
 673      * type of the leading parameter to the resulting method handle.
 674      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 675      * <p>
 676      * The JVM represents constructors and static initializer blocks as internal methods
 677      * with special names ({@code "<init>"} and {@code "<clinit>"}).
 678      * The internal syntax of invocation instructions allows them to refer to such internal
 679      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 680      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 681      * <p>
 682      * If the relationship between nested types is expressed directly through the
 683      * {@code NestHost} and {@code NestMembers} attributes
 684      * (see the Java Virtual Machine Specification, sections {@jvms
 685      * 4.7.28} and {@jvms 4.7.29}),
 686      * then the associated {@code Lookup} object provides direct access to
 687      * the lookup class and all of its nestmates
 688      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 689      * Otherwise, access between nested classes is obtained by the Java compiler creating
 690      * a wrapper method to access a private method of another class in the same nest.
 691      * For example, a nested class {@code C.D}
 692      * can access private members within other related classes such as
 693      * {@code C}, {@code C.D.E}, or {@code C.B},
 694      * but the Java compiler may need to generate wrapper methods in
 695      * those related classes.  In such cases, a {@code Lookup} object on
 696      * {@code C.E} would be unable to access those private members.
 697      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 698      * which can transform a lookup on {@code C.E} into one on any of those other
 699      * classes, without special elevation of privilege.
 700      * <p>
 701      * The accesses permitted to a given lookup object may be limited,
 702      * according to its set of {@link #lookupModes lookupModes},
 703      * to a subset of members normally accessible to the lookup class.
 704      * For example, the {@link MethodHandles#publicLookup publicLookup}
 705      * method produces a lookup object which is only allowed to access
 706      * public members in public classes of exported packages.
 707      * The caller sensitive method {@link MethodHandles#lookup lookup}
 708      * produces a lookup object with full capabilities relative to
 709      * its caller class, to emulate all supported bytecode behaviors.
 710      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 711      * with fewer access modes than the original lookup object.
 712      *
 713      * <p style="font-size:smaller;">
 714      * <a id="privacc"></a>
 715      * <em>Discussion of private and module access:</em>
 716      * We say that a lookup has <em>private access</em>
 717      * if its {@linkplain #lookupModes lookup modes}
 718      * include the possibility of accessing {@code private} members
 719      * (which includes the private members of nestmates).
 720      * As documented in the relevant methods elsewhere,
 721      * only lookups with private access possess the following capabilities:
 722      * <ul style="font-size:smaller;">
 723      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 724      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 725      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 726      *     for classes accessible to the lookup class
 727      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 728      *     within the same package member
 729      * </ul>
 730      * <p style="font-size:smaller;">
 731      * Similarly, a lookup with module access ensures that the original lookup creator was
 732      * a member in the same module as the lookup class.
 733      * <p style="font-size:smaller;">
 734      * Private and module access are independently determined modes; a lookup may have
 735      * either or both or neither.  A lookup which possesses both access modes is said to
 736      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
 737      * <p style="font-size:smaller;">
 738      * A lookup with <em>original access</em> ensures that this lookup is created by
 739      * the original lookup class and the bootstrap method invoked by the VM.
 740      * Such a lookup with original access also has private and module access
 741      * which has the following additional capability:
 742      * <ul style="font-size:smaller;">
 743      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 744      *     such as {@code Class.forName}
 745      * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
 746      * class data} associated with the lookup class</li>
 747      * </ul>
 748      * <p style="font-size:smaller;">
 749      * Each of these permissions is a consequence of the fact that a lookup object
 750      * with private access can be securely traced back to an originating class,
 751      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 752      * can be reliably determined and emulated by method handles.
 753      *
 754      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 755      * When a lookup class in one module {@code M1} accesses a class in another module
 756      * {@code M2}, extra access checking is performed beyond the access mode bits.
 757      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 758      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 759      * and when the type is in a package of {@code M2} that is exported to
 760      * at least {@code M1}.
 761      * <p>
 762      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 763      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 764      * MethodHandles.privateLookupIn} methods.
 765      * Teleporting across modules will always record the original lookup class as
 766      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 767      * and drops {@link Lookup#MODULE MODULE} access.
 768      * If the target class is in the same module as the lookup class {@code C},
 769      * then the target class becomes the new lookup class
 770      * and there is no change to the previous lookup class.
 771      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 772      * {@code C} becomes the new previous lookup class
 773      * and the target class becomes the new lookup class.
 774      * In that case, if there was already a previous lookup class in {@code M0},
 775      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 776      * drops all privileges.
 777      * For example,
 778      * <blockquote><pre>
 779      * {@code
 780      * Lookup lookup = MethodHandles.lookup();   // in class C
 781      * Lookup lookup2 = lookup.in(D.class);
 782      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 783      * }</pre></blockquote>
 784      * <p>
 785      * The {@link #lookup()} factory method produces a {@code Lookup} object
 786      * with {@code null} previous lookup class.
 787      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 788      * to class {@code D} without elevation of privileges.
 789      * If {@code C} and {@code D} are in the same module,
 790      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 791      * same previous lookup class as the original {@code lookup}, or
 792      * {@code null} if not present.
 793      * <p>
 794      * When a {@code Lookup} teleports from a class
 795      * in one nest to another nest, {@code PRIVATE} access is dropped.
 796      * When a {@code Lookup} teleports from a class in one package to
 797      * another package, {@code PACKAGE} access is dropped.
 798      * When a {@code Lookup} teleports from a class in one module to another module,
 799      * {@code MODULE} access is dropped.
 800      * Teleporting across modules drops the ability to access non-exported classes
 801      * in both the module of the new lookup class and the module of the old lookup class
 802      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 803      * A {@code Lookup} can teleport back and forth to a class in the module of
 804      * the lookup class and the module of the previous class lookup.
 805      * Teleporting across modules can only decrease access but cannot increase it.
 806      * Teleporting to some third module drops all accesses.
 807      * <p>
 808      * In the above example, if {@code C} and {@code D} are in different modules,
 809      * {@code lookup2} records {@code D} as its lookup class and
 810      * {@code C} as its previous lookup class and {@code lookup2} has only
 811      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 812      * {@code C}'s module and {@code D}'s module.
 813      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 814      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 815      * class {@code D} is recorded as its previous lookup class.
 816      * <p>
 817      * Teleporting across modules restricts access to the public types that
 818      * both the lookup class and the previous lookup class can equally access
 819      * (see below).
 820      * <p>
 821      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 822      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 823      * and create a new {@code Lookup} with <a href="#privacc">private access</a>
 824      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 825      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 826      * to call {@code privateLookupIn}.
 827      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 828      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 829      * produces a new {@code Lookup} on {@code T} with full capabilities.
 830      * A {@code lookup} on {@code C} is also allowed
 831      * to do deep reflection on {@code T} in another module {@code M2} if
 832      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 833      * the package containing {@code T} to at least {@code M1}.
 834      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 835      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 836      * The resulting {@code Lookup} can be used to do member lookup or teleport
 837      * to another lookup class by calling {@link #in Lookup::in}.  But
 838      * it cannot be used to obtain another private {@code Lookup} by calling
 839      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 840      * because it has no {@code MODULE} access.
 841      *
 842      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 843      *
 844      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 845      * allows cross-module access. The access checking is performed with respect
 846      * to both the lookup class and the previous lookup class if present.
 847      * <p>
 848      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 849      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 850      * exported unconditionally}.
 851      * <p>
 852      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 853      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 854      * that are readable to {@code M1} and the type is in a package that is exported
 855      * at least to {@code M1}.
 856      * <p>
 857      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 858      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 859      * the intersection of all public types that are accessible to {@code M1}
 860      * with all public types that are accessible to {@code M0}. {@code M0}
 861      * reads {@code M1} and hence the set of accessible types includes:
 862      *
 863      * <table class="striped">
 864      * <caption style="display:none">
 865      * Public types in the following packages are accessible to the
 866      * lookup class and the previous lookup class.
 867      * </caption>
 868      * <thead>
 869      * <tr>
 870      * <th scope="col">Equally accessible types to {@code M0} and {@code M1}</th>
 871      * </tr>
 872      * </thead>
 873      * <tbody>
 874      * <tr>
 875      * <th scope="row" style="text-align:left">unconditional-exported packages from {@code M1}</th>
 876      * </tr>
 877      * <tr>
 878      * <th scope="row" style="text-align:left">unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</th>
 879      * </tr>
 880      * <tr>
 881      * <th scope="row" style="text-align:left">unconditional-exported packages from a third module {@code M2}
 882      * if both {@code M0} and {@code M1} read {@code M2}</th>
 883      * </tr>
 884      * <tr>
 885      * <th scope="row" style="text-align:left">qualified-exported packages from {@code M1} to {@code M0}</th>
 886      * </tr>
 887      * <tr>
 888      * <th scope="row" style="text-align:left">qualified-exported packages from {@code M0} to {@code M1}
 889      * if {@code M1} reads {@code M0}</th>
 890      * </tr>
 891      * <tr>
 892      * <th scope="row" style="text-align:left">qualified-exported packages from a third module {@code M2} to
 893      * both {@code M0} and {@code M1} if both {@code M0} and {@code M1} read {@code M2}</th>
 894      * </tr>
 895      * </tbody>
 896      * </table>
 897      *
 898      * <h2><a id="access-modes"></a>Access modes</h2>
 899      *
 900      * The table below shows the access modes of a {@code Lookup} produced by
 901      * any of the following factory or transformation methods:
 902      * <ul>
 903      * <li>{@link #lookup() MethodHandles::lookup}</li>
 904      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 905      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 906      * <li>{@link Lookup#in Lookup::in}</li>
 907      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 908      * </ul>
 909      *
 910      * <table class="striped">
 911      * <caption style="display:none">
 912      * Access mode summary
 913      * </caption>
 914      * <thead>
 915      * <tr>
 916      * <th scope="col">Lookup object</th>
 917      * <th style="text-align:center">original</th>
 918      * <th style="text-align:center">protected</th>
 919      * <th style="text-align:center">private</th>
 920      * <th style="text-align:center">package</th>
 921      * <th style="text-align:center">module</th>
 922      * <th style="text-align:center">public</th>
 923      * </tr>
 924      * </thead>
 925      * <tbody>
 926      * <tr>
 927      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 928      * <td style="text-align:center">ORI</td>
 929      * <td style="text-align:center">PRO</td>
 930      * <td style="text-align:center">PRI</td>
 931      * <td style="text-align:center">PAC</td>
 932      * <td style="text-align:center">MOD</td>
 933      * <td style="text-align:center">1R</td>
 934      * </tr>
 935      * <tr>
 936      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 937      * <td></td>
 938      * <td></td>
 939      * <td></td>
 940      * <td style="text-align:center">PAC</td>
 941      * <td style="text-align:center">MOD</td>
 942      * <td style="text-align:center">1R</td>
 943      * </tr>
 944      * <tr>
 945      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 946      * <td></td>
 947      * <td></td>
 948      * <td></td>
 949      * <td></td>
 950      * <td style="text-align:center">MOD</td>
 951      * <td style="text-align:center">1R</td>
 952      * </tr>
 953      * <tr>
 954      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 955      * <td></td>
 956      * <td></td>
 957      * <td></td>
 958      * <td></td>
 959      * <td></td>
 960      * <td style="text-align:center">2R</td>
 961      * </tr>
 962      * <tr>
 963      * <td>{@code CL.in(D).in(C)} hop back to module</td>
 964      * <td></td>
 965      * <td></td>
 966      * <td></td>
 967      * <td></td>
 968      * <td></td>
 969      * <td style="text-align:center">2R</td>
 970      * </tr>
 971      * <tr>
 972      * <td>{@code PRI1 = privateLookupIn(C1,CL)}</td>
 973      * <td></td>
 974      * <td style="text-align:center">PRO</td>
 975      * <td style="text-align:center">PRI</td>
 976      * <td style="text-align:center">PAC</td>
 977      * <td style="text-align:center">MOD</td>
 978      * <td style="text-align:center">1R</td>
 979      * </tr>
 980      * <tr>
 981      * <td>{@code PRI1a = privateLookupIn(C,PRI1)}</td>
 982      * <td></td>
 983      * <td style="text-align:center">PRO</td>
 984      * <td style="text-align:center">PRI</td>
 985      * <td style="text-align:center">PAC</td>
 986      * <td style="text-align:center">MOD</td>
 987      * <td style="text-align:center">1R</td>
 988      * </tr>
 989      * <tr>
 990      * <td>{@code PRI1.in(C1)} same package</td>
 991      * <td></td>
 992      * <td></td>
 993      * <td></td>
 994      * <td style="text-align:center">PAC</td>
 995      * <td style="text-align:center">MOD</td>
 996      * <td style="text-align:center">1R</td>
 997      * </tr>
 998      * <tr>
 999      * <td>{@code PRI1.in(C1)} different package</td>
1000      * <td></td>
1001      * <td></td>
1002      * <td></td>
1003      * <td></td>
1004      * <td style="text-align:center">MOD</td>
1005      * <td style="text-align:center">1R</td>
1006      * </tr>
1007      * <tr>
1008      * <td>{@code PRI1.in(D)} different module</td>
1009      * <td></td>
1010      * <td></td>
1011      * <td></td>
1012      * <td></td>
1013      * <td></td>
1014      * <td style="text-align:center">2R</td>
1015      * </tr>
1016      * <tr>
1017      * <td>{@code PRI1.dropLookupMode(PROTECTED)}</td>
1018      * <td></td>
1019      * <td></td>
1020      * <td style="text-align:center">PRI</td>
1021      * <td style="text-align:center">PAC</td>
1022      * <td style="text-align:center">MOD</td>
1023      * <td style="text-align:center">1R</td>
1024      * </tr>
1025      * <tr>
1026      * <td>{@code PRI1.dropLookupMode(PRIVATE)}</td>
1027      * <td></td>
1028      * <td></td>
1029      * <td></td>
1030      * <td style="text-align:center">PAC</td>
1031      * <td style="text-align:center">MOD</td>
1032      * <td style="text-align:center">1R</td>
1033      * </tr>
1034      * <tr>
1035      * <td>{@code PRI1.dropLookupMode(PACKAGE)}</td>
1036      * <td></td>
1037      * <td></td>
1038      * <td></td>
1039      * <td></td>
1040      * <td style="text-align:center">MOD</td>
1041      * <td style="text-align:center">1R</td>
1042      * </tr>
1043      * <tr>
1044      * <td>{@code PRI1.dropLookupMode(MODULE)}</td>
1045      * <td></td>
1046      * <td></td>
1047      * <td></td>
1048      * <td></td>
1049      * <td></td>
1050      * <td style="text-align:center">1R</td>
1051      * </tr>
1052      * <tr>
1053      * <td>{@code PRI1.dropLookupMode(PUBLIC)}</td>
1054      * <td></td>
1055      * <td></td>
1056      * <td></td>
1057      * <td></td>
1058      * <td></td>
1059      * <td style="text-align:center">none</td>
1060      * <tr>
1061      * <td>{@code PRI2 = privateLookupIn(D,CL)}</td>
1062      * <td></td>
1063      * <td style="text-align:center">PRO</td>
1064      * <td style="text-align:center">PRI</td>
1065      * <td style="text-align:center">PAC</td>
1066      * <td></td>
1067      * <td style="text-align:center">2R</td>
1068      * </tr>
1069      * <tr>
1070      * <td>{@code privateLookupIn(D,PRI1)}</td>
1071      * <td></td>
1072      * <td style="text-align:center">PRO</td>
1073      * <td style="text-align:center">PRI</td>
1074      * <td style="text-align:center">PAC</td>
1075      * <td></td>
1076      * <td style="text-align:center">2R</td>
1077      * </tr>
1078      * <tr>
1079      * <td>{@code privateLookupIn(C,PRI2)} fails</td>
1080      * <td></td>
1081      * <td></td>
1082      * <td></td>
1083      * <td></td>
1084      * <td></td>
1085      * <td style="text-align:center">IAE</td>
1086      * </tr>
1087      * <tr>
1088      * <td>{@code PRI2.in(D2)} same package</td>
1089      * <td></td>
1090      * <td></td>
1091      * <td></td>
1092      * <td style="text-align:center">PAC</td>
1093      * <td></td>
1094      * <td style="text-align:center">2R</td>
1095      * </tr>
1096      * <tr>
1097      * <td>{@code PRI2.in(D2)} different package</td>
1098      * <td></td>
1099      * <td></td>
1100      * <td></td>
1101      * <td></td>
1102      * <td></td>
1103      * <td style="text-align:center">2R</td>
1104      * </tr>
1105      * <tr>
1106      * <td>{@code PRI2.in(C1)} hop back to module</td>
1107      * <td></td>
1108      * <td></td>
1109      * <td></td>
1110      * <td></td>
1111      * <td></td>
1112      * <td style="text-align:center">2R</td>
1113      * </tr>
1114      * <tr>
1115      * <td>{@code PRI2.in(E)} hop to third module</td>
1116      * <td></td>
1117      * <td></td>
1118      * <td></td>
1119      * <td></td>
1120      * <td></td>
1121      * <td style="text-align:center">none</td>
1122      * </tr>
1123      * <tr>
1124      * <td>{@code PRI2.dropLookupMode(PROTECTED)}</td>
1125      * <td></td>
1126      * <td></td>
1127      * <td style="text-align:center">PRI</td>
1128      * <td style="text-align:center">PAC</td>
1129      * <td></td>
1130      * <td style="text-align:center">2R</td>
1131      * </tr>
1132      * <tr>
1133      * <td>{@code PRI2.dropLookupMode(PRIVATE)}</td>
1134      * <td></td>
1135      * <td></td>
1136      * <td></td>
1137      * <td style="text-align:center">PAC</td>
1138      * <td></td>
1139      * <td style="text-align:center">2R</td>
1140      * </tr>
1141      * <tr>
1142      * <td>{@code PRI2.dropLookupMode(PACKAGE)}</td>
1143      * <td></td>
1144      * <td></td>
1145      * <td></td>
1146      * <td></td>
1147      * <td></td>
1148      * <td style="text-align:center">2R</td>
1149      * </tr>
1150      * <tr>
1151      * <td>{@code PRI2.dropLookupMode(MODULE)}</td>
1152      * <td></td>
1153      * <td></td>
1154      * <td></td>
1155      * <td></td>
1156      * <td></td>
1157      * <td style="text-align:center">2R</td>
1158      * </tr>
1159      * <tr>
1160      * <td>{@code PRI2.dropLookupMode(PUBLIC)}</td>
1161      * <td></td>
1162      * <td></td>
1163      * <td></td>
1164      * <td></td>
1165      * <td></td>
1166      * <td style="text-align:center">none</td>
1167      * </tr>
1168      * <tr>
1169      * <td>{@code CL.dropLookupMode(PROTECTED)}</td>
1170      * <td></td>
1171      * <td></td>
1172      * <td style="text-align:center">PRI</td>
1173      * <td style="text-align:center">PAC</td>
1174      * <td style="text-align:center">MOD</td>
1175      * <td style="text-align:center">1R</td>
1176      * </tr>
1177      * <tr>
1178      * <td>{@code CL.dropLookupMode(PRIVATE)}</td>
1179      * <td></td>
1180      * <td></td>
1181      * <td></td>
1182      * <td style="text-align:center">PAC</td>
1183      * <td style="text-align:center">MOD</td>
1184      * <td style="text-align:center">1R</td>
1185      * </tr>
1186      * <tr>
1187      * <td>{@code CL.dropLookupMode(PACKAGE)}</td>
1188      * <td></td>
1189      * <td></td>
1190      * <td></td>
1191      * <td></td>
1192      * <td style="text-align:center">MOD</td>
1193      * <td style="text-align:center">1R</td>
1194      * </tr>
1195      * <tr>
1196      * <td>{@code CL.dropLookupMode(MODULE)}</td>
1197      * <td></td>
1198      * <td></td>
1199      * <td></td>
1200      * <td></td>
1201      * <td></td>
1202      * <td style="text-align:center">1R</td>
1203      * </tr>
1204      * <tr>
1205      * <td>{@code CL.dropLookupMode(PUBLIC)}</td>
1206      * <td></td>
1207      * <td></td>
1208      * <td></td>
1209      * <td></td>
1210      * <td></td>
1211      * <td style="text-align:center">none</td>
1212      * </tr>
1213      * <tr>
1214      * <td>{@code PUB = publicLookup()}</td>
1215      * <td></td>
1216      * <td></td>
1217      * <td></td>
1218      * <td></td>
1219      * <td></td>
1220      * <td style="text-align:center">U</td>
1221      * </tr>
1222      * <tr>
1223      * <td>{@code PUB.in(D)} different module</td>
1224      * <td></td>
1225      * <td></td>
1226      * <td></td>
1227      * <td></td>
1228      * <td></td>
1229      * <td style="text-align:center">U</td>
1230      * </tr>
1231      * <tr>
1232      * <td>{@code PUB.in(D).in(E)} third module</td>
1233      * <td></td>
1234      * <td></td>
1235      * <td></td>
1236      * <td></td>
1237      * <td></td>
1238      * <td style="text-align:center">U</td>
1239      * </tr>
1240      * <tr>
1241      * <td>{@code PUB.dropLookupMode(UNCONDITIONAL)}</td>
1242      * <td></td>
1243      * <td></td>
1244      * <td></td>
1245      * <td></td>
1246      * <td></td>
1247      * <td style="text-align:center">none</td>
1248      * </tr>
1249      * <tr>
1250      * <td>{@code privateLookupIn(C1,PUB)} fails</td>
1251      * <td></td>
1252      * <td></td>
1253      * <td></td>
1254      * <td></td>
1255      * <td></td>
1256      * <td style="text-align:center">IAE</td>
1257      * </tr>
1258      * <tr>
1259      * <td>{@code ANY.in(X)}, for inaccessible {@code X}</td>
1260      * <td></td>
1261      * <td></td>
1262      * <td></td>
1263      * <td></td>
1264      * <td></td>
1265      * <td style="text-align:center">none</td>
1266      * </tr>
1267      * </tbody>
1268      * </table>
1269      *
1270      * <p>
1271      * Notes:
1272      * <ul>
1273      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1274      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1275      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1276      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1277      * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1278      *     {@code PRO} indicates {@link #PROTECTED} bit set,
1279      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1280      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1281      *     {@code MOD} indicates {@link #MODULE} bit set,
1282      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1283      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1284      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1285      * <li>Public access comes in three kinds:
1286      * <ul>
1287      * <li>unconditional ({@code U}): the lookup assumes readability.
1288      *     The lookup has {@code null} previous lookup class.
1289      * <li>one-module-reads ({@code 1R}): the module access checking is
1290      *     performed with respect to the lookup class.  The lookup has {@code null}
1291      *     previous lookup class.
1292      * <li>two-module-reads ({@code 2R}): the module access checking is
1293      *     performed with respect to the lookup class and the previous lookup class.
1294      *     The lookup has a non-null previous lookup class which is in a
1295      *     different module from the current lookup class.
1296      * </ul>
1297      * <li>Any attempt to reach a third module loses all access.</li>
1298      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1299      * all access modes are dropped.</li>
1300      * </ul>
1301      *
1302      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1303      * Although bytecode instructions can only refer to classes in
1304      * a related class loader, this API can search for methods in any
1305      * class, as long as a reference to its {@code Class} object is
1306      * available.  Such cross-loader references are also possible with the
1307      * Core Reflection API, and are impossible to bytecode instructions
1308      * such as {@code invokestatic} or {@code getfield}.
1309      * There is a {@linkplain java.lang.SecurityManager security manager API}
1310      * to allow applications to check such cross-loader references.
1311      * These checks apply to both the {@code MethodHandles.Lookup} API
1312      * and the Core Reflection API
1313      * (as found on {@link java.lang.Class Class}).
1314      * <p>
1315      * If a security manager is present, member and class lookups are subject to
1316      * additional checks.
1317      * From one to three calls are made to the security manager.
1318      * Any of these calls can refuse access by throwing a
1319      * {@link java.lang.SecurityException SecurityException}.
1320      * Define {@code smgr} as the security manager,
1321      * {@code lookc} as the lookup class of the current lookup object,
1322      * {@code refc} as the containing class in which the member
1323      * is being sought, and {@code defc} as the class in which the
1324      * member is actually defined.
1325      * (If a class or other type is being accessed,
1326      * the {@code refc} and {@code defc} values are the class itself.)
1327      * The value {@code lookc} is defined as <em>not present</em>
1328      * if the current lookup object does not have
1329      * {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1330      * The calls are made according to the following rules:
1331      * <ul>
1332      * <li><b>Step 1:</b>
1333      *     If {@code lookc} is not present, or if its class loader is not
1334      *     the same as or an ancestor of the class loader of {@code refc},
1335      *     then {@link SecurityManager#checkPackageAccess
1336      *     smgr.checkPackageAccess(refcPkg)} is called,
1337      *     where {@code refcPkg} is the package of {@code refc}.
1338      * <li><b>Step 2a:</b>
1339      *     If the retrieved member is not public and
1340      *     {@code lookc} is not present, then
1341      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1342      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
1343      * <li><b>Step 2b:</b>
1344      *     If the retrieved class has a {@code null} class loader,
1345      *     and {@code lookc} is not present, then
1346      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1347      *     with {@code RuntimePermission("getClassLoader")} is called.
1348      * <li><b>Step 3:</b>
1349      *     If the retrieved member is not public,
1350      *     and if {@code lookc} is not present,
1351      *     and if {@code defc} and {@code refc} are different,
1352      *     then {@link SecurityManager#checkPackageAccess
1353      *     smgr.checkPackageAccess(defcPkg)} is called,
1354      *     where {@code defcPkg} is the package of {@code defc}.
1355      * </ul>
1356      * Security checks are performed after other access checks have passed.
1357      * Therefore, the above rules presuppose a member or class that is public,
1358      * or else that is being accessed from a lookup class that has
1359      * rights to access the member or class.
1360      * <p>
1361      * If a security manager is present and the current lookup object does not have
1362      * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then
1363      * {@link #defineClass(byte[]) defineClass},
1364      * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass},
1365      * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...)
1366      * defineHiddenClassWithClassData}
1367      * calls {@link SecurityManager#checkPermission smgr.checkPermission}
1368      * with {@code RuntimePermission("defineClass")}.
1369      *
1370      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1371      * A small number of Java methods have a special property called caller sensitivity.
1372      * A <em>caller-sensitive</em> method can behave differently depending on the
1373      * identity of its immediate caller.
1374      * <p>
1375      * If a method handle for a caller-sensitive method is requested,
1376      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1377      * but they take account of the lookup class in a special way.
1378      * The resulting method handle behaves as if it were called
1379      * from an instruction contained in the lookup class,
1380      * so that the caller-sensitive method detects the lookup class.
1381      * (By contrast, the invoker of the method handle is disregarded.)
1382      * Thus, in the case of caller-sensitive methods,
1383      * different lookup classes may give rise to
1384      * differently behaving method handles.
1385      * <p>
1386      * In cases where the lookup object is
1387      * {@link MethodHandles#publicLookup() publicLookup()},
1388      * or some other lookup object without the
1389      * {@linkplain #ORIGINAL original access},
1390      * the lookup class is disregarded.
1391      * In such cases, no caller-sensitive method handle can be created,
1392      * access is forbidden, and the lookup fails with an
1393      * {@code IllegalAccessException}.
1394      * <p style="font-size:smaller;">
1395      * <em>Discussion:</em>
1396      * For example, the caller-sensitive method
1397      * {@link java.lang.Class#forName(String) Class.forName(x)}
1398      * can return varying classes or throw varying exceptions,
1399      * depending on the class loader of the class that calls it.
1400      * A public lookup of {@code Class.forName} will fail, because
1401      * there is no reasonable way to determine its bytecode behavior.
1402      * <p style="font-size:smaller;">
1403      * If an application caches method handles for broad sharing,
1404      * it should use {@code publicLookup()} to create them.
1405      * If there is a lookup of {@code Class.forName}, it will fail,
1406      * and the application must take appropriate action in that case.
1407      * It may be that a later lookup, perhaps during the invocation of a
1408      * bootstrap method, can incorporate the specific identity
1409      * of the caller, making the method accessible.
1410      * <p style="font-size:smaller;">
1411      * The function {@code MethodHandles.lookup} is caller sensitive
1412      * so that there can be a secure foundation for lookups.
1413      * Nearly all other methods in the JSR 292 API rely on lookup
1414      * objects to check access requests.
1415      *
1416      * @revised 9
1417      */
1418     public static final
1419     class Lookup {
1420         /** The class on behalf of whom the lookup is being performed. */
1421         private final Class<?> lookupClass;
1422 
1423         /** previous lookup class */
1424         private final Class<?> prevLookupClass;
1425 
1426         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1427         private final int allowedModes;
1428 
1429         static {
1430             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1431         }
1432 
1433         /** A single-bit mask representing {@code public} access,
1434          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1435          *  The value, {@code 0x01}, happens to be the same as the value of the
1436          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1437          *  <p>
1438          *  A {@code Lookup} with this lookup mode performs cross-module access check
1439          *  with respect to the {@linkplain #lookupClass() lookup class} and
1440          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1441          */
1442         public static final int PUBLIC = Modifier.PUBLIC;
1443 
1444         /** A single-bit mask representing {@code private} access,
1445          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1446          *  The value, {@code 0x02}, happens to be the same as the value of the
1447          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1448          */
1449         public static final int PRIVATE = Modifier.PRIVATE;
1450 
1451         /** A single-bit mask representing {@code protected} access,
1452          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1453          *  The value, {@code 0x04}, happens to be the same as the value of the
1454          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1455          */
1456         public static final int PROTECTED = Modifier.PROTECTED;
1457 
1458         /** A single-bit mask representing {@code package} access (default access),
1459          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1460          *  The value is {@code 0x08}, which does not correspond meaningfully to
1461          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1462          */
1463         public static final int PACKAGE = Modifier.STATIC;
1464 
1465         /** A single-bit mask representing {@code module} access,
1466          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1467          *  The value is {@code 0x10}, which does not correspond meaningfully to
1468          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1469          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1470          *  with this lookup mode can access all public types in the module of the
1471          *  lookup class and public types in packages exported by other modules
1472          *  to the module of the lookup class.
1473          *  <p>
1474          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1475          *  previous lookup class} is always {@code null}.
1476          *
1477          *  @since 9
1478          */
1479         public static final int MODULE = PACKAGE << 1;
1480 
1481         /** A single-bit mask representing {@code unconditional} access
1482          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1483          *  The value is {@code 0x20}, which does not correspond meaningfully to
1484          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1485          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1486          *  java.lang.Module#canRead(java.lang.Module) readability}.
1487          *  This lookup mode can access all public members of public types
1488          *  of all modules when the type is in a package that is {@link
1489          *  java.lang.Module#isExported(String) exported unconditionally}.
1490          *
1491          *  <p>
1492          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1493          *  previous lookup class} is always {@code null}.
1494          *
1495          *  @since 9
1496          *  @see #publicLookup()
1497          */
1498         public static final int UNCONDITIONAL = PACKAGE << 2;
1499 
1500         /** A single-bit mask representing {@code original} access
1501          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1502          *  The value is {@code 0x40}, which does not correspond meaningfully to
1503          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1504          *
1505          *  <p>
1506          *  If this lookup mode is set, the {@code Lookup} object must be
1507          *  created by the original lookup class by calling
1508          *  {@link MethodHandles#lookup()} method or by a bootstrap method
1509          *  invoked by the VM.  The {@code Lookup} object with this lookup
1510          *  mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1511          *
1512          *  @since 16
1513          */
1514         public static final int ORIGINAL = PACKAGE << 3;
1515 
1516         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1517         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);   // with original access
1518         private static final int TRUSTED   = -1;
1519 
1520         /*
1521          * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1522          * Adjust 0 => PACKAGE
1523          */
1524         private static int fixmods(int mods) {
1525             mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1526             if (Modifier.isPublic(mods))
1527                 mods |= UNCONDITIONAL;
1528             return (mods != 0) ? mods : PACKAGE;
1529         }
1530 
1531         /** Tells which class is performing the lookup.  It is this class against
1532          *  which checks are performed for visibility and access permissions.
1533          *  <p>
1534          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1535          *  access checks are performed against both the lookup class and the previous lookup class.
1536          *  <p>
1537          *  The class implies a maximum level of access permission,
1538          *  but the permissions may be additionally limited by the bitmask
1539          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1540          *  can be accessed.
1541          *  @return the lookup class, on behalf of which this lookup object finds members
1542          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1543          */
1544         public Class<?> lookupClass() {
1545             return lookupClass;
1546         }
1547 
1548         /** Reports a lookup class in another module that this lookup object
1549          * was previously teleported from, or {@code null}.
1550          * <p>
1551          * A {@code Lookup} object produced by the factory methods, such as the
1552          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1553          * has {@code null} previous lookup class.
1554          * A {@code Lookup} object has a non-null previous lookup class
1555          * when this lookup was teleported from an old lookup class
1556          * in one module to a new lookup class in another module.
1557          *
1558          * @return the lookup class in another module that this lookup object was
1559          *         previously teleported from, or {@code null}
1560          * @since 14
1561          * @see #in(Class)
1562          * @see MethodHandles#privateLookupIn(Class, Lookup)
1563          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1564          */
1565         public Class<?> previousLookupClass() {
1566             return prevLookupClass;
1567         }
1568 
1569         // This is just for calling out to MethodHandleImpl.
1570         private Class<?> lookupClassOrNull() {
1571             return (allowedModes == TRUSTED) ? null : lookupClass;
1572         }
1573 
1574         /** Tells which access-protection classes of members this lookup object can produce.
1575          *  The result is a bit-mask of the bits
1576          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1577          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1578          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1579          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1580          *  {@linkplain #MODULE MODULE (0x10)},
1581          *  {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1582          *  and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1583          *  <p>
1584          *  A freshly-created lookup object
1585          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1586          *  all possible bits set, except {@code UNCONDITIONAL}.
1587          *  A lookup object on a new lookup class
1588          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1589          *  may have some mode bits set to zero.
1590          *  Mode bits can also be
1591          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1592          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1593          *  The purpose of this is to restrict access via the new lookup object,
1594          *  so that it can access only names which can be reached by the original
1595          *  lookup object, and also by the new lookup class.
1596          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1597          *  @see #in
1598          *  @see #dropLookupMode
1599          *
1600          *  @revised 9
1601          */
1602         public int lookupModes() {
1603             return allowedModes & ALL_MODES;
1604         }
1605 
1606         /** Embody the current class (the lookupClass) as a lookup class
1607          * for method handle creation.
1608          * Must be called by from a method in this package,
1609          * which in turn is called by a method not in this package.
1610          */
1611         Lookup(Class<?> lookupClass) {
1612             this(lookupClass, null, FULL_POWER_MODES);
1613         }
1614 
1615         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1616             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1617                     && prevLookupClass.getModule() != lookupClass.getModule());
1618             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1619             this.lookupClass = lookupClass;
1620             this.prevLookupClass = prevLookupClass;
1621             this.allowedModes = allowedModes;
1622         }
1623 
1624         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1625             // make sure we haven't accidentally picked up a privileged class:
1626             checkUnprivilegedlookupClass(lookupClass);
1627             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1628         }
1629 
1630         /**
1631          * Creates a lookup on the specified new lookup class.
1632          * The resulting object will report the specified
1633          * class as its own {@link #lookupClass() lookupClass}.
1634          *
1635          * <p>
1636          * However, the resulting {@code Lookup} object is guaranteed
1637          * to have no more access capabilities than the original.
1638          * In particular, access capabilities can be lost as follows:<ul>
1639          * <li>If the new lookup class is different from the old lookup class,
1640          * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1641          * <li>If the new lookup class is in a different module from the old one,
1642          * i.e. {@link #MODULE MODULE} access is lost.
1643          * <li>If the new lookup class is in a different package
1644          * than the old one, protected and default (package) members will not be accessible,
1645          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1646          * <li>If the new lookup class is not within the same package member
1647          * as the old one, private members will not be accessible, and protected members
1648          * will not be accessible by virtue of inheritance,
1649          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1650          * (Protected members may continue to be accessible because of package sharing.)
1651          * <li>If the new lookup class is not
1652          * {@linkplain #accessClass(Class) accessible} to this lookup,
1653          * then no members, not even public members, will be accessible
1654          * i.e. all access modes are lost.
1655          * <li>If the new lookup class, the old lookup class and the previous lookup class
1656          * are all in different modules i.e. teleporting to a third module,
1657          * all access modes are lost.
1658          * </ul>
1659          * <p>
1660          * The new previous lookup class is chosen as follows:
1661          * <ul>
1662          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1663          * the new previous lookup class is {@code null}.
1664          * <li>If the new lookup class is in the same module as the old lookup class,
1665          * the new previous lookup class is the old previous lookup class.
1666          * <li>If the new lookup class is in a different module from the old lookup class,
1667          * the new previous lookup class is the old lookup class.
1668          *</ul>
1669          * <p>
1670          * The resulting lookup's capabilities for loading classes
1671          * (used during {@link #findClass} invocations)
1672          * are determined by the lookup class' loader,
1673          * which may change due to this operation.
1674          *
1675          * @param requestedLookupClass the desired lookup class for the new lookup object
1676          * @return a lookup object which reports the desired lookup class, or the same object
1677          * if there is no change
1678          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1679          * @throws NullPointerException if the argument is null
1680          *
1681          * @revised 9
1682          * @see #accessClass(Class)
1683          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1684          */
1685         public Lookup in(Class<?> requestedLookupClass) {
1686             Objects.requireNonNull(requestedLookupClass);
1687             if (requestedLookupClass.isPrimitive())
1688                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1689             if (requestedLookupClass.isArray())
1690                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1691 
1692             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1693                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1694             if (requestedLookupClass == this.lookupClass)
1695                 return this;  // keep same capabilities
1696             int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1697             Module fromModule = this.lookupClass.getModule();
1698             Module targetModule = requestedLookupClass.getModule();
1699             Class<?> plc = this.previousLookupClass();
1700             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1701                 assert plc == null;
1702                 newModes = UNCONDITIONAL;
1703             } else if (fromModule != targetModule) {
1704                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1705                     // allow hopping back and forth between fromModule and plc's module
1706                     // but not the third module
1707                     newModes = 0;
1708                 }
1709                 // drop MODULE access
1710                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1711                 // teleport from this lookup class
1712                 plc = this.lookupClass;
1713             }
1714             if ((newModes & PACKAGE) != 0
1715                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1716                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1717             }
1718             // Allow nestmate lookups to be created without special privilege:
1719             if ((newModes & PRIVATE) != 0
1720                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1721                 newModes &= ~(PRIVATE|PROTECTED);
1722             }
1723             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1724                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1725                 // The requested class it not accessible from the lookup class.
1726                 // No permissions.
1727                 newModes = 0;
1728             }
1729             return newLookup(requestedLookupClass, plc, newModes);
1730         }
1731 
1732         /**
1733          * Creates a lookup on the same lookup class which this lookup object
1734          * finds members, but with a lookup mode that has lost the given lookup mode.
1735          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1736          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1737          * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1738          * {@link #UNCONDITIONAL UNCONDITIONAL}.
1739          *
1740          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1741          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1742          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1743          * lookup has no access.
1744          *
1745          * <p> If this lookup is not a public lookup, then the following applies
1746          * regardless of its {@linkplain #lookupModes() lookup modes}.
1747          * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1748          * dropped and so the resulting lookup mode will never have these access
1749          * capabilities. When dropping {@code PACKAGE}
1750          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1751          * access. When dropping {@code MODULE} then the resulting lookup will not
1752          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1753          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1754          *
1755          * @apiNote
1756          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1757          * delegate non-public access within the package of the lookup class without
1758          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1759          * A lookup with {@code MODULE} but not
1760          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1761          * the module of the lookup class without conferring package access.
1762          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1763          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1764          * to public classes accessible to both the module of the lookup class
1765          * and the module of the previous lookup class.
1766          *
1767          * @param modeToDrop the lookup mode to drop
1768          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1769          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1770          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1771          * or {@code UNCONDITIONAL}
1772          * @see MethodHandles#privateLookupIn
1773          * @since 9
1774          */
1775         public Lookup dropLookupMode(int modeToDrop) {
1776             int oldModes = lookupModes();
1777             int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1778             switch (modeToDrop) {
1779                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1780                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1781                 case PACKAGE: newModes &= ~(PRIVATE); break;
1782                 case PROTECTED:
1783                 case PRIVATE:
1784                 case ORIGINAL:
1785                 case UNCONDITIONAL: break;
1786                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1787             }
1788             if (newModes == oldModes) return this;  // return self if no change
1789             return newLookup(lookupClass(), previousLookupClass(), newModes);
1790         }
1791 
1792         /**
1793          * Creates and links a class or interface from {@code bytes}
1794          * with the same class loader and in the same runtime package and
1795          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1796          * {@linkplain #lookupClass() lookup class} as if calling
1797          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1798          * ClassLoader::defineClass}.
1799          *
1800          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1801          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1802          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1803          * that the lookup object was created by a caller in the runtime package (or derived
1804          * from a lookup originally created by suitably privileged code to a target class in
1805          * the runtime package). </p>
1806          *
1807          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1808          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1809          * same package as the lookup class. </p>
1810          *
1811          * <p> This method does not run the class initializer. The class initializer may
1812          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1813          * Specification</em>. </p>
1814          *
1815          * <p> If there is a security manager and this lookup does not have {@linkplain
1816          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1817          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1818          *
1819          * @param bytes the class bytes
1820          * @return the {@code Class} object for the class
1821          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1822          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1823          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1824          * than the lookup class or {@code bytes} is not a class or interface
1825          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1826          * @throws VerifyError if the newly created class cannot be verified
1827          * @throws LinkageError if the newly created class cannot be linked for any other reason
1828          * @throws SecurityException if a security manager is present and it
1829          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1830          * @throws NullPointerException if {@code bytes} is {@code null}
1831          * @since 9
1832          * @see Lookup#privateLookupIn
1833          * @see Lookup#dropLookupMode
1834          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1835          */
1836         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1837             ensureDefineClassPermission();
1838             if ((lookupModes() & PACKAGE) == 0)
1839                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1840             return makeClassDefiner(bytes.clone()).defineClass(false);
1841         }
1842 
1843         private void ensureDefineClassPermission() {
1844             if (allowedModes == TRUSTED)  return;
1845 
1846             if (!hasFullPrivilegeAccess()) {
1847                 @SuppressWarnings("removal")
1848                 SecurityManager sm = System.getSecurityManager();
1849                 if (sm != null)
1850                     sm.checkPermission(new RuntimePermission("defineClass"));
1851             }
1852         }
1853 
1854         /**
1855          * The set of class options that specify whether a hidden class created by
1856          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1857          * Lookup::defineHiddenClass} method is dynamically added as a new member
1858          * to the nest of a lookup class and/or whether a hidden class has
1859          * a strong relationship with the class loader marked as its defining loader.
1860          *
1861          * @since 15
1862          */
1863         public enum ClassOption {
1864             /**
1865              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1866              * of a lookup class as a nestmate.
1867              *
1868              * <p> A hidden nestmate class has access to the private members of all
1869              * classes and interfaces in the same nest.
1870              *
1871              * @see Class#getNestHost()
1872              */
1873             NESTMATE(NESTMATE_CLASS),
1874 
1875             /**
1876              * Specifies that a hidden class has a <em>strong</em>
1877              * relationship with the class loader marked as its defining loader,
1878              * as a normal class or interface has with its own defining loader.
1879              * This means that the hidden class may be unloaded if and only if
1880              * its defining loader is not reachable and thus may be reclaimed
1881              * by a garbage collector (JLS 12.7).
1882              *
1883              * <p> By default, a hidden class or interface may be unloaded
1884              * even if the class loader that is marked as its defining loader is
1885              * <a href="../ref/package-summary.html#reachability">reachable</a>.
1886 
1887              *
1888              * @jls 12.7 Unloading of Classes and Interfaces
1889              */
1890             STRONG(STRONG_LOADER_LINK);
1891 
1892             /* the flag value is used by VM at define class time */
1893             private final int flag;
1894             ClassOption(int flag) {
1895                 this.flag = flag;
1896             }
1897 
1898             static int optionsToFlag(Set<ClassOption> options) {
1899                 int flags = 0;
1900                 for (ClassOption cp : options) {
1901                     flags |= cp.flag;
1902                 }
1903                 return flags;
1904             }
1905         }
1906 
1907         /**
1908          * Creates a <em>hidden</em> class or interface from {@code bytes},
1909          * returning a {@code Lookup} on the newly created class or interface.
1910          *
1911          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1912          * which either defines {@code C} directly or delegates to another class loader.
1913          * A class loader defines {@code C} directly by invoking
1914          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1915          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1916          * to derive {@code C} from a purported representation in {@code class} file format.
1917          * In situations where use of a class loader is undesirable, a class or interface
1918          * {@code C} can be created by this method instead. This method is capable of
1919          * defining {@code C}, and thereby creating it, without invoking
1920          * {@code ClassLoader::defineClass}.
1921          * Instead, this method defines {@code C} as if by arranging for
1922          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1923          * from a purported representation in {@code class} file format
1924          * using the following rules:
1925          *
1926          * <ol>
1927          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1928          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1929          * This level of access is needed to create {@code C} in the module
1930          * of the lookup class of this {@code Lookup}.</li>
1931          *
1932          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1933          * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1934          * The major and minor version may differ from the {@code class} file version
1935          * of the lookup class of this {@code Lookup}.</li>
1936          *
1937          * <li> The value of {@code this_class} must be a valid index in the
1938          * {@code constant_pool} table, and the entry at that index must be a valid
1939          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1940          * encoded in internal form that is specified by this structure. {@code N} must
1941          * denote a class or interface in the same package as the lookup class.</li>
1942          *
1943          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1944          * where {@code <suffix>} is an unqualified name.
1945          *
1946          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1947          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1948          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1949          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1950          * refers to the new {@code CONSTANT_Utf8_info} structure.
1951          *
1952          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1953          *
1954          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1955          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1956          * with the following adjustments:
1957          * <ul>
1958          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1959          * that includes a single {@code "."} character, even though this is not a valid
1960          * binary class or interface name in internal form.</li>
1961          *
1962          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1963          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1964          *
1965          * <li> {@code C} is considered to have the same runtime
1966          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1967          * and {@linkplain java.security.ProtectionDomain protection domain}
1968          * as the lookup class of this {@code Lookup}.
1969          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1970          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1971          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1972          * <ul>
1973          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1974          *      even though this is not a valid binary class or interface name.</li>
1975          * <li> {@link Class#descriptorString()} returns the string
1976          *      {@code "L" + N + "." + <suffix> + ";"},
1977          *      even though this is not a valid type descriptor name.</li>
1978          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
1979          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
1980          * </ul>
1981          * </ul>
1982          * </li>
1983          * </ol>
1984          *
1985          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1986          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
1987          * <ul>
1988          * <li> During verification, whenever it is necessary to load the class named
1989          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
1990          * made of any class loader.</li>
1991          *
1992          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
1993          * by {@code this_class}, the symbolic reference is considered to be resolved to
1994          * {@code C} and resolution always succeeds immediately.</li>
1995          * </ul>
1996          *
1997          * <p> If the {@code initialize} parameter is {@code true},
1998          * then {@code C} is initialized by the Java Virtual Machine.
1999          *
2000          * <p> The newly created class or interface {@code C} serves as the
2001          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
2002          * returned by this method. {@code C} is <em>hidden</em> in the sense that
2003          * no other class or interface can refer to {@code C} via a constant pool entry.
2004          * That is, a hidden class or interface cannot be named as a supertype, a field type,
2005          * a method parameter type, or a method return type by any other class.
2006          * This is because a hidden class or interface does not have a binary name, so
2007          * there is no internal form available to record in any class's constant pool.
2008          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
2009          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
2010          * is not {@linkplain java.lang.instrument.Instrumentation#isModifiableClass(Class)
2011          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
2012          * JVM Tool Interface</a>.
2013          *
2014          * <p> A class or interface created by
2015          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
2016          * a class loader} has a strong relationship with that class loader.
2017          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
2018          * that {@linkplain Class#getClassLoader() defined it}.
2019          * This means that a class created by a class loader may be unloaded if and
2020          * only if its defining loader is not reachable and thus may be reclaimed
2021          * by a garbage collector (JLS 12.7).
2022          *
2023          * By default, however, a hidden class or interface may be unloaded even if
2024          * the class loader that is marked as its defining loader is
2025          * <a href="../ref/package-summary.html#reachability">reachable</a>.
2026          * This behavior is useful when a hidden class or interface serves multiple
2027          * classes defined by arbitrary class loaders.  In other cases, a hidden
2028          * class or interface may be linked to a single class (or a small number of classes)
2029          * with the same defining loader as the hidden class or interface.
2030          * In such cases, where the hidden class or interface must be coterminous
2031          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
2032          * option may be passed in {@code options}.
2033          * This arranges for a hidden class to have the same strong relationship
2034          * with the class loader marked as its defining loader,
2035          * as a normal class or interface has with its own defining loader.
2036          *
2037          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
2038          * may still prevent a hidden class or interface from being
2039          * unloaded by ensuring that the {@code Class} object is reachable.
2040          *
2041          * <p> The unloading characteristics are set for each hidden class when it is
2042          * defined, and cannot be changed later.  An advantage of allowing hidden classes
2043          * to be unloaded independently of the class loader marked as their defining loader
2044          * is that a very large number of hidden classes may be created by an application.
2045          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
2046          * just as if normal classes were created by class loaders.
2047          *
2048          * <p> Classes and interfaces in a nest are allowed to have mutual access to
2049          * their private members.  The nest relationship is determined by
2050          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
2051          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
2052          * By default, a hidden class belongs to a nest consisting only of itself
2053          * because a hidden class has no binary name.
2054          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
2055          * to create a hidden class or interface {@code C} as a member of a nest.
2056          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
2057          * in the {@code ClassFile} structure from which {@code C} was derived.
2058          * Instead, the following rules determine the nest host of {@code C}:
2059          * <ul>
2060          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
2061          *     been determined, then let {@code H} be the nest host of the lookup class.
2062          *     Otherwise, the nest host of the lookup class is determined using the
2063          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
2064          * <li>The nest host of {@code C} is determined to be {@code H},
2065          *     the nest host of the lookup class.</li>
2066          * </ul>
2067          *
2068          * <p> A hidden class or interface may be serializable, but this requires a custom
2069          * serialization mechanism in order to ensure that instances are properly serialized
2070          * and deserialized. The default serialization mechanism supports only classes and
2071          * interfaces that are discoverable by their class name.
2072          *
2073          * @param bytes the bytes that make up the class data,
2074          * in the format of a valid {@code class} file as defined by
2075          * <cite>The Java Virtual Machine Specification</cite>.
2076          * @param initialize if {@code true} the class will be initialized.
2077          * @param options {@linkplain ClassOption class options}
2078          * @return the {@code Lookup} object on the hidden class,
2079          * with {@linkplain #ORIGINAL original} and
2080          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2081          *
2082          * @throws IllegalAccessException if this {@code Lookup} does not have
2083          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2084          * @throws SecurityException if a security manager is present and it
2085          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2086          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2087          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2088          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2089          * than the lookup class or {@code bytes} is not a class or interface
2090          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2091          * @throws IncompatibleClassChangeError if the class or interface named as
2092          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2093          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2094          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2095          * {@code C} is {@code C} itself
2096          * @throws VerifyError if the newly created class cannot be verified
2097          * @throws LinkageError if the newly created class cannot be linked for any other reason
2098          * @throws NullPointerException if any parameter is {@code null}
2099          *
2100          * @since 15
2101          * @see Class#isHidden()
2102          * @jvms 4.2.1 Binary Class and Interface Names
2103          * @jvms 4.2.2 Unqualified Names
2104          * @jvms 4.7.28 The {@code NestHost} Attribute
2105          * @jvms 4.7.29 The {@code NestMembers} Attribute
2106          * @jvms 5.4.3.1 Class and Interface Resolution
2107          * @jvms 5.4.4 Access Control
2108          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2109          * @jvms 5.4 Linking
2110          * @jvms 5.5 Initialization
2111          * @jls 12.7 Unloading of Classes and Interfaces
2112          */
2113         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2114                 throws IllegalAccessException
2115         {
2116             Objects.requireNonNull(bytes);
2117             Objects.requireNonNull(options);
2118 
2119             ensureDefineClassPermission();
2120             if (!hasFullPrivilegeAccess()) {
2121                 throw new IllegalAccessException(this + " does not have full privilege access");
2122             }
2123 
2124             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
2125         }
2126 
2127         /**
2128          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2129          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2130          * returning a {@code Lookup} on the newly created class or interface.
2131          *
2132          * <p> This method is equivalent to calling
2133          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2134          * as if the hidden class is injected with a private static final <i>unnamed</i>
2135          * field which is initialized with the given {@code classData} at
2136          * the first instruction of the class initializer.
2137          * The newly created class is linked by the Java Virtual Machine.
2138          *
2139          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2140          * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2141          * methods can be used to retrieve the {@code classData}.
2142          *
2143          * @apiNote
2144          * A framework can create a hidden class with class data with one or more
2145          * objects and load the class data as dynamically-computed constant(s)
2146          * via a bootstrap method.  {@link MethodHandles#classData(Lookup, String, Class)
2147          * Class data} is accessible only to the lookup object created by the newly
2148          * defined hidden class but inaccessible to other members in the same nest
2149          * (unlike private static fields that are accessible to nestmates).
2150          * Care should be taken w.r.t. mutability for example when passing
2151          * an array or other mutable structure through the class data.
2152          * Changing any value stored in the class data at runtime may lead to
2153          * unpredictable behavior.
2154          * If the class data is a {@code List}, it is good practice to make it
2155          * unmodifiable for example via {@link List#of List::of}.
2156          *
2157          * @param bytes     the class bytes
2158          * @param classData pre-initialized class data
2159          * @param initialize if {@code true} the class will be initialized.
2160          * @param options   {@linkplain ClassOption class options}
2161          * @return the {@code Lookup} object on the hidden class,
2162          * with {@linkplain #ORIGINAL original} and
2163          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2164          *
2165          * @throws IllegalAccessException if this {@code Lookup} does not have
2166          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2167          * @throws SecurityException if a security manager is present and it
2168          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2169          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2170          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2171          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2172          * than the lookup class or {@code bytes} is not a class or interface
2173          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2174          * @throws IncompatibleClassChangeError if the class or interface named as
2175          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2176          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2177          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2178          * {@code C} is {@code C} itself
2179          * @throws VerifyError if the newly created class cannot be verified
2180          * @throws LinkageError if the newly created class cannot be linked for any other reason
2181          * @throws NullPointerException if any parameter is {@code null}
2182          *
2183          * @since 16
2184          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2185          * @see Class#isHidden()
2186          * @see MethodHandles#classData(Lookup, String, Class)
2187          * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2188          * @jvms 4.2.1 Binary Class and Interface Names
2189          * @jvms 4.2.2 Unqualified Names
2190          * @jvms 4.7.28 The {@code NestHost} Attribute
2191          * @jvms 4.7.29 The {@code NestMembers} Attribute
2192          * @jvms 5.4.3.1 Class and Interface Resolution
2193          * @jvms 5.4.4 Access Control
2194          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2195          * @jvms 5.4 Linking
2196          * @jvms 5.5 Initialization
2197          * @jls 12.7 Unloading of Classes and Interface
2198          */
2199         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2200                 throws IllegalAccessException
2201         {
2202             Objects.requireNonNull(bytes);
2203             Objects.requireNonNull(classData);
2204             Objects.requireNonNull(options);
2205 
2206             ensureDefineClassPermission();
2207             if (!hasFullPrivilegeAccess()) {
2208                 throw new IllegalAccessException(this + " does not have full privilege access");
2209             }
2210 
2211             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2212                        .defineClassAsLookup(initialize, classData);
2213         }
2214 
2215         static class ClassFile {
2216             final String name;
2217             final int accessFlags;
2218             final byte[] bytes;
2219             ClassFile(String name, int accessFlags, byte[] bytes) {
2220                 this.name = name;
2221                 this.accessFlags = accessFlags;
2222                 this.bytes = bytes;
2223             }
2224 
2225             static ClassFile newInstanceNoCheck(String name, byte[] bytes) {
2226                 return new ClassFile(name, 0, bytes);
2227             }
2228 
2229             /**
2230              * This method checks the class file version and the structure of `this_class`.
2231              * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2232              * that is in the named package.
2233              *
2234              * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2235              * or the class is not in the given package name.
2236              */
2237             static ClassFile newInstance(byte[] bytes, String pkgName) {
2238                 int magic = readInt(bytes, 0);
2239                 if (magic != 0xCAFEBABE) {
2240                     throw new ClassFormatError("Incompatible magic value: " + magic);
2241                 }
2242                 int minor = readUnsignedShort(bytes, 4);
2243                 int major = readUnsignedShort(bytes, 6);
2244                 if (!VM.isSupportedClassFileVersion(major, minor)) {
2245                     throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2246                 }
2247 
2248                 String name;
2249                 int accessFlags;
2250                 try {
2251                     ClassReader reader = new ClassReader(bytes);
2252                     // ClassReader::getClassName does not check if `this_class` is CONSTANT_Class_info
2253                     // workaround to read `this_class` using readConst and validate the value
2254                     int thisClass = reader.readUnsignedShort(reader.header + 2);
2255                     Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]);
2256                     if (!(constant instanceof Type type)) {
2257                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2258                     }
2259                     if (!type.getDescriptor().startsWith("L")) {
2260                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2261                     }
2262                     name = type.getClassName();
2263                     accessFlags = reader.readUnsignedShort(reader.header);
2264                 } catch (RuntimeException e) {
2265                     // ASM exceptions are poorly specified
2266                     ClassFormatError cfe = new ClassFormatError();
2267                     cfe.initCause(e);
2268                     throw cfe;
2269                 }
2270 
2271                 // must be a class or interface
2272                 if ((accessFlags & Opcodes.ACC_MODULE) != 0) {
2273                     throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2274                 }
2275 
2276                 // check if it's in the named package
2277                 int index = name.lastIndexOf('.');
2278                 String pn = (index == -1) ? "" : name.substring(0, index);
2279                 if (!pn.equals(pkgName)) {
2280                     throw newIllegalArgumentException(name + " not in same package as lookup class");
2281                 }
2282 
2283                 return new ClassFile(name, accessFlags, bytes);
2284             }
2285 
2286             private static int readInt(byte[] bytes, int offset) {
2287                 if ((offset+4) > bytes.length) {
2288                     throw new ClassFormatError("Invalid ClassFile structure");
2289                 }
2290                 return ((bytes[offset] & 0xFF) << 24)
2291                         | ((bytes[offset + 1] & 0xFF) << 16)
2292                         | ((bytes[offset + 2] & 0xFF) << 8)
2293                         | (bytes[offset + 3] & 0xFF);
2294             }
2295 
2296             private static int readUnsignedShort(byte[] bytes, int offset) {
2297                 if ((offset+2) > bytes.length) {
2298                     throw new ClassFormatError("Invalid ClassFile structure");
2299                 }
2300                 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2301             }
2302         }
2303 
2304         /*
2305          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2306          * from the given bytes.
2307          *
2308          * Caller should make a defensive copy of the arguments if needed
2309          * before calling this factory method.
2310          *
2311          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2312          * {@bytes} denotes a class in a different package than the lookup class
2313          */
2314         private ClassDefiner makeClassDefiner(byte[] bytes) {
2315             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2316             return new ClassDefiner(this, cf, STRONG_LOADER_LINK);
2317         }
2318 
2319         /**
2320          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2321          * from the given bytes.  The name must be in the same package as the lookup class.
2322          *
2323          * Caller should make a defensive copy of the arguments if needed
2324          * before calling this factory method.
2325          *
2326          * @param bytes   class bytes
2327          * @return ClassDefiner that defines a hidden class of the given bytes.
2328          *
2329          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2330          * {@bytes} denotes a class in a different package than the lookup class
2331          */
2332         ClassDefiner makeHiddenClassDefiner(byte[] bytes) {
2333             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2334             return makeHiddenClassDefiner(cf, Set.of(), false);
2335         }
2336 
2337         /**
2338          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2339          * from the given bytes and options.
2340          * The name must be in the same package as the lookup class.
2341          *
2342          * Caller should make a defensive copy of the arguments if needed
2343          * before calling this factory method.
2344          *
2345          * @param bytes   class bytes
2346          * @param options class options
2347          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2348          * @return ClassDefiner that defines a hidden class of the given bytes and options
2349          *
2350          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2351          * {@bytes} denotes a class in a different package than the lookup class
2352          */
2353         ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2354                                             Set<ClassOption> options,
2355                                             boolean accessVmAnnotations) {
2356             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2357             return makeHiddenClassDefiner(cf, options, accessVmAnnotations);
2358         }
2359 
2360         /**
2361          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2362          * from the given bytes.  No package name check on the given name.
2363          *
2364          * @param name    fully-qualified name that specifies the prefix of the hidden class
2365          * @param bytes   class bytes
2366          * @return ClassDefiner that defines a hidden class of the given bytes.
2367          */
2368         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes) {
2369             // skip name and access flags validation
2370             return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), Set.of(), false);
2371         }
2372 
2373         /**
2374          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2375          * from the given class file and options.
2376          *
2377          * @param cf ClassFile
2378          * @param options class options
2379          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2380          */
2381         private ClassDefiner makeHiddenClassDefiner(ClassFile cf,
2382                                                     Set<ClassOption> options,
2383                                                     boolean accessVmAnnotations) {
2384             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2385             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2386                 // jdk.internal.vm.annotations are permitted for classes
2387                 // defined to boot loader and platform loader
2388                 flags |= ACCESS_VM_ANNOTATIONS;
2389             }
2390 
2391             return new ClassDefiner(this, cf, flags);
2392         }
2393 
2394         static class ClassDefiner {
2395             private final Lookup lookup;
2396             private final String name;
2397             private final byte[] bytes;
2398             private final int classFlags;
2399 
2400             private ClassDefiner(Lookup lookup, ClassFile cf, int flags) {
2401                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2402                 this.lookup = lookup;
2403                 this.bytes = cf.bytes;
2404                 this.name = cf.name;
2405                 this.classFlags = flags;
2406             }
2407 
2408             String className() {
2409                 return name;
2410             }
2411 
2412             Class<?> defineClass(boolean initialize) {
2413                 return defineClass(initialize, null);
2414             }
2415 
2416             Lookup defineClassAsLookup(boolean initialize) {
2417                 Class<?> c = defineClass(initialize, null);
2418                 return new Lookup(c, null, FULL_POWER_MODES);
2419             }
2420 
2421             /**
2422              * Defines the class of the given bytes and the given classData.
2423              * If {@code initialize} parameter is true, then the class will be initialized.
2424              *
2425              * @param initialize true if the class to be initialized
2426              * @param classData classData or null
2427              * @return the class
2428              *
2429              * @throws LinkageError linkage error
2430              */
2431             Class<?> defineClass(boolean initialize, Object classData) {
2432                 Class<?> lookupClass = lookup.lookupClass();
2433                 ClassLoader loader = lookupClass.getClassLoader();
2434                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2435                 Class<?> c = SharedSecrets.getJavaLangAccess()
2436                         .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2437                 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2438                 return c;
2439             }
2440 
2441             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2442                 Class<?> c = defineClass(initialize, classData);
2443                 return new Lookup(c, null, FULL_POWER_MODES);
2444             }
2445 
2446             private boolean isNestmate() {
2447                 return (classFlags & NESTMATE_CLASS) != 0;
2448             }
2449         }
2450 
2451         private ProtectionDomain lookupClassProtectionDomain() {
2452             ProtectionDomain pd = cachedProtectionDomain;
2453             if (pd == null) {
2454                 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2455             }
2456             return pd;
2457         }
2458 
2459         // cached protection domain
2460         private volatile ProtectionDomain cachedProtectionDomain;
2461 
2462         // Make sure outer class is initialized first.
2463         static { IMPL_NAMES.getClass(); }
2464 
2465         /** Package-private version of lookup which is trusted. */
2466         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2467 
2468         /** Version of lookup which is trusted minimally.
2469          *  It can only be used to create method handles to publicly accessible
2470          *  members in packages that are exported unconditionally.
2471          */
2472         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2473 
2474         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2475             String name = lookupClass.getName();
2476             if (name.startsWith("java.lang.invoke."))
2477                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2478         }
2479 
2480         /**
2481          * Displays the name of the class from which lookups are to be made,
2482          * followed by "/" and the name of the {@linkplain #previousLookupClass()
2483          * previous lookup class} if present.
2484          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2485          * If there are restrictions on the access permitted to this lookup,
2486          * this is indicated by adding a suffix to the class name, consisting
2487          * of a slash and a keyword.  The keyword represents the strongest
2488          * allowed access, and is chosen as follows:
2489          * <ul>
2490          * <li>If no access is allowed, the suffix is "/noaccess".
2491          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2492          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2493          * <li>If only public and module access are allowed, the suffix is "/module".
2494          * <li>If public and package access are allowed, the suffix is "/package".
2495          * <li>If public, package, and private access are allowed, the suffix is "/private".
2496          * </ul>
2497          * If none of the above cases apply, it is the case that
2498          * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2499          * (public, module, package, private, and protected) is allowed.
2500          * In this case, no suffix is added.
2501          * This is true only of an object obtained originally from
2502          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2503          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2504          * always have restricted access, and will display a suffix.
2505          * <p>
2506          * (It may seem strange that protected access should be
2507          * stronger than private access.  Viewed independently from
2508          * package access, protected access is the first to be lost,
2509          * because it requires a direct subclass relationship between
2510          * caller and callee.)
2511          * @see #in
2512          *
2513          * @revised 9
2514          */
2515         @Override
2516         public String toString() {
2517             String cname = lookupClass.getName();
2518             if (prevLookupClass != null)
2519                 cname += "/" + prevLookupClass.getName();
2520             switch (allowedModes) {
2521             case 0:  // no privileges
2522                 return cname + "/noaccess";
2523             case UNCONDITIONAL:
2524                 return cname + "/publicLookup";
2525             case PUBLIC:
2526                 return cname + "/public";
2527             case PUBLIC|MODULE:
2528                 return cname + "/module";
2529             case PUBLIC|PACKAGE:
2530             case PUBLIC|MODULE|PACKAGE:
2531                 return cname + "/package";
2532             case PUBLIC|PACKAGE|PRIVATE:
2533             case PUBLIC|MODULE|PACKAGE|PRIVATE:
2534                     return cname + "/private";
2535             case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2536             case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2537             case FULL_POWER_MODES:
2538                     return cname;
2539             case TRUSTED:
2540                 return "/trusted";  // internal only; not exported
2541             default:  // Should not happen, but it's a bitfield...
2542                 cname = cname + "/" + Integer.toHexString(allowedModes);
2543                 assert(false) : cname;
2544                 return cname;
2545             }
2546         }
2547 
2548         /**
2549          * Produces a method handle for a static method.
2550          * The type of the method handle will be that of the method.
2551          * (Since static methods do not take receivers, there is no
2552          * additional receiver argument inserted into the method handle type,
2553          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2554          * The method and all its argument types must be accessible to the lookup object.
2555          * <p>
2556          * The returned method handle will have
2557          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2558          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2559          * <p>
2560          * If the returned method handle is invoked, the method's class will
2561          * be initialized, if it has not already been initialized.
2562          * <p><b>Example:</b>
2563          * <blockquote><pre>{@code
2564 import static java.lang.invoke.MethodHandles.*;
2565 import static java.lang.invoke.MethodType.*;
2566 ...
2567 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2568   "asList", methodType(List.class, Object[].class));
2569 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2570          * }</pre></blockquote>
2571          * @param refc the class from which the method is accessed
2572          * @param name the name of the method
2573          * @param type the type of the method
2574          * @return the desired method handle
2575          * @throws NoSuchMethodException if the method does not exist
2576          * @throws IllegalAccessException if access checking fails,
2577          *                                or if the method is not {@code static},
2578          *                                or if the method's variable arity modifier bit
2579          *                                is set and {@code asVarargsCollector} fails
2580          * @throws    SecurityException if a security manager is present and it
2581          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2582          * @throws NullPointerException if any argument is null
2583          */
2584         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2585             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2586             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2587         }
2588 
2589         /**
2590          * Produces a method handle for a virtual method.
2591          * The type of the method handle will be that of the method,
2592          * with the receiver type (usually {@code refc}) prepended.
2593          * The method and all its argument types must be accessible to the lookup object.
2594          * <p>
2595          * When called, the handle will treat the first argument as a receiver
2596          * and, for non-private methods, dispatch on the receiver's type to determine which method
2597          * implementation to enter.
2598          * For private methods the named method in {@code refc} will be invoked on the receiver.
2599          * (The dispatching action is identical with that performed by an
2600          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2601          * <p>
2602          * The first argument will be of type {@code refc} if the lookup
2603          * class has full privileges to access the member.  Otherwise
2604          * the member must be {@code protected} and the first argument
2605          * will be restricted in type to the lookup class.
2606          * <p>
2607          * The returned method handle will have
2608          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2609          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2610          * <p>
2611          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2612          * instructions and method handles produced by {@code findVirtual},
2613          * if the class is {@code MethodHandle} and the name string is
2614          * {@code invokeExact} or {@code invoke}, the resulting
2615          * method handle is equivalent to one produced by
2616          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2617          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2618          * with the same {@code type} argument.
2619          * <p>
2620          * If the class is {@code VarHandle} and the name string corresponds to
2621          * the name of a signature-polymorphic access mode method, the resulting
2622          * method handle is equivalent to one produced by
2623          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2624          * the access mode corresponding to the name string and with the same
2625          * {@code type} arguments.
2626          * <p>
2627          * <b>Example:</b>
2628          * <blockquote><pre>{@code
2629 import static java.lang.invoke.MethodHandles.*;
2630 import static java.lang.invoke.MethodType.*;
2631 ...
2632 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2633   "concat", methodType(String.class, String.class));
2634 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2635   "hashCode", methodType(int.class));
2636 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2637   "hashCode", methodType(int.class));
2638 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2639 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2640 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2641 // interface method:
2642 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2643   "subSequence", methodType(CharSequence.class, int.class, int.class));
2644 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2645 // constructor "internal method" must be accessed differently:
2646 MethodType MT_newString = methodType(void.class); //()V for new String()
2647 try { assertEquals("impossible", lookup()
2648         .findVirtual(String.class, "<init>", MT_newString));
2649  } catch (NoSuchMethodException ex) { } // OK
2650 MethodHandle MH_newString = publicLookup()
2651   .findConstructor(String.class, MT_newString);
2652 assertEquals("", (String) MH_newString.invokeExact());
2653          * }</pre></blockquote>
2654          *
2655          * @param refc the class or interface from which the method is accessed
2656          * @param name the name of the method
2657          * @param type the type of the method, with the receiver argument omitted
2658          * @return the desired method handle
2659          * @throws NoSuchMethodException if the method does not exist
2660          * @throws IllegalAccessException if access checking fails,
2661          *                                or if the method is {@code static},
2662          *                                or if the method's variable arity modifier bit
2663          *                                is set and {@code asVarargsCollector} fails
2664          * @throws    SecurityException if a security manager is present and it
2665          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2666          * @throws NullPointerException if any argument is null
2667          */
2668         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2669             if (refc == MethodHandle.class) {
2670                 MethodHandle mh = findVirtualForMH(name, type);
2671                 if (mh != null)  return mh;
2672             } else if (refc == VarHandle.class) {
2673                 MethodHandle mh = findVirtualForVH(name, type);
2674                 if (mh != null)  return mh;
2675             }
2676             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2677             MemberName method = resolveOrFail(refKind, refc, name, type);
2678             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2679         }
2680         private MethodHandle findVirtualForMH(String name, MethodType type) {
2681             // these names require special lookups because of the implicit MethodType argument
2682             if ("invoke".equals(name))
2683                 return invoker(type);
2684             if ("invokeExact".equals(name))
2685                 return exactInvoker(type);
2686             assert(!MemberName.isMethodHandleInvokeName(name));
2687             return null;
2688         }
2689         private MethodHandle findVirtualForVH(String name, MethodType type) {
2690             try {
2691                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2692             } catch (IllegalArgumentException e) {
2693                 return null;
2694             }
2695         }
2696 
2697         /**
2698          * Produces a method handle which creates an object and initializes it, using
2699          * the constructor of the specified type.
2700          * The parameter types of the method handle will be those of the constructor,
2701          * while the return type will be a reference to the constructor's class.
2702          * The constructor and all its argument types must be accessible to the lookup object.
2703          * <p>
2704          * The requested type must have a return type of {@code void}.
2705          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2706          * <p>
2707          * The returned method handle will have
2708          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2709          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2710          * <p>
2711          * If the returned method handle is invoked, the constructor's class will
2712          * be initialized, if it has not already been initialized.
2713          * <p><b>Example:</b>
2714          * <blockquote><pre>{@code
2715 import static java.lang.invoke.MethodHandles.*;
2716 import static java.lang.invoke.MethodType.*;
2717 ...
2718 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2719   ArrayList.class, methodType(void.class, Collection.class));
2720 Collection orig = Arrays.asList("x", "y");
2721 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2722 assert(orig != copy);
2723 assertEquals(orig, copy);
2724 // a variable-arity constructor:
2725 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2726   ProcessBuilder.class, methodType(void.class, String[].class));
2727 ProcessBuilder pb = (ProcessBuilder)
2728   MH_newProcessBuilder.invoke("x", "y", "z");
2729 assertEquals("[x, y, z]", pb.command().toString());
2730          * }</pre></blockquote>
2731          * @param refc the class or interface from which the method is accessed
2732          * @param type the type of the method, with the receiver argument omitted, and a void return type
2733          * @return the desired method handle
2734          * @throws NoSuchMethodException if the constructor does not exist
2735          * @throws IllegalAccessException if access checking fails
2736          *                                or if the method's variable arity modifier bit
2737          *                                is set and {@code asVarargsCollector} fails
2738          * @throws    SecurityException if a security manager is present and it
2739          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2740          * @throws NullPointerException if any argument is null
2741          */
2742         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2743             if (refc.isArray()) {
2744                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2745             }
2746             String name = "<init>";
2747             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2748             return getDirectConstructor(refc, ctor);
2749         }
2750 
2751         /**
2752          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2753          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2754          * Such a resolution, as specified in JVMS 5.4.3.1 section, attempts to locate and load the class,
2755          * and then determines whether the class is accessible to this lookup object.
2756          * <p>
2757          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2758          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2759          *
2760          * @param targetName the fully qualified name of the class to be looked up.
2761          * @return the requested class.
2762          * @throws SecurityException if a security manager is present and it
2763          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2764          * @throws LinkageError if the linkage fails
2765          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2766          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2767          * modes.
2768          * @throws NullPointerException if {@code targetName} is null
2769          * @since 9
2770          * @jvms 5.4.3.1 Class and Interface Resolution
2771          */
2772         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2773             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2774             return accessClass(targetClass);
2775         }
2776 
2777         /**
2778          * Ensures that {@code targetClass} has been initialized. The class
2779          * to be initialized must be {@linkplain #accessClass accessible}
2780          * to this {@code Lookup} object.  This method causes {@code targetClass}
2781          * to be initialized if it has not been already initialized,
2782          * as specified in JVMS {@jvms 5.5}.
2783          *
2784          * <p>
2785          * This method returns when {@code targetClass} is fully initialized, or
2786          * when {@code targetClass} is being initialized by the current thread.
2787          *
2788          * @param targetClass the class to be initialized
2789          * @return {@code targetClass} that has been initialized, or that is being
2790          *         initialized by the current thread.
2791          *
2792          * @throws  IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2793          *          or array class
2794          * @throws  IllegalAccessException if {@code targetClass} is not
2795          *          {@linkplain #accessClass accessible} to this lookup
2796          * @throws  ExceptionInInitializerError if the class initialization provoked
2797          *          by this method fails
2798          * @throws  SecurityException if a security manager is present and it
2799          *          <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2800          * @since 15
2801          * @jvms 5.5 Initialization
2802          */
2803         public Class<?> ensureInitialized(Class<?> targetClass) throws IllegalAccessException {
2804             if (targetClass.isPrimitive())
2805                 throw new IllegalArgumentException(targetClass + " is a primitive class");
2806             if (targetClass.isArray())
2807                 throw new IllegalArgumentException(targetClass + " is an array class");
2808 
2809             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2810                 throw makeAccessException(targetClass);
2811             }
2812             checkSecurityManager(targetClass);
2813 
2814             // ensure class initialization
2815             Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2816             return targetClass;
2817         }
2818 
2819         /*
2820          * Returns IllegalAccessException due to access violation to the given targetClass.
2821          *
2822          * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2823          * which verifies access to a class rather a member.
2824          */
2825         private IllegalAccessException makeAccessException(Class<?> targetClass) {
2826             String message = "access violation: "+ targetClass;
2827             if (this == MethodHandles.publicLookup()) {
2828                 message += ", from public Lookup";
2829             } else {
2830                 Module m = lookupClass().getModule();
2831                 message += ", from " + lookupClass() + " (" + m + ")";
2832                 if (prevLookupClass != null) {
2833                     message += ", previous lookup " +
2834                             prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2835                 }
2836             }
2837             return new IllegalAccessException(message);
2838         }
2839 
2840         /**
2841          * Determines if a class can be accessed from the lookup context defined by
2842          * this {@code Lookup} object. The static initializer of the class is not run.
2843          * If {@code targetClass} is an array class, {@code targetClass} is accessible
2844          * if the element type of the array class is accessible.  Otherwise,
2845          * {@code targetClass} is determined as accessible as follows.
2846          *
2847          * <p>
2848          * If {@code targetClass} is in the same module as the lookup class,
2849          * the lookup class is {@code LC} in module {@code M1} and
2850          * the previous lookup class is in module {@code M0} or
2851          * {@code null} if not present,
2852          * {@code targetClass} is accessible if and only if one of the following is true:
2853          * <ul>
2854          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2855          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2856          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2857          *     in the same runtime package of {@code LC}.</li>
2858          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2859          *     a public type in {@code M1}.</li>
2860          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2861          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2862          *     if the previous lookup class is present; otherwise, {@code targetClass}
2863          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2864          * </ul>
2865          *
2866          * <p>
2867          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2868          * can access public types in all modules when the type is in a package
2869          * that is exported unconditionally.
2870          * <p>
2871          * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2872          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2873          * is inaccessible.
2874          * <p>
2875          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2876          * {@code M1} is the module containing {@code lookupClass} and
2877          * {@code M2} is the module containing {@code targetClass},
2878          * then {@code targetClass} is accessible if and only if
2879          * <ul>
2880          * <li>{@code M1} reads {@code M2}, and
2881          * <li>{@code targetClass} is public and in a package exported by
2882          *     {@code M2} at least to {@code M1}.
2883          * </ul>
2884          * <p>
2885          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2886          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2887          * containing the previous lookup class, then {@code targetClass} is accessible
2888          * if and only if one of the following is true:
2889          * <ul>
2890          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2891          *     {@linkplain Module#reads reads} {@code M0} and the type is
2892          *     in a package that is exported to at least {@code M1}.
2893          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2894          *     {@linkplain Module#reads reads} {@code M1} and the type is
2895          *     in a package that is exported to at least {@code M0}.
2896          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2897          *     and {@code M1} reads {@code M2} and the type is in a package
2898          *     that is exported to at least both {@code M0} and {@code M2}.
2899          * </ul>
2900          * <p>
2901          * Otherwise, {@code targetClass} is not accessible.
2902          *
2903          * @param targetClass the class to be access-checked
2904          * @return the class that has been access-checked
2905          * @throws IllegalAccessException if the class is not accessible from the lookup class
2906          * and previous lookup class, if present, using the allowed access modes.
2907          * @throws SecurityException if a security manager is present and it
2908          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2909          * @throws NullPointerException if {@code targetClass} is {@code null}
2910          * @since 9
2911          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
2912          */
2913         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
2914             if (!isClassAccessible(targetClass)) {
2915                 throw makeAccessException(targetClass);
2916             }
2917             checkSecurityManager(targetClass);
2918             return targetClass;
2919         }
2920 
2921         /**
2922          * Produces an early-bound method handle for a virtual method.
2923          * It will bypass checks for overriding methods on the receiver,
2924          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
2925          * instruction from within the explicitly specified {@code specialCaller}.
2926          * The type of the method handle will be that of the method,
2927          * with a suitably restricted receiver type prepended.
2928          * (The receiver type will be {@code specialCaller} or a subtype.)
2929          * The method and all its argument types must be accessible
2930          * to the lookup object.
2931          * <p>
2932          * Before method resolution,
2933          * if the explicitly specified caller class is not identical with the
2934          * lookup class, or if this lookup object does not have
2935          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
2936          * privileges, the access fails.
2937          * <p>
2938          * The returned method handle will have
2939          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2940          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2941          * <p style="font-size:smaller;">
2942          * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
2943          * even though the {@code invokespecial} instruction can refer to them
2944          * in special circumstances.  Use {@link #findConstructor findConstructor}
2945          * to access instance initialization methods in a safe manner.)</em>
2946          * <p><b>Example:</b>
2947          * <blockquote><pre>{@code
2948 import static java.lang.invoke.MethodHandles.*;
2949 import static java.lang.invoke.MethodType.*;
2950 ...
2951 static class Listie extends ArrayList {
2952   public String toString() { return "[wee Listie]"; }
2953   static Lookup lookup() { return MethodHandles.lookup(); }
2954 }
2955 ...
2956 // no access to constructor via invokeSpecial:
2957 MethodHandle MH_newListie = Listie.lookup()
2958   .findConstructor(Listie.class, methodType(void.class));
2959 Listie l = (Listie) MH_newListie.invokeExact();
2960 try { assertEquals("impossible", Listie.lookup().findSpecial(
2961         Listie.class, "<init>", methodType(void.class), Listie.class));
2962  } catch (NoSuchMethodException ex) { } // OK
2963 // access to super and self methods via invokeSpecial:
2964 MethodHandle MH_super = Listie.lookup().findSpecial(
2965   ArrayList.class, "toString" , methodType(String.class), Listie.class);
2966 MethodHandle MH_this = Listie.lookup().findSpecial(
2967   Listie.class, "toString" , methodType(String.class), Listie.class);
2968 MethodHandle MH_duper = Listie.lookup().findSpecial(
2969   Object.class, "toString" , methodType(String.class), Listie.class);
2970 assertEquals("[]", (String) MH_super.invokeExact(l));
2971 assertEquals(""+l, (String) MH_this.invokeExact(l));
2972 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
2973 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
2974         String.class, "toString", methodType(String.class), Listie.class));
2975  } catch (IllegalAccessException ex) { } // OK
2976 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
2977 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
2978          * }</pre></blockquote>
2979          *
2980          * @param refc the class or interface from which the method is accessed
2981          * @param name the name of the method (which must not be "&lt;init&gt;")
2982          * @param type the type of the method, with the receiver argument omitted
2983          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
2984          * @return the desired method handle
2985          * @throws NoSuchMethodException if the method does not exist
2986          * @throws IllegalAccessException if access checking fails,
2987          *                                or if the method is {@code static},
2988          *                                or if the method's variable arity modifier bit
2989          *                                is set and {@code asVarargsCollector} fails
2990          * @throws    SecurityException if a security manager is present and it
2991          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2992          * @throws NullPointerException if any argument is null
2993          */
2994         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
2995                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
2996             checkSpecialCaller(specialCaller, refc);
2997             Lookup specialLookup = this.in(specialCaller);
2998             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
2999             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
3000         }
3001 
3002         /**
3003          * Produces a method handle giving read access to a non-static field.
3004          * The type of the method handle will have a return type of the field's
3005          * value type.
3006          * The method handle's single argument will be the instance containing
3007          * the field.
3008          * Access checking is performed immediately on behalf of the lookup class.
3009          * @param refc the class or interface from which the method is accessed
3010          * @param name the field's name
3011          * @param type the field's type
3012          * @return a method handle which can load values from the field
3013          * @throws NoSuchFieldException if the field does not exist
3014          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3015          * @throws    SecurityException if a security manager is present and it
3016          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3017          * @throws NullPointerException if any argument is null
3018          * @see #findVarHandle(Class, String, Class)
3019          */
3020         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3021             MemberName field = resolveOrFail(REF_getField, refc, name, type);
3022             return getDirectField(REF_getField, refc, field);
3023         }
3024 
3025         /**
3026          * Produces a method handle giving write access to a non-static field.
3027          * The type of the method handle will have a void return type.
3028          * The method handle will take two arguments, the instance containing
3029          * the field, and the value to be stored.
3030          * The second argument will be of the field's value type.
3031          * Access checking is performed immediately on behalf of the lookup class.
3032          * @param refc the class or interface from which the method is accessed
3033          * @param name the field's name
3034          * @param type the field's type
3035          * @return a method handle which can store values into the field
3036          * @throws NoSuchFieldException if the field does not exist
3037          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3038          *                                or {@code final}
3039          * @throws    SecurityException if a security manager is present and it
3040          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3041          * @throws NullPointerException if any argument is null
3042          * @see #findVarHandle(Class, String, Class)
3043          */
3044         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3045             MemberName field = resolveOrFail(REF_putField, refc, name, type);
3046             return getDirectField(REF_putField, refc, field);
3047         }
3048 
3049         /**
3050          * Produces a VarHandle giving access to a non-static field {@code name}
3051          * of type {@code type} declared in a class of type {@code recv}.
3052          * The VarHandle's variable type is {@code type} and it has one
3053          * coordinate type, {@code recv}.
3054          * <p>
3055          * Access checking is performed immediately on behalf of the lookup
3056          * class.
3057          * <p>
3058          * Certain access modes of the returned VarHandle are unsupported under
3059          * the following conditions:
3060          * <ul>
3061          * <li>if the field is declared {@code final}, then the write, atomic
3062          *     update, numeric atomic update, and bitwise atomic update access
3063          *     modes are unsupported.
3064          * <li>if the field type is anything other than {@code byte},
3065          *     {@code short}, {@code char}, {@code int}, {@code long},
3066          *     {@code float}, or {@code double} then numeric atomic update
3067          *     access modes are unsupported.
3068          * <li>if the field type is anything other than {@code boolean},
3069          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3070          *     {@code long} then bitwise atomic update access modes are
3071          *     unsupported.
3072          * </ul>
3073          * <p>
3074          * If the field is declared {@code volatile} then the returned VarHandle
3075          * will override access to the field (effectively ignore the
3076          * {@code volatile} declaration) in accordance to its specified
3077          * access modes.
3078          * <p>
3079          * If the field type is {@code float} or {@code double} then numeric
3080          * and atomic update access modes compare values using their bitwise
3081          * representation (see {@link Float#floatToRawIntBits} and
3082          * {@link Double#doubleToRawLongBits}, respectively).
3083          * @apiNote
3084          * Bitwise comparison of {@code float} values or {@code double} values,
3085          * as performed by the numeric and atomic update access modes, differ
3086          * from the primitive {@code ==} operator and the {@link Float#equals}
3087          * and {@link Double#equals} methods, specifically with respect to
3088          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3089          * Care should be taken when performing a compare and set or a compare
3090          * and exchange operation with such values since the operation may
3091          * unexpectedly fail.
3092          * There are many possible NaN values that are considered to be
3093          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3094          * provided by Java can distinguish between them.  Operation failure can
3095          * occur if the expected or witness value is a NaN value and it is
3096          * transformed (perhaps in a platform specific manner) into another NaN
3097          * value, and thus has a different bitwise representation (see
3098          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3099          * details).
3100          * The values {@code -0.0} and {@code +0.0} have different bitwise
3101          * representations but are considered equal when using the primitive
3102          * {@code ==} operator.  Operation failure can occur if, for example, a
3103          * numeric algorithm computes an expected value to be say {@code -0.0}
3104          * and previously computed the witness value to be say {@code +0.0}.
3105          * @param recv the receiver class, of type {@code R}, that declares the
3106          * non-static field
3107          * @param name the field's name
3108          * @param type the field's type, of type {@code T}
3109          * @return a VarHandle giving access to non-static fields.
3110          * @throws NoSuchFieldException if the field does not exist
3111          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3112          * @throws    SecurityException if a security manager is present and it
3113          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3114          * @throws NullPointerException if any argument is null
3115          * @since 9
3116          */
3117         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3118             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3119             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3120             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3121         }
3122 
3123         /**
3124          * Produces a method handle giving read access to a static field.
3125          * The type of the method handle will have a return type of the field's
3126          * value type.
3127          * The method handle will take no arguments.
3128          * Access checking is performed immediately on behalf of the lookup class.
3129          * <p>
3130          * If the returned method handle is invoked, the field's class will
3131          * be initialized, if it has not already been initialized.
3132          * @param refc the class or interface from which the method is accessed
3133          * @param name the field's name
3134          * @param type the field's type
3135          * @return a method handle which can load values from the field
3136          * @throws NoSuchFieldException if the field does not exist
3137          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3138          * @throws    SecurityException if a security manager is present and it
3139          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3140          * @throws NullPointerException if any argument is null
3141          */
3142         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3143             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3144             return getDirectField(REF_getStatic, refc, field);
3145         }
3146 
3147         /**
3148          * Produces a method handle giving write access to a static field.
3149          * The type of the method handle will have a void return type.
3150          * The method handle will take a single
3151          * argument, of the field's value type, the value to be stored.
3152          * Access checking is performed immediately on behalf of the lookup class.
3153          * <p>
3154          * If the returned method handle is invoked, the field's class will
3155          * be initialized, if it has not already been initialized.
3156          * @param refc the class or interface from which the method is accessed
3157          * @param name the field's name
3158          * @param type the field's type
3159          * @return a method handle which can store values into the field
3160          * @throws NoSuchFieldException if the field does not exist
3161          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3162          *                                or is {@code final}
3163          * @throws    SecurityException if a security manager is present and it
3164          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3165          * @throws NullPointerException if any argument is null
3166          */
3167         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3168             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3169             return getDirectField(REF_putStatic, refc, field);
3170         }
3171 
3172         /**
3173          * Produces a VarHandle giving access to a static field {@code name} of
3174          * type {@code type} declared in a class of type {@code decl}.
3175          * The VarHandle's variable type is {@code type} and it has no
3176          * coordinate types.
3177          * <p>
3178          * Access checking is performed immediately on behalf of the lookup
3179          * class.
3180          * <p>
3181          * If the returned VarHandle is operated on, the declaring class will be
3182          * initialized, if it has not already been initialized.
3183          * <p>
3184          * Certain access modes of the returned VarHandle are unsupported under
3185          * the following conditions:
3186          * <ul>
3187          * <li>if the field is declared {@code final}, then the write, atomic
3188          *     update, numeric atomic update, and bitwise atomic update access
3189          *     modes are unsupported.
3190          * <li>if the field type is anything other than {@code byte},
3191          *     {@code short}, {@code char}, {@code int}, {@code long},
3192          *     {@code float}, or {@code double}, then numeric atomic update
3193          *     access modes are unsupported.
3194          * <li>if the field type is anything other than {@code boolean},
3195          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3196          *     {@code long} then bitwise atomic update access modes are
3197          *     unsupported.
3198          * </ul>
3199          * <p>
3200          * If the field is declared {@code volatile} then the returned VarHandle
3201          * will override access to the field (effectively ignore the
3202          * {@code volatile} declaration) in accordance to its specified
3203          * access modes.
3204          * <p>
3205          * If the field type is {@code float} or {@code double} then numeric
3206          * and atomic update access modes compare values using their bitwise
3207          * representation (see {@link Float#floatToRawIntBits} and
3208          * {@link Double#doubleToRawLongBits}, respectively).
3209          * @apiNote
3210          * Bitwise comparison of {@code float} values or {@code double} values,
3211          * as performed by the numeric and atomic update access modes, differ
3212          * from the primitive {@code ==} operator and the {@link Float#equals}
3213          * and {@link Double#equals} methods, specifically with respect to
3214          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3215          * Care should be taken when performing a compare and set or a compare
3216          * and exchange operation with such values since the operation may
3217          * unexpectedly fail.
3218          * There are many possible NaN values that are considered to be
3219          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3220          * provided by Java can distinguish between them.  Operation failure can
3221          * occur if the expected or witness value is a NaN value and it is
3222          * transformed (perhaps in a platform specific manner) into another NaN
3223          * value, and thus has a different bitwise representation (see
3224          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3225          * details).
3226          * The values {@code -0.0} and {@code +0.0} have different bitwise
3227          * representations but are considered equal when using the primitive
3228          * {@code ==} operator.  Operation failure can occur if, for example, a
3229          * numeric algorithm computes an expected value to be say {@code -0.0}
3230          * and previously computed the witness value to be say {@code +0.0}.
3231          * @param decl the class that declares the static field
3232          * @param name the field's name
3233          * @param type the field's type, of type {@code T}
3234          * @return a VarHandle giving access to a static field
3235          * @throws NoSuchFieldException if the field does not exist
3236          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3237          * @throws    SecurityException if a security manager is present and it
3238          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3239          * @throws NullPointerException if any argument is null
3240          * @since 9
3241          */
3242         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3243             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3244             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3245             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3246         }
3247 
3248         /**
3249          * Produces an early-bound method handle for a non-static method.
3250          * The receiver must have a supertype {@code defc} in which a method
3251          * of the given name and type is accessible to the lookup class.
3252          * The method and all its argument types must be accessible to the lookup object.
3253          * The type of the method handle will be that of the method,
3254          * without any insertion of an additional receiver parameter.
3255          * The given receiver will be bound into the method handle,
3256          * so that every call to the method handle will invoke the
3257          * requested method on the given receiver.
3258          * <p>
3259          * The returned method handle will have
3260          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3261          * the method's variable arity modifier bit ({@code 0x0080}) is set
3262          * <em>and</em> the trailing array argument is not the only argument.
3263          * (If the trailing array argument is the only argument,
3264          * the given receiver value will be bound to it.)
3265          * <p>
3266          * This is almost equivalent to the following code, with some differences noted below:
3267          * <blockquote><pre>{@code
3268 import static java.lang.invoke.MethodHandles.*;
3269 import static java.lang.invoke.MethodType.*;
3270 ...
3271 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3272 MethodHandle mh1 = mh0.bindTo(receiver);
3273 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3274 return mh1;
3275          * }</pre></blockquote>
3276          * where {@code defc} is either {@code receiver.getClass()} or a super
3277          * type of that class, in which the requested method is accessible
3278          * to the lookup class.
3279          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3280          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3281          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3282          * the receiver is restricted by {@code findVirtual} to the lookup class.)
3283          * @param receiver the object from which the method is accessed
3284          * @param name the name of the method
3285          * @param type the type of the method, with the receiver argument omitted
3286          * @return the desired method handle
3287          * @throws NoSuchMethodException if the method does not exist
3288          * @throws IllegalAccessException if access checking fails
3289          *                                or if the method's variable arity modifier bit
3290          *                                is set and {@code asVarargsCollector} fails
3291          * @throws    SecurityException if a security manager is present and it
3292          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3293          * @throws NullPointerException if any argument is null
3294          * @see MethodHandle#bindTo
3295          * @see #findVirtual
3296          */
3297         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3298             Class<? extends Object> refc = receiver.getClass(); // may get NPE
3299             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3300             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3301             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3302                 throw new IllegalAccessException("The restricted defining class " +
3303                                                  mh.type().leadingReferenceParameter().getName() +
3304                                                  " is not assignable from receiver class " +
3305                                                  receiver.getClass().getName());
3306             }
3307             return mh.bindArgumentL(0, receiver).setVarargs(method);
3308         }
3309 
3310         /**
3311          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3312          * to <i>m</i>, if the lookup class has permission.
3313          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3314          * If <i>m</i> is virtual, overriding is respected on every call.
3315          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3316          * The type of the method handle will be that of the method,
3317          * with the receiver type prepended (but only if it is non-static).
3318          * If the method's {@code accessible} flag is not set,
3319          * access checking is performed immediately on behalf of the lookup class.
3320          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3321          * <p>
3322          * The returned method handle will have
3323          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3324          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3325          * <p>
3326          * If <i>m</i> is static, and
3327          * if the returned method handle is invoked, the method's class will
3328          * be initialized, if it has not already been initialized.
3329          * @param m the reflected method
3330          * @return a method handle which can invoke the reflected method
3331          * @throws IllegalAccessException if access checking fails
3332          *                                or if the method's variable arity modifier bit
3333          *                                is set and {@code asVarargsCollector} fails
3334          * @throws NullPointerException if the argument is null
3335          */
3336         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3337             if (m.getDeclaringClass() == MethodHandle.class) {
3338                 MethodHandle mh = unreflectForMH(m);
3339                 if (mh != null)  return mh;
3340             }
3341             if (m.getDeclaringClass() == VarHandle.class) {
3342                 MethodHandle mh = unreflectForVH(m);
3343                 if (mh != null)  return mh;
3344             }
3345             MemberName method = new MemberName(m);
3346             byte refKind = method.getReferenceKind();
3347             if (refKind == REF_invokeSpecial)
3348                 refKind = REF_invokeVirtual;
3349             assert(method.isMethod());
3350             @SuppressWarnings("deprecation")
3351             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3352             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3353         }
3354         private MethodHandle unreflectForMH(Method m) {
3355             // these names require special lookups because they throw UnsupportedOperationException
3356             if (MemberName.isMethodHandleInvokeName(m.getName()))
3357                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3358             return null;
3359         }
3360         private MethodHandle unreflectForVH(Method m) {
3361             // these names require special lookups because they throw UnsupportedOperationException
3362             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3363                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3364             return null;
3365         }
3366 
3367         /**
3368          * Produces a method handle for a reflected method.
3369          * It will bypass checks for overriding methods on the receiver,
3370          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3371          * instruction from within the explicitly specified {@code specialCaller}.
3372          * The type of the method handle will be that of the method,
3373          * with a suitably restricted receiver type prepended.
3374          * (The receiver type will be {@code specialCaller} or a subtype.)
3375          * If the method's {@code accessible} flag is not set,
3376          * access checking is performed immediately on behalf of the lookup class,
3377          * as if {@code invokespecial} instruction were being linked.
3378          * <p>
3379          * Before method resolution,
3380          * if the explicitly specified caller class is not identical with the
3381          * lookup class, or if this lookup object does not have
3382          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3383          * privileges, the access fails.
3384          * <p>
3385          * The returned method handle will have
3386          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3387          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3388          * @param m the reflected method
3389          * @param specialCaller the class nominally calling the method
3390          * @return a method handle which can invoke the reflected method
3391          * @throws IllegalAccessException if access checking fails,
3392          *                                or if the method is {@code static},
3393          *                                or if the method's variable arity modifier bit
3394          *                                is set and {@code asVarargsCollector} fails
3395          * @throws NullPointerException if any argument is null
3396          */
3397         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3398             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3399             Lookup specialLookup = this.in(specialCaller);
3400             MemberName method = new MemberName(m, true);
3401             assert(method.isMethod());
3402             // ignore m.isAccessible:  this is a new kind of access
3403             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3404         }
3405 
3406         /**
3407          * Produces a method handle for a reflected constructor.
3408          * The type of the method handle will be that of the constructor,
3409          * with the return type changed to the declaring class.
3410          * The method handle will perform a {@code newInstance} operation,
3411          * creating a new instance of the constructor's class on the
3412          * arguments passed to the method handle.
3413          * <p>
3414          * If the constructor's {@code accessible} flag is not set,
3415          * access checking is performed immediately on behalf of the lookup class.
3416          * <p>
3417          * The returned method handle will have
3418          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3419          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3420          * <p>
3421          * If the returned method handle is invoked, the constructor's class will
3422          * be initialized, if it has not already been initialized.
3423          * @param c the reflected constructor
3424          * @return a method handle which can invoke the reflected constructor
3425          * @throws IllegalAccessException if access checking fails
3426          *                                or if the method's variable arity modifier bit
3427          *                                is set and {@code asVarargsCollector} fails
3428          * @throws NullPointerException if the argument is null
3429          */
3430         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3431             MemberName ctor = new MemberName(c);
3432             assert(ctor.isConstructor());
3433             @SuppressWarnings("deprecation")
3434             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3435             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
3436         }
3437 
3438         /**
3439          * Produces a method handle giving read access to a reflected field.
3440          * The type of the method handle will have a return type of the field's
3441          * value type.
3442          * If the field is {@code static}, the method handle will take no arguments.
3443          * Otherwise, its single argument will be the instance containing
3444          * the field.
3445          * If the {@code Field} object's {@code accessible} flag is not set,
3446          * access checking is performed immediately on behalf of the lookup class.
3447          * <p>
3448          * If the field is static, and
3449          * if the returned method handle is invoked, the field's class will
3450          * be initialized, if it has not already been initialized.
3451          * @param f the reflected field
3452          * @return a method handle which can load values from the reflected field
3453          * @throws IllegalAccessException if access checking fails
3454          * @throws NullPointerException if the argument is null
3455          */
3456         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3457             return unreflectField(f, false);
3458         }
3459 
3460         /**
3461          * Produces a method handle giving write access to a reflected field.
3462          * The type of the method handle will have a void return type.
3463          * If the field is {@code static}, the method handle will take a single
3464          * argument, of the field's value type, the value to be stored.
3465          * Otherwise, the two arguments will be the instance containing
3466          * the field, and the value to be stored.
3467          * If the {@code Field} object's {@code accessible} flag is not set,
3468          * access checking is performed immediately on behalf of the lookup class.
3469          * <p>
3470          * If the field is {@code final}, write access will not be
3471          * allowed and access checking will fail, except under certain
3472          * narrow circumstances documented for {@link Field#set Field.set}.
3473          * A method handle is returned only if a corresponding call to
3474          * the {@code Field} object's {@code set} method could return
3475          * normally.  In particular, fields which are both {@code static}
3476          * and {@code final} may never be set.
3477          * <p>
3478          * If the field is {@code static}, and
3479          * if the returned method handle is invoked, the field's class will
3480          * be initialized, if it has not already been initialized.
3481          * @param f the reflected field
3482          * @return a method handle which can store values into the reflected field
3483          * @throws IllegalAccessException if access checking fails,
3484          *         or if the field is {@code final} and write access
3485          *         is not enabled on the {@code Field} object
3486          * @throws NullPointerException if the argument is null
3487          */
3488         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3489             return unreflectField(f, true);
3490         }
3491 
3492         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3493             MemberName field = new MemberName(f, isSetter);
3494             if (isSetter && field.isFinal()) {
3495                 if (field.isTrustedFinalField()) {
3496                     String msg = field.isStatic() ? "static final field has no write access"
3497                                                   : "final field has no write access";
3498                     throw field.makeAccessException(msg, this);
3499                 }
3500             }
3501             assert(isSetter
3502                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3503                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3504             @SuppressWarnings("deprecation")
3505             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3506             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3507         }
3508 
3509         /**
3510          * Produces a VarHandle giving access to a reflected field {@code f}
3511          * of type {@code T} declared in a class of type {@code R}.
3512          * The VarHandle's variable type is {@code T}.
3513          * If the field is non-static the VarHandle has one coordinate type,
3514          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3515          * coordinate types.
3516          * <p>
3517          * Access checking is performed immediately on behalf of the lookup
3518          * class, regardless of the value of the field's {@code accessible}
3519          * flag.
3520          * <p>
3521          * If the field is static, and if the returned VarHandle is operated
3522          * on, the field's declaring class will be initialized, if it has not
3523          * already been initialized.
3524          * <p>
3525          * Certain access modes of the returned VarHandle are unsupported under
3526          * the following conditions:
3527          * <ul>
3528          * <li>if the field is declared {@code final}, then the write, atomic
3529          *     update, numeric atomic update, and bitwise atomic update access
3530          *     modes are unsupported.
3531          * <li>if the field type is anything other than {@code byte},
3532          *     {@code short}, {@code char}, {@code int}, {@code long},
3533          *     {@code float}, or {@code double} then numeric atomic update
3534          *     access modes are unsupported.
3535          * <li>if the field type is anything other than {@code boolean},
3536          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3537          *     {@code long} then bitwise atomic update access modes are
3538          *     unsupported.
3539          * </ul>
3540          * <p>
3541          * If the field is declared {@code volatile} then the returned VarHandle
3542          * will override access to the field (effectively ignore the
3543          * {@code volatile} declaration) in accordance to its specified
3544          * access modes.
3545          * <p>
3546          * If the field type is {@code float} or {@code double} then numeric
3547          * and atomic update access modes compare values using their bitwise
3548          * representation (see {@link Float#floatToRawIntBits} and
3549          * {@link Double#doubleToRawLongBits}, respectively).
3550          * @apiNote
3551          * Bitwise comparison of {@code float} values or {@code double} values,
3552          * as performed by the numeric and atomic update access modes, differ
3553          * from the primitive {@code ==} operator and the {@link Float#equals}
3554          * and {@link Double#equals} methods, specifically with respect to
3555          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3556          * Care should be taken when performing a compare and set or a compare
3557          * and exchange operation with such values since the operation may
3558          * unexpectedly fail.
3559          * There are many possible NaN values that are considered to be
3560          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3561          * provided by Java can distinguish between them.  Operation failure can
3562          * occur if the expected or witness value is a NaN value and it is
3563          * transformed (perhaps in a platform specific manner) into another NaN
3564          * value, and thus has a different bitwise representation (see
3565          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3566          * details).
3567          * The values {@code -0.0} and {@code +0.0} have different bitwise
3568          * representations but are considered equal when using the primitive
3569          * {@code ==} operator.  Operation failure can occur if, for example, a
3570          * numeric algorithm computes an expected value to be say {@code -0.0}
3571          * and previously computed the witness value to be say {@code +0.0}.
3572          * @param f the reflected field, with a field of type {@code T}, and
3573          * a declaring class of type {@code R}
3574          * @return a VarHandle giving access to non-static fields or a static
3575          * field
3576          * @throws IllegalAccessException if access checking fails
3577          * @throws NullPointerException if the argument is null
3578          * @since 9
3579          */
3580         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3581             MemberName getField = new MemberName(f, false);
3582             MemberName putField = new MemberName(f, true);
3583             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
3584                                                       f.getDeclaringClass(), getField, putField);
3585         }
3586 
3587         /**
3588          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3589          * created by this lookup object or a similar one.
3590          * Security and access checks are performed to ensure that this lookup object
3591          * is capable of reproducing the target method handle.
3592          * This means that the cracking may fail if target is a direct method handle
3593          * but was created by an unrelated lookup object.
3594          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3595          * and was created by a lookup object for a different class.
3596          * @param target a direct method handle to crack into symbolic reference components
3597          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3598          * @throws    SecurityException if a security manager is present and it
3599          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3600          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3601          * @throws    NullPointerException if the target is {@code null}
3602          * @see MethodHandleInfo
3603          * @since 1.8
3604          */
3605         public MethodHandleInfo revealDirect(MethodHandle target) {
3606             if (!target.isCrackable()) {
3607                 throw newIllegalArgumentException("not a direct method handle");
3608             }
3609             MemberName member = target.internalMemberName();
3610             Class<?> defc = member.getDeclaringClass();
3611             byte refKind = member.getReferenceKind();
3612             assert(MethodHandleNatives.refKindIsValid(refKind));
3613             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3614                 // Devirtualized method invocation is usually formally virtual.
3615                 // To avoid creating extra MemberName objects for this common case,
3616                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3617                 refKind = REF_invokeVirtual;
3618             if (refKind == REF_invokeVirtual && defc.isInterface())
3619                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3620                 refKind = REF_invokeInterface;
3621             // Check SM permissions and member access before cracking.
3622             try {
3623                 checkAccess(refKind, defc, member);
3624                 checkSecurityManager(defc, member);
3625             } catch (IllegalAccessException ex) {
3626                 throw new IllegalArgumentException(ex);
3627             }
3628             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3629                 Class<?> callerClass = target.internalCallerClass();
3630                 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3631                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3632             }
3633             // Produce the handle to the results.
3634             return new InfoFromMemberName(this, member, refKind);
3635         }
3636 
3637         /// Helper methods, all package-private.
3638 
3639         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3640             checkSymbolicClass(refc);  // do this before attempting to resolve
3641             Objects.requireNonNull(name);
3642             Objects.requireNonNull(type);
3643             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3644                                             NoSuchFieldException.class);
3645         }
3646 
3647         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3648             checkSymbolicClass(refc);  // do this before attempting to resolve
3649             Objects.requireNonNull(type);
3650             checkMethodName(refKind, name);  // implicit null-check of name
3651             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3652                                             NoSuchMethodException.class);
3653         }
3654 
3655         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3656             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3657             Objects.requireNonNull(member.getName());
3658             Objects.requireNonNull(member.getType());
3659             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3660                                             ReflectiveOperationException.class);
3661         }
3662 
3663         MemberName resolveOrNull(byte refKind, MemberName member) {
3664             // do this before attempting to resolve
3665             if (!isClassAccessible(member.getDeclaringClass())) {
3666                 return null;
3667             }
3668             Objects.requireNonNull(member.getName());
3669             Objects.requireNonNull(member.getType());
3670             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3671         }
3672 
3673         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3674             // do this before attempting to resolve
3675             if (!isClassAccessible(refc)) {
3676                 return null;
3677             }
3678             Objects.requireNonNull(type);
3679             // implicit null-check of name
3680             if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3681                 return null;
3682             }
3683             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3684         }
3685 
3686         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3687             if (!isClassAccessible(refc)) {
3688                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3689             }
3690         }
3691 
3692         boolean isClassAccessible(Class<?> refc) {
3693             Objects.requireNonNull(refc);
3694             Class<?> caller = lookupClassOrNull();
3695             Class<?> type = refc;
3696             while (type.isArray()) {
3697                 type = type.getComponentType();
3698             }
3699             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3700         }
3701 
3702         /** Check name for an illegal leading "&lt;" character. */
3703         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3704             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
3705                 throw new NoSuchMethodException("illegal method name: "+name);
3706         }
3707 
3708         /**
3709          * Find my trustable caller class if m is a caller sensitive method.
3710          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3711          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3712          */
3713         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3714             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3715                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3716                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3717             }
3718             return this;
3719         }
3720 
3721         /**
3722          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3723          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3724          *
3725          * @deprecated This method was originally designed to test {@code PRIVATE} access
3726          * that implies full privilege access but {@code MODULE} access has since become
3727          * independent of {@code PRIVATE} access.  It is recommended to call
3728          * {@link #hasFullPrivilegeAccess()} instead.
3729          * @since 9
3730          */
3731         @Deprecated(since="14")
3732         public boolean hasPrivateAccess() {
3733             return hasFullPrivilegeAccess();
3734         }
3735 
3736         /**
3737          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3738          * i.e. {@code PRIVATE} and {@code MODULE} access.
3739          * A {@code Lookup} object must have full privilege access in order to
3740          * access all members that are allowed to the
3741          * {@linkplain #lookupClass() lookup class}.
3742          *
3743          * @return {@code true} if this lookup has full privilege access.
3744          * @since 14
3745          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3746          */
3747         public boolean hasFullPrivilegeAccess() {
3748             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3749         }
3750 
3751         /**
3752          * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a>
3753          * for ensureInitialzed, findClass or accessClass.
3754          */
3755         void checkSecurityManager(Class<?> refc) {
3756             if (allowedModes == TRUSTED)  return;
3757 
3758             @SuppressWarnings("removal")
3759             SecurityManager smgr = System.getSecurityManager();
3760             if (smgr == null)  return;
3761 
3762             // Step 1:
3763             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3764             if (!fullPrivilegeLookup ||
3765                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3766                 ReflectUtil.checkPackageAccess(refc);
3767             }
3768 
3769             // Step 2b:
3770             if (!fullPrivilegeLookup) {
3771                 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
3772             }
3773         }
3774 
3775         /**
3776          * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
3777          * Determines a trustable caller class to compare with refc, the symbolic reference class.
3778          * If this lookup object has full privilege access except original access,
3779          * then the caller class is the lookupClass.
3780          *
3781          * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)}
3782          * from the same module skips the security permission check.
3783          */
3784         void checkSecurityManager(Class<?> refc, MemberName m) {
3785             Objects.requireNonNull(refc);
3786             Objects.requireNonNull(m);
3787 
3788             if (allowedModes == TRUSTED)  return;
3789 
3790             @SuppressWarnings("removal")
3791             SecurityManager smgr = System.getSecurityManager();
3792             if (smgr == null)  return;
3793 
3794             // Step 1:
3795             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3796             if (!fullPrivilegeLookup ||
3797                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3798                 ReflectUtil.checkPackageAccess(refc);
3799             }
3800 
3801             // Step 2a:
3802             if (m.isPublic()) return;
3803             if (!fullPrivilegeLookup) {
3804                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3805             }
3806 
3807             // Step 3:
3808             Class<?> defc = m.getDeclaringClass();
3809             if (!fullPrivilegeLookup && defc != refc) {
3810                 ReflectUtil.checkPackageAccess(defc);
3811             }
3812         }
3813 
3814         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3815             boolean wantStatic = (refKind == REF_invokeStatic);
3816             String message;
3817             if (m.isConstructor())
3818                 message = "expected a method, not a constructor";
3819             else if (!m.isMethod())
3820                 message = "expected a method";
3821             else if (wantStatic != m.isStatic())
3822                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3823             else
3824                 { checkAccess(refKind, refc, m); return; }
3825             throw m.makeAccessException(message, this);
3826         }
3827 
3828         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3829             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3830             String message;
3831             if (wantStatic != m.isStatic())
3832                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3833             else
3834                 { checkAccess(refKind, refc, m); return; }
3835             throw m.makeAccessException(message, this);
3836         }
3837 
3838         /** Check public/protected/private bits on the symbolic reference class and its member. */
3839         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3840             assert(m.referenceKindIsConsistentWith(refKind) &&
3841                    MethodHandleNatives.refKindIsValid(refKind) &&
3842                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3843             int allowedModes = this.allowedModes;
3844             if (allowedModes == TRUSTED)  return;
3845             int mods = m.getModifiers();
3846             if (Modifier.isProtected(mods) &&
3847                     refKind == REF_invokeVirtual &&
3848                     m.getDeclaringClass() == Object.class &&
3849                     m.getName().equals("clone") &&
3850                     refc.isArray()) {
3851                 // The JVM does this hack also.
3852                 // (See ClassVerifier::verify_invoke_instructions
3853                 // and LinkResolver::check_method_accessability.)
3854                 // Because the JVM does not allow separate methods on array types,
3855                 // there is no separate method for int[].clone.
3856                 // All arrays simply inherit Object.clone.
3857                 // But for access checking logic, we make Object.clone
3858                 // (normally protected) appear to be public.
3859                 // Later on, when the DirectMethodHandle is created,
3860                 // its leading argument will be restricted to the
3861                 // requested array type.
3862                 // N.B. The return type is not adjusted, because
3863                 // that is *not* the bytecode behavior.
3864                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3865             }
3866             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3867                 // cannot "new" a protected ctor in a different package
3868                 mods ^= Modifier.PROTECTED;
3869             }
3870             if (Modifier.isFinal(mods) &&
3871                     MethodHandleNatives.refKindIsSetter(refKind))
3872                 throw m.makeAccessException("unexpected set of a final field", this);
3873             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3874             if ((requestedModes & allowedModes) != 0) {
3875                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3876                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3877                     return;
3878             } else {
3879                 // Protected members can also be checked as if they were package-private.
3880                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
3881                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
3882                     return;
3883             }
3884             throw m.makeAccessException(accessFailedMessage(refc, m), this);
3885         }
3886 
3887         String accessFailedMessage(Class<?> refc, MemberName m) {
3888             Class<?> defc = m.getDeclaringClass();
3889             int mods = m.getModifiers();
3890             // check the class first:
3891             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
3892                                (defc == refc ||
3893                                 Modifier.isPublic(refc.getModifiers())));
3894             if (!classOK && (allowedModes & PACKAGE) != 0) {
3895                 // ignore previous lookup class to check if default package access
3896                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
3897                            (defc == refc ||
3898                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
3899             }
3900             if (!classOK)
3901                 return "class is not public";
3902             if (Modifier.isPublic(mods))
3903                 return "access to public member failed";  // (how?, module not readable?)
3904             if (Modifier.isPrivate(mods))
3905                 return "member is private";
3906             if (Modifier.isProtected(mods))
3907                 return "member is protected";
3908             return "member is private to package";
3909         }
3910 
3911         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
3912             int allowedModes = this.allowedModes;
3913             if (allowedModes == TRUSTED)  return;
3914             if ((lookupModes() & PRIVATE) == 0
3915                 || (specialCaller != lookupClass()
3916                        // ensure non-abstract methods in superinterfaces can be special-invoked
3917                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
3918                 throw new MemberName(specialCaller).
3919                     makeAccessException("no private access for invokespecial", this);
3920         }
3921 
3922         private boolean restrictProtectedReceiver(MemberName method) {
3923             // The accessing class only has the right to use a protected member
3924             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
3925             if (!method.isProtected() || method.isStatic()
3926                 || allowedModes == TRUSTED
3927                 || method.getDeclaringClass() == lookupClass()
3928                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
3929                 return false;
3930             return true;
3931         }
3932         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
3933             assert(!method.isStatic());
3934             // receiver type of mh is too wide; narrow to caller
3935             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
3936                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
3937             }
3938             MethodType rawType = mh.type();
3939             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
3940             MethodType narrowType = rawType.changeParameterType(0, caller);
3941             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
3942             assert(mh.viewAsTypeChecks(narrowType, true));
3943             return mh.copyWith(narrowType, mh.form);
3944         }
3945 
3946         /** Check access and get the requested method. */
3947         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3948             final boolean doRestrict    = true;
3949             final boolean checkSecurity = true;
3950             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3951         }
3952         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
3953         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3954             final boolean doRestrict    = false;
3955             final boolean checkSecurity = true;
3956             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
3957         }
3958         /** Check access and get the requested method, eliding security manager checks. */
3959         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3960             final boolean doRestrict    = true;
3961             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
3962             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3963         }
3964         /** Common code for all methods; do not call directly except from immediately above. */
3965         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
3966                                                    boolean checkSecurity,
3967                                                    boolean doRestrict,
3968                                                    Lookup boundCaller) throws IllegalAccessException {
3969             checkMethod(refKind, refc, method);
3970             // Optionally check with the security manager; this isn't needed for unreflect* calls.
3971             if (checkSecurity)
3972                 checkSecurityManager(refc, method);
3973             assert(!method.isMethodHandleInvoke());
3974 
3975             if (refKind == REF_invokeSpecial &&
3976                 refc != lookupClass() &&
3977                 !refc.isInterface() &&
3978                 refc != lookupClass().getSuperclass() &&
3979                 refc.isAssignableFrom(lookupClass())) {
3980                 assert(!method.getName().equals("<init>"));  // not this code path
3981 
3982                 // Per JVMS 6.5, desc. of invokespecial instruction:
3983                 // If the method is in a superclass of the LC,
3984                 // and if our original search was above LC.super,
3985                 // repeat the search (symbolic lookup) from LC.super
3986                 // and continue with the direct superclass of that class,
3987                 // and so forth, until a match is found or no further superclasses exist.
3988                 // FIXME: MemberName.resolve should handle this instead.
3989                 Class<?> refcAsSuper = lookupClass();
3990                 MemberName m2;
3991                 do {
3992                     refcAsSuper = refcAsSuper.getSuperclass();
3993                     m2 = new MemberName(refcAsSuper,
3994                                         method.getName(),
3995                                         method.getMethodType(),
3996                                         REF_invokeSpecial);
3997                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
3998                 } while (m2 == null &&         // no method is found yet
3999                          refc != refcAsSuper); // search up to refc
4000                 if (m2 == null)  throw new InternalError(method.toString());
4001                 method = m2;
4002                 refc = refcAsSuper;
4003                 // redo basic checks
4004                 checkMethod(refKind, refc, method);
4005             }
4006             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
4007             MethodHandle mh = dmh;
4008             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
4009             if ((doRestrict && refKind == REF_invokeSpecial) ||
4010                     (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method))) {
4011                 mh = restrictReceiver(method, dmh, lookupClass());
4012             }
4013             mh = maybeBindCaller(method, mh, boundCaller);
4014             mh = mh.setVarargs(method);
4015             return mh;
4016         }
4017         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
4018                                              throws IllegalAccessException {
4019             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
4020                 return mh;
4021 
4022             // boundCaller must have full privilege access.
4023             // It should have been checked by findBoundCallerLookup. Safe to check this again.
4024             if ((boundCaller.lookupModes() & ORIGINAL) == 0)
4025                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
4026 
4027             assert boundCaller.hasFullPrivilegeAccess();
4028 
4029             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
4030             // Note: caller will apply varargs after this step happens.
4031             return cbmh;
4032         }
4033 
4034         /** Check access and get the requested field. */
4035         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4036             final boolean checkSecurity = true;
4037             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4038         }
4039         /** Check access and get the requested field, eliding security manager checks. */
4040         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4041             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4042             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4043         }
4044         /** Common code for all fields; do not call directly except from immediately above. */
4045         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
4046                                                   boolean checkSecurity) throws IllegalAccessException {
4047             checkField(refKind, refc, field);
4048             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4049             if (checkSecurity)
4050                 checkSecurityManager(refc, field);
4051             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
4052             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
4053                                     restrictProtectedReceiver(field));
4054             if (doRestrict)
4055                 return restrictReceiver(field, dmh, lookupClass());
4056             return dmh;
4057         }
4058         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
4059                                             Class<?> refc, MemberName getField, MemberName putField)
4060                 throws IllegalAccessException {
4061             final boolean checkSecurity = true;
4062             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4063         }
4064         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
4065                                                              Class<?> refc, MemberName getField, MemberName putField)
4066                 throws IllegalAccessException {
4067             final boolean checkSecurity = false;
4068             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4069         }
4070         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
4071                                                   Class<?> refc, MemberName getField, MemberName putField,
4072                                                   boolean checkSecurity) throws IllegalAccessException {
4073             assert getField.isStatic() == putField.isStatic();
4074             assert getField.isGetter() && putField.isSetter();
4075             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
4076             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
4077 
4078             checkField(getRefKind, refc, getField);
4079             if (checkSecurity)
4080                 checkSecurityManager(refc, getField);
4081 
4082             if (!putField.isFinal()) {
4083                 // A VarHandle does not support updates to final fields, any
4084                 // such VarHandle to a final field will be read-only and
4085                 // therefore the following write-based accessibility checks are
4086                 // only required for non-final fields
4087                 checkField(putRefKind, refc, putField);
4088                 if (checkSecurity)
4089                     checkSecurityManager(refc, putField);
4090             }
4091 
4092             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
4093                                   restrictProtectedReceiver(getField));
4094             if (doRestrict) {
4095                 assert !getField.isStatic();
4096                 // receiver type of VarHandle is too wide; narrow to caller
4097                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
4098                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4099                 }
4100                 refc = lookupClass();
4101             }
4102             return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(),
4103                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4104         }
4105         /** Check access and get the requested constructor. */
4106         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4107             final boolean checkSecurity = true;
4108             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4109         }
4110         /** Check access and get the requested constructor, eliding security manager checks. */
4111         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4112             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4113             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4114         }
4115         /** Common code for all constructors; do not call directly except from immediately above. */
4116         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4117                                                   boolean checkSecurity) throws IllegalAccessException {
4118             assert(ctor.isConstructor());
4119             checkAccess(REF_newInvokeSpecial, refc, ctor);
4120             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4121             if (checkSecurity)
4122                 checkSecurityManager(refc, ctor);
4123             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4124             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4125         }
4126 
4127         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4128          */
4129         /*non-public*/
4130         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4131                 throws ReflectiveOperationException {
4132             if (!(type instanceof Class || type instanceof MethodType))
4133                 throw new InternalError("unresolved MemberName");
4134             MemberName member = new MemberName(refKind, defc, name, type);
4135             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4136             if (mh != null) {
4137                 checkSymbolicClass(defc);
4138                 return mh;
4139             }
4140             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
4141                 // Treat MethodHandle.invoke and invokeExact specially.
4142                 mh = findVirtualForMH(member.getName(), member.getMethodType());
4143                 if (mh != null) {
4144                     return mh;
4145                 }
4146             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4147                 // Treat signature-polymorphic methods on VarHandle specially.
4148                 mh = findVirtualForVH(member.getName(), member.getMethodType());
4149                 if (mh != null) {
4150                     return mh;
4151                 }
4152             }
4153             MemberName resolved = resolveOrFail(refKind, member);
4154             mh = getDirectMethodForConstant(refKind, defc, resolved);
4155             if (mh instanceof DirectMethodHandle
4156                     && canBeCached(refKind, defc, resolved)) {
4157                 MemberName key = mh.internalMemberName();
4158                 if (key != null) {
4159                     key = key.asNormalOriginal();
4160                 }
4161                 if (member.equals(key)) {  // better safe than sorry
4162                     LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
4163                 }
4164             }
4165             return mh;
4166         }
4167         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4168             if (refKind == REF_invokeSpecial) {
4169                 return false;
4170             }
4171             if (!Modifier.isPublic(defc.getModifiers()) ||
4172                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4173                     !member.isPublic() ||
4174                     member.isCallerSensitive()) {
4175                 return false;
4176             }
4177             ClassLoader loader = defc.getClassLoader();
4178             if (loader != null) {
4179                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4180                 boolean found = false;
4181                 while (sysl != null) {
4182                     if (loader == sysl) { found = true; break; }
4183                     sysl = sysl.getParent();
4184                 }
4185                 if (!found) {
4186                     return false;
4187                 }
4188             }
4189             try {
4190                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4191                     new MemberName(refKind, defc, member.getName(), member.getType()));
4192                 if (resolved2 == null) {
4193                     return false;
4194                 }
4195                 checkSecurityManager(defc, resolved2);
4196             } catch (SecurityException ex) {
4197                 return false;
4198             }
4199             return true;
4200         }
4201         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4202                 throws ReflectiveOperationException {
4203             if (MethodHandleNatives.refKindIsField(refKind)) {
4204                 return getDirectFieldNoSecurityManager(refKind, defc, member);
4205             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4206                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
4207             } else if (refKind == REF_newInvokeSpecial) {
4208                 return getDirectConstructorNoSecurityManager(defc, member);
4209             }
4210             // oops
4211             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4212         }
4213 
4214         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4215     }
4216 
4217     /**
4218      * Produces a method handle constructing arrays of a desired type,
4219      * as if by the {@code anewarray} bytecode.
4220      * The return type of the method handle will be the array type.
4221      * The type of its sole argument will be {@code int}, which specifies the size of the array.
4222      *
4223      * <p> If the returned method handle is invoked with a negative
4224      * array size, a {@code NegativeArraySizeException} will be thrown.
4225      *
4226      * @param arrayClass an array type
4227      * @return a method handle which can create arrays of the given type
4228      * @throws NullPointerException if the argument is {@code null}
4229      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4230      * @see java.lang.reflect.Array#newInstance(Class, int)
4231      * @jvms 6.5 {@code anewarray} Instruction
4232      * @since 9
4233      */
4234     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4235         if (!arrayClass.isArray()) {
4236             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4237         }
4238         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4239                 bindTo(arrayClass.getComponentType());
4240         return ani.asType(ani.type().changeReturnType(arrayClass));
4241     }
4242 
4243     /**
4244      * Produces a method handle returning the length of an array,
4245      * as if by the {@code arraylength} bytecode.
4246      * The type of the method handle will have {@code int} as return type,
4247      * and its sole argument will be the array type.
4248      *
4249      * <p> If the returned method handle is invoked with a {@code null}
4250      * array reference, a {@code NullPointerException} will be thrown.
4251      *
4252      * @param arrayClass an array type
4253      * @return a method handle which can retrieve the length of an array of the given array type
4254      * @throws NullPointerException if the argument is {@code null}
4255      * @throws IllegalArgumentException if arrayClass is not an array type
4256      * @jvms 6.5 {@code arraylength} Instruction
4257      * @since 9
4258      */
4259     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4260         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4261     }
4262 
4263     /**
4264      * Produces a method handle giving read access to elements of an array,
4265      * as if by the {@code aaload} bytecode.
4266      * The type of the method handle will have a return type of the array's
4267      * element type.  Its first argument will be the array type,
4268      * and the second will be {@code int}.
4269      *
4270      * <p> When the returned method handle is invoked,
4271      * the array reference and array index are checked.
4272      * A {@code NullPointerException} will be thrown if the array reference
4273      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4274      * thrown if the index is negative or if it is greater than or equal to
4275      * the length of the array.
4276      *
4277      * @param arrayClass an array type
4278      * @return a method handle which can load values from the given array type
4279      * @throws NullPointerException if the argument is null
4280      * @throws  IllegalArgumentException if arrayClass is not an array type
4281      * @jvms 6.5 {@code aaload} Instruction
4282      */
4283     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4284         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4285     }
4286 
4287     /**
4288      * Produces a method handle giving write access to elements of an array,
4289      * as if by the {@code astore} bytecode.
4290      * The type of the method handle will have a void return type.
4291      * Its last argument will be the array's element type.
4292      * The first and second arguments will be the array type and int.
4293      *
4294      * <p> When the returned method handle is invoked,
4295      * the array reference and array index are checked.
4296      * A {@code NullPointerException} will be thrown if the array reference
4297      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4298      * thrown if the index is negative or if it is greater than or equal to
4299      * the length of the array.
4300      *
4301      * @param arrayClass the class of an array
4302      * @return a method handle which can store values into the array type
4303      * @throws NullPointerException if the argument is null
4304      * @throws IllegalArgumentException if arrayClass is not an array type
4305      * @jvms 6.5 {@code aastore} Instruction
4306      */
4307     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4308         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4309     }
4310 
4311     /**
4312      * Produces a VarHandle giving access to elements of an array of type
4313      * {@code arrayClass}.  The VarHandle's variable type is the component type
4314      * of {@code arrayClass} and the list of coordinate types is
4315      * {@code (arrayClass, int)}, where the {@code int} coordinate type
4316      * corresponds to an argument that is an index into an array.
4317      * <p>
4318      * Certain access modes of the returned VarHandle are unsupported under
4319      * the following conditions:
4320      * <ul>
4321      * <li>if the component type is anything other than {@code byte},
4322      *     {@code short}, {@code char}, {@code int}, {@code long},
4323      *     {@code float}, or {@code double} then numeric atomic update access
4324      *     modes are unsupported.
4325      * <li>if the component type is anything other than {@code boolean},
4326      *     {@code byte}, {@code short}, {@code char}, {@code int} or
4327      *     {@code long} then bitwise atomic update access modes are
4328      *     unsupported.
4329      * </ul>
4330      * <p>
4331      * If the component type is {@code float} or {@code double} then numeric
4332      * and atomic update access modes compare values using their bitwise
4333      * representation (see {@link Float#floatToRawIntBits} and
4334      * {@link Double#doubleToRawLongBits}, respectively).
4335      *
4336      * <p> When the returned {@code VarHandle} is invoked,
4337      * the array reference and array index are checked.
4338      * A {@code NullPointerException} will be thrown if the array reference
4339      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4340      * thrown if the index is negative or if it is greater than or equal to
4341      * the length of the array.
4342      *
4343      * @apiNote
4344      * Bitwise comparison of {@code float} values or {@code double} values,
4345      * as performed by the numeric and atomic update access modes, differ
4346      * from the primitive {@code ==} operator and the {@link Float#equals}
4347      * and {@link Double#equals} methods, specifically with respect to
4348      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4349      * Care should be taken when performing a compare and set or a compare
4350      * and exchange operation with such values since the operation may
4351      * unexpectedly fail.
4352      * There are many possible NaN values that are considered to be
4353      * {@code NaN} in Java, although no IEEE 754 floating-point operation
4354      * provided by Java can distinguish between them.  Operation failure can
4355      * occur if the expected or witness value is a NaN value and it is
4356      * transformed (perhaps in a platform specific manner) into another NaN
4357      * value, and thus has a different bitwise representation (see
4358      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4359      * details).
4360      * The values {@code -0.0} and {@code +0.0} have different bitwise
4361      * representations but are considered equal when using the primitive
4362      * {@code ==} operator.  Operation failure can occur if, for example, a
4363      * numeric algorithm computes an expected value to be say {@code -0.0}
4364      * and previously computed the witness value to be say {@code +0.0}.
4365      * @param arrayClass the class of an array, of type {@code T[]}
4366      * @return a VarHandle giving access to elements of an array
4367      * @throws NullPointerException if the arrayClass is null
4368      * @throws IllegalArgumentException if arrayClass is not an array type
4369      * @since 9
4370      */
4371     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4372         return VarHandles.makeArrayElementHandle(arrayClass);
4373     }
4374 
4375     /**
4376      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4377      * viewed as if it were a different primitive array type, such as
4378      * {@code int[]} or {@code long[]}.
4379      * The VarHandle's variable type is the component type of
4380      * {@code viewArrayClass} and the list of coordinate types is
4381      * {@code (byte[], int)}, where the {@code int} coordinate type
4382      * corresponds to an argument that is an index into a {@code byte[]} array.
4383      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4384      * array, composing bytes to or from a value of the component type of
4385      * {@code viewArrayClass} according to the given endianness.
4386      * <p>
4387      * The supported component types (variables types) are {@code short},
4388      * {@code char}, {@code int}, {@code long}, {@code float} and
4389      * {@code double}.
4390      * <p>
4391      * Access of bytes at a given index will result in an
4392      * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4393      * or greater than the {@code byte[]} array length minus the size (in bytes)
4394      * of {@code T}.
4395      * <p>
4396      * Access of bytes at an index may be aligned or misaligned for {@code T},
4397      * with respect to the underlying memory address, {@code A} say, associated
4398      * with the array and index.
4399      * If access is misaligned then access for anything other than the
4400      * {@code get} and {@code set} access modes will result in an
4401      * {@code IllegalStateException}.  In such cases atomic access is only
4402      * guaranteed with respect to the largest power of two that divides the GCD
4403      * of {@code A} and the size (in bytes) of {@code T}.
4404      * If access is aligned then following access modes are supported and are
4405      * guaranteed to support atomic access:
4406      * <ul>
4407      * <li>read write access modes for all {@code T}, with the exception of
4408      *     access modes {@code get} and {@code set} for {@code long} and
4409      *     {@code double} on 32-bit platforms.
4410      * <li>atomic update access modes for {@code int}, {@code long},
4411      *     {@code float} or {@code double}.
4412      *     (Future major platform releases of the JDK may support additional
4413      *     types for certain currently unsupported access modes.)
4414      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4415      *     (Future major platform releases of the JDK may support additional
4416      *     numeric types for certain currently unsupported access modes.)
4417      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4418      *     (Future major platform releases of the JDK may support additional
4419      *     numeric types for certain currently unsupported access modes.)
4420      * </ul>
4421      * <p>
4422      * Misaligned access, and therefore atomicity guarantees, may be determined
4423      * for {@code byte[]} arrays without operating on a specific array.  Given
4424      * an {@code index}, {@code T} and its corresponding boxed type,
4425      * {@code T_BOX}, misalignment may be determined as follows:
4426      * <pre>{@code
4427      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4428      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
4429      *     alignmentOffset(0, sizeOfT);
4430      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
4431      * boolean isMisaligned = misalignedAtIndex != 0;
4432      * }</pre>
4433      * <p>
4434      * If the variable type is {@code float} or {@code double} then atomic
4435      * update access modes compare values using their bitwise representation
4436      * (see {@link Float#floatToRawIntBits} and
4437      * {@link Double#doubleToRawLongBits}, respectively).
4438      * @param viewArrayClass the view array class, with a component type of
4439      * type {@code T}
4440      * @param byteOrder the endianness of the view array elements, as
4441      * stored in the underlying {@code byte} array
4442      * @return a VarHandle giving access to elements of a {@code byte[]} array
4443      * viewed as if elements corresponding to the components type of the view
4444      * array class
4445      * @throws NullPointerException if viewArrayClass or byteOrder is null
4446      * @throws IllegalArgumentException if viewArrayClass is not an array type
4447      * @throws UnsupportedOperationException if the component type of
4448      * viewArrayClass is not supported as a variable type
4449      * @since 9
4450      */
4451     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4452                                      ByteOrder byteOrder) throws IllegalArgumentException {
4453         Objects.requireNonNull(byteOrder);
4454         return VarHandles.byteArrayViewHandle(viewArrayClass,
4455                                               byteOrder == ByteOrder.BIG_ENDIAN);
4456     }
4457 
4458     /**
4459      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4460      * viewed as if it were an array of elements of a different primitive
4461      * component type to that of {@code byte}, such as {@code int[]} or
4462      * {@code long[]}.
4463      * The VarHandle's variable type is the component type of
4464      * {@code viewArrayClass} and the list of coordinate types is
4465      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4466      * corresponds to an argument that is an index into a {@code byte[]} array.
4467      * The returned VarHandle accesses bytes at an index in a
4468      * {@code ByteBuffer}, composing bytes to or from a value of the component
4469      * type of {@code viewArrayClass} according to the given endianness.
4470      * <p>
4471      * The supported component types (variables types) are {@code short},
4472      * {@code char}, {@code int}, {@code long}, {@code float} and
4473      * {@code double}.
4474      * <p>
4475      * Access will result in a {@code ReadOnlyBufferException} for anything
4476      * other than the read access modes if the {@code ByteBuffer} is read-only.
4477      * <p>
4478      * Access of bytes at a given index will result in an
4479      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4480      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4481      * {@code T}.
4482      * <p>
4483      * Access of bytes at an index may be aligned or misaligned for {@code T},
4484      * with respect to the underlying memory address, {@code A} say, associated
4485      * with the {@code ByteBuffer} and index.
4486      * If access is misaligned then access for anything other than the
4487      * {@code get} and {@code set} access modes will result in an
4488      * {@code IllegalStateException}.  In such cases atomic access is only
4489      * guaranteed with respect to the largest power of two that divides the GCD
4490      * of {@code A} and the size (in bytes) of {@code T}.
4491      * If access is aligned then following access modes are supported and are
4492      * guaranteed to support atomic access:
4493      * <ul>
4494      * <li>read write access modes for all {@code T}, with the exception of
4495      *     access modes {@code get} and {@code set} for {@code long} and
4496      *     {@code double} on 32-bit platforms.
4497      * <li>atomic update access modes for {@code int}, {@code long},
4498      *     {@code float} or {@code double}.
4499      *     (Future major platform releases of the JDK may support additional
4500      *     types for certain currently unsupported access modes.)
4501      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4502      *     (Future major platform releases of the JDK may support additional
4503      *     numeric types for certain currently unsupported access modes.)
4504      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4505      *     (Future major platform releases of the JDK may support additional
4506      *     numeric types for certain currently unsupported access modes.)
4507      * </ul>
4508      * <p>
4509      * Misaligned access, and therefore atomicity guarantees, may be determined
4510      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4511      * {@code index}, {@code T} and its corresponding boxed type,
4512      * {@code T_BOX}, as follows:
4513      * <pre>{@code
4514      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4515      * ByteBuffer bb = ...
4516      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4517      * boolean isMisaligned = misalignedAtIndex != 0;
4518      * }</pre>
4519      * <p>
4520      * If the variable type is {@code float} or {@code double} then atomic
4521      * update access modes compare values using their bitwise representation
4522      * (see {@link Float#floatToRawIntBits} and
4523      * {@link Double#doubleToRawLongBits}, respectively).
4524      * @param viewArrayClass the view array class, with a component type of
4525      * type {@code T}
4526      * @param byteOrder the endianness of the view array elements, as
4527      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4528      * endianness of a {@code ByteBuffer})
4529      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4530      * viewed as if elements corresponding to the components type of the view
4531      * array class
4532      * @throws NullPointerException if viewArrayClass or byteOrder is null
4533      * @throws IllegalArgumentException if viewArrayClass is not an array type
4534      * @throws UnsupportedOperationException if the component type of
4535      * viewArrayClass is not supported as a variable type
4536      * @since 9
4537      */
4538     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4539                                       ByteOrder byteOrder) throws IllegalArgumentException {
4540         Objects.requireNonNull(byteOrder);
4541         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4542                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4543     }
4544 
4545 
4546     /// method handle invocation (reflective style)
4547 
4548     /**
4549      * Produces a method handle which will invoke any method handle of the
4550      * given {@code type}, with a given number of trailing arguments replaced by
4551      * a single trailing {@code Object[]} array.
4552      * The resulting invoker will be a method handle with the following
4553      * arguments:
4554      * <ul>
4555      * <li>a single {@code MethodHandle} target
4556      * <li>zero or more leading values (counted by {@code leadingArgCount})
4557      * <li>an {@code Object[]} array containing trailing arguments
4558      * </ul>
4559      * <p>
4560      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4561      * the indicated {@code type}.
4562      * That is, if the target is exactly of the given {@code type}, it will behave
4563      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4564      * is used to convert the target to the required {@code type}.
4565      * <p>
4566      * The type of the returned invoker will not be the given {@code type}, but rather
4567      * will have all parameters except the first {@code leadingArgCount}
4568      * replaced by a single array of type {@code Object[]}, which will be
4569      * the final parameter.
4570      * <p>
4571      * Before invoking its target, the invoker will spread the final array, apply
4572      * reference casts as necessary, and unbox and widen primitive arguments.
4573      * If, when the invoker is called, the supplied array argument does
4574      * not have the correct number of elements, the invoker will throw
4575      * an {@link IllegalArgumentException} instead of invoking the target.
4576      * <p>
4577      * This method is equivalent to the following code (though it may be more efficient):
4578      * <blockquote><pre>{@code
4579 MethodHandle invoker = MethodHandles.invoker(type);
4580 int spreadArgCount = type.parameterCount() - leadingArgCount;
4581 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4582 return invoker;
4583      * }</pre></blockquote>
4584      * This method throws no reflective or security exceptions.
4585      * @param type the desired target type
4586      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4587      * @return a method handle suitable for invoking any method handle of the given type
4588      * @throws NullPointerException if {@code type} is null
4589      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4590      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4591      *                  or if the resulting method handle's type would have
4592      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4593      */
4594     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4595         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4596             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4597         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4598         return type.invokers().spreadInvoker(leadingArgCount);
4599     }
4600 
4601     /**
4602      * Produces a special <em>invoker method handle</em> which can be used to
4603      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4604      * The resulting invoker will have a type which is
4605      * exactly equal to the desired type, except that it will accept
4606      * an additional leading argument of type {@code MethodHandle}.
4607      * <p>
4608      * This method is equivalent to the following code (though it may be more efficient):
4609      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4610      *
4611      * <p style="font-size:smaller;">
4612      * <em>Discussion:</em>
4613      * Invoker method handles can be useful when working with variable method handles
4614      * of unknown types.
4615      * For example, to emulate an {@code invokeExact} call to a variable method
4616      * handle {@code M}, extract its type {@code T},
4617      * look up the invoker method {@code X} for {@code T},
4618      * and call the invoker method, as {@code X.invoke(T, A...)}.
4619      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4620      * is unknown.)
4621      * If spreading, collecting, or other argument transformations are required,
4622      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4623      * method handle values, as long as they are compatible with the type of {@code X}.
4624      * <p style="font-size:smaller;">
4625      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4626      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4627      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4628      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4629      * <p>
4630      * This method throws no reflective or security exceptions.
4631      * @param type the desired target type
4632      * @return a method handle suitable for invoking any method handle of the given type
4633      * @throws IllegalArgumentException if the resulting method handle's type would have
4634      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4635      */
4636     public static MethodHandle exactInvoker(MethodType type) {
4637         return type.invokers().exactInvoker();
4638     }
4639 
4640     /**
4641      * Produces a special <em>invoker method handle</em> which can be used to
4642      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4643      * The resulting invoker will have a type which is
4644      * exactly equal to the desired type, except that it will accept
4645      * an additional leading argument of type {@code MethodHandle}.
4646      * <p>
4647      * Before invoking its target, if the target differs from the expected type,
4648      * the invoker will apply reference casts as
4649      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4650      * Similarly, the return value will be converted as necessary.
4651      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4652      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4653      * <p>
4654      * This method is equivalent to the following code (though it may be more efficient):
4655      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4656      * <p style="font-size:smaller;">
4657      * <em>Discussion:</em>
4658      * A {@linkplain MethodType#genericMethodType general method type} is one which
4659      * mentions only {@code Object} arguments and return values.
4660      * An invoker for such a type is capable of calling any method handle
4661      * of the same arity as the general type.
4662      * <p style="font-size:smaller;">
4663      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4664      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4665      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4666      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4667      * <p>
4668      * This method throws no reflective or security exceptions.
4669      * @param type the desired target type
4670      * @return a method handle suitable for invoking any method handle convertible to the given type
4671      * @throws IllegalArgumentException if the resulting method handle's type would have
4672      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4673      */
4674     public static MethodHandle invoker(MethodType type) {
4675         return type.invokers().genericInvoker();
4676     }
4677 
4678     /**
4679      * Produces a special <em>invoker method handle</em> which can be used to
4680      * invoke a signature-polymorphic access mode method on any VarHandle whose
4681      * associated access mode type is compatible with the given type.
4682      * The resulting invoker will have a type which is exactly equal to the
4683      * desired given type, except that it will accept an additional leading
4684      * argument of type {@code VarHandle}.
4685      *
4686      * @param accessMode the VarHandle access mode
4687      * @param type the desired target type
4688      * @return a method handle suitable for invoking an access mode method of
4689      *         any VarHandle whose access mode type is of the given type.
4690      * @since 9
4691      */
4692     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4693         return type.invokers().varHandleMethodExactInvoker(accessMode);
4694     }
4695 
4696     /**
4697      * Produces a special <em>invoker method handle</em> which can be used to
4698      * invoke a signature-polymorphic access mode method on any VarHandle whose
4699      * associated access mode type is compatible with the given type.
4700      * The resulting invoker will have a type which is exactly equal to the
4701      * desired given type, except that it will accept an additional leading
4702      * argument of type {@code VarHandle}.
4703      * <p>
4704      * Before invoking its target, if the access mode type differs from the
4705      * desired given type, the invoker will apply reference casts as necessary
4706      * and box, unbox, or widen primitive values, as if by
4707      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4708      * converted as necessary.
4709      * <p>
4710      * This method is equivalent to the following code (though it may be more
4711      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4712      *
4713      * @param accessMode the VarHandle access mode
4714      * @param type the desired target type
4715      * @return a method handle suitable for invoking an access mode method of
4716      *         any VarHandle whose access mode type is convertible to the given
4717      *         type.
4718      * @since 9
4719      */
4720     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4721         return type.invokers().varHandleMethodInvoker(accessMode);
4722     }
4723 
4724     /*non-public*/
4725     static MethodHandle basicInvoker(MethodType type) {
4726         return type.invokers().basicInvoker();
4727     }
4728 
4729      /// method handle modification (creation from other method handles)
4730 
4731     /**
4732      * Produces a method handle which adapts the type of the
4733      * given method handle to a new type by pairwise argument and return type conversion.
4734      * The original type and new type must have the same number of arguments.
4735      * The resulting method handle is guaranteed to report a type
4736      * which is equal to the desired new type.
4737      * <p>
4738      * If the original type and new type are equal, returns target.
4739      * <p>
4740      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4741      * and some additional conversions are also applied if those conversions fail.
4742      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4743      * if possible, before or instead of any conversions done by {@code asType}:
4744      * <ul>
4745      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4746      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4747      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4748      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4749      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4750      *     (This treatment follows the usage of the bytecode verifier.)
4751      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4752      *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
4753      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4754      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4755      *     then a Java casting conversion (JLS 5.5) is applied.
4756      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4757      *     widening and/or narrowing.)
4758      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4759      *     conversion will be applied at runtime, possibly followed
4760      *     by a Java casting conversion (JLS 5.5) on the primitive value,
4761      *     possibly followed by a conversion from byte to boolean by testing
4762      *     the low-order bit.
4763      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4764      *     and if the reference is null at runtime, a zero value is introduced.
4765      * </ul>
4766      * @param target the method handle to invoke after arguments are retyped
4767      * @param newType the expected type of the new method handle
4768      * @return a method handle which delegates to the target after performing
4769      *           any necessary argument conversions, and arranges for any
4770      *           necessary return value conversions
4771      * @throws NullPointerException if either argument is null
4772      * @throws WrongMethodTypeException if the conversion cannot be made
4773      * @see MethodHandle#asType
4774      */
4775     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4776         explicitCastArgumentsChecks(target, newType);
4777         // use the asTypeCache when possible:
4778         MethodType oldType = target.type();
4779         if (oldType == newType)  return target;
4780         if (oldType.explicitCastEquivalentToAsType(newType)) {
4781             return target.asFixedArity().asType(newType);
4782         }
4783         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4784     }
4785 
4786     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4787         if (target.type().parameterCount() != newType.parameterCount()) {
4788             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4789         }
4790     }
4791 
4792     /**
4793      * Produces a method handle which adapts the calling sequence of the
4794      * given method handle to a new type, by reordering the arguments.
4795      * The resulting method handle is guaranteed to report a type
4796      * which is equal to the desired new type.
4797      * <p>
4798      * The given array controls the reordering.
4799      * Call {@code #I} the number of incoming parameters (the value
4800      * {@code newType.parameterCount()}, and call {@code #O} the number
4801      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4802      * Then the length of the reordering array must be {@code #O},
4803      * and each element must be a non-negative number less than {@code #I}.
4804      * For every {@code N} less than {@code #O}, the {@code N}-th
4805      * outgoing argument will be taken from the {@code I}-th incoming
4806      * argument, where {@code I} is {@code reorder[N]}.
4807      * <p>
4808      * No argument or return value conversions are applied.
4809      * The type of each incoming argument, as determined by {@code newType},
4810      * must be identical to the type of the corresponding outgoing parameter
4811      * or parameters in the target method handle.
4812      * The return type of {@code newType} must be identical to the return
4813      * type of the original target.
4814      * <p>
4815      * The reordering array need not specify an actual permutation.
4816      * An incoming argument will be duplicated if its index appears
4817      * more than once in the array, and an incoming argument will be dropped
4818      * if its index does not appear in the array.
4819      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4820      * incoming arguments which are not mentioned in the reordering array
4821      * may be of any type, as determined only by {@code newType}.
4822      * <blockquote><pre>{@code
4823 import static java.lang.invoke.MethodHandles.*;
4824 import static java.lang.invoke.MethodType.*;
4825 ...
4826 MethodType intfn1 = methodType(int.class, int.class);
4827 MethodType intfn2 = methodType(int.class, int.class, int.class);
4828 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4829 assert(sub.type().equals(intfn2));
4830 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4831 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4832 assert((int)rsub.invokeExact(1, 100) == 99);
4833 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4834 assert(add.type().equals(intfn2));
4835 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4836 assert(twice.type().equals(intfn1));
4837 assert((int)twice.invokeExact(21) == 42);
4838      * }</pre></blockquote>
4839      * <p>
4840      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4841      * variable-arity method handle}, even if the original target method handle was.
4842      * @param target the method handle to invoke after arguments are reordered
4843      * @param newType the expected type of the new method handle
4844      * @param reorder an index array which controls the reordering
4845      * @return a method handle which delegates to the target after it
4846      *           drops unused arguments and moves and/or duplicates the other arguments
4847      * @throws NullPointerException if any argument is null
4848      * @throws IllegalArgumentException if the index array length is not equal to
4849      *                  the arity of the target, or if any index array element
4850      *                  not a valid index for a parameter of {@code newType},
4851      *                  or if two corresponding parameter types in
4852      *                  {@code target.type()} and {@code newType} are not identical,
4853      */
4854     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4855         reorder = reorder.clone();  // get a private copy
4856         MethodType oldType = target.type();
4857         permuteArgumentChecks(reorder, newType, oldType);
4858         // first detect dropped arguments and handle them separately
4859         int[] originalReorder = reorder;
4860         BoundMethodHandle result = target.rebind();
4861         LambdaForm form = result.form;
4862         int newArity = newType.parameterCount();
4863         // Normalize the reordering into a real permutation,
4864         // by removing duplicates and adding dropped elements.
4865         // This somewhat improves lambda form caching, as well
4866         // as simplifying the transform by breaking it up into steps.
4867         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4868             if (ddIdx > 0) {
4869                 // We found a duplicated entry at reorder[ddIdx].
4870                 // Example:  (x,y,z)->asList(x,y,z)
4871                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4872                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4873                 // The starred element corresponds to the argument
4874                 // deleted by the dupArgumentForm transform.
4875                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
4876                 boolean killFirst = false;
4877                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
4878                     // Set killFirst if the dup is larger than an intervening position.
4879                     // This will remove at least one inversion from the permutation.
4880                     if (dupVal > val) killFirst = true;
4881                 }
4882                 if (!killFirst) {
4883                     srcPos = dstPos;
4884                     dstPos = ddIdx;
4885                 }
4886                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
4887                 assert (reorder[srcPos] == reorder[dstPos]);
4888                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
4889                 // contract the reordering by removing the element at dstPos
4890                 int tailPos = dstPos + 1;
4891                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
4892                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
4893             } else {
4894                 int dropVal = ~ddIdx, insPos = 0;
4895                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
4896                     // Find first element of reorder larger than dropVal.
4897                     // This is where we will insert the dropVal.
4898                     insPos += 1;
4899                 }
4900                 Class<?> ptype = newType.parameterType(dropVal);
4901                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
4902                 oldType = oldType.insertParameterTypes(insPos, ptype);
4903                 // expand the reordering by inserting an element at insPos
4904                 int tailPos = insPos + 1;
4905                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
4906                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
4907                 reorder[insPos] = dropVal;
4908             }
4909             assert (permuteArgumentChecks(reorder, newType, oldType));
4910         }
4911         assert (reorder.length == newArity);  // a perfect permutation
4912         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
4913         form = form.editor().permuteArgumentsForm(1, reorder);
4914         if (newType == result.type() && form == result.internalForm())
4915             return result;
4916         return result.copyWith(newType, form);
4917     }
4918 
4919     /**
4920      * Return an indication of any duplicate or omission in reorder.
4921      * If the reorder contains a duplicate entry, return the index of the second occurrence.
4922      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
4923      * Otherwise, return zero.
4924      * If an element not in [0..newArity-1] is encountered, return reorder.length.
4925      */
4926     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
4927         final int BIT_LIMIT = 63;  // max number of bits in bit mask
4928         if (newArity < BIT_LIMIT) {
4929             long mask = 0;
4930             for (int i = 0; i < reorder.length; i++) {
4931                 int arg = reorder[i];
4932                 if (arg >= newArity) {
4933                     return reorder.length;
4934                 }
4935                 long bit = 1L << arg;
4936                 if ((mask & bit) != 0) {
4937                     return i;  // >0 indicates a dup
4938                 }
4939                 mask |= bit;
4940             }
4941             if (mask == (1L << newArity) - 1) {
4942                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
4943                 return 0;
4944             }
4945             // find first zero
4946             long zeroBit = Long.lowestOneBit(~mask);
4947             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
4948             assert(zeroPos <= newArity);
4949             if (zeroPos == newArity) {
4950                 return 0;
4951             }
4952             return ~zeroPos;
4953         } else {
4954             // same algorithm, different bit set
4955             BitSet mask = new BitSet(newArity);
4956             for (int i = 0; i < reorder.length; i++) {
4957                 int arg = reorder[i];
4958                 if (arg >= newArity) {
4959                     return reorder.length;
4960                 }
4961                 if (mask.get(arg)) {
4962                     return i;  // >0 indicates a dup
4963                 }
4964                 mask.set(arg);
4965             }
4966             int zeroPos = mask.nextClearBit(0);
4967             assert(zeroPos <= newArity);
4968             if (zeroPos == newArity) {
4969                 return 0;
4970             }
4971             return ~zeroPos;
4972         }
4973     }
4974 
4975     static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
4976         if (newType.returnType() != oldType.returnType())
4977             throw newIllegalArgumentException("return types do not match",
4978                     oldType, newType);
4979         if (reorder.length != oldType.parameterCount())
4980             throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
4981                     oldType, Arrays.toString(reorder));
4982 
4983         int limit = newType.parameterCount();
4984         for (int j = 0; j < reorder.length; j++) {
4985             int i = reorder[j];
4986             if (i < 0 || i >= limit) {
4987                 throw newIllegalArgumentException("index is out of bounds for new type",
4988                         i, newType);
4989             }
4990             Class<?> src = newType.parameterType(i);
4991             Class<?> dst = oldType.parameterType(j);
4992             if (src != dst)
4993                 throw newIllegalArgumentException("parameter types do not match after reorder",
4994                         oldType, newType);
4995         }
4996         return true;
4997     }
4998 
4999     /**
5000      * Produces a method handle of the requested return type which returns the given
5001      * constant value every time it is invoked.
5002      * <p>
5003      * Before the method handle is returned, the passed-in value is converted to the requested type.
5004      * If the requested type is primitive, widening primitive conversions are attempted,
5005      * else reference conversions are attempted.
5006      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5007      * @param type the return type of the desired method handle
5008      * @param value the value to return
5009      * @return a method handle of the given return type and no arguments, which always returns the given value
5010      * @throws NullPointerException if the {@code type} argument is null
5011      * @throws ClassCastException if the value cannot be converted to the required return type
5012      * @throws IllegalArgumentException if the given type is {@code void.class}
5013      */
5014     public static MethodHandle constant(Class<?> type, Object value) {
5015         if (type.isPrimitive()) {
5016             if (type == void.class)
5017                 throw newIllegalArgumentException("void type");
5018             Wrapper w = Wrapper.forPrimitiveType(type);
5019             value = w.convert(value, type);
5020             if (w.zero().equals(value))
5021                 return zero(w, type);
5022             return insertArguments(identity(type), 0, value);
5023         } else {
5024             if (value == null)
5025                 return zero(Wrapper.OBJECT, type);
5026             return identity(type).bindTo(value);
5027         }
5028     }
5029 
5030     /**
5031      * Produces a method handle which returns its sole argument when invoked.
5032      * @param type the type of the sole parameter and return value of the desired method handle
5033      * @return a unary method handle which accepts and returns the given type
5034      * @throws NullPointerException if the argument is null
5035      * @throws IllegalArgumentException if the given type is {@code void.class}
5036      */
5037     public static MethodHandle identity(Class<?> type) {
5038         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5039         int pos = btw.ordinal();
5040         MethodHandle ident = IDENTITY_MHS[pos];
5041         if (ident == null) {
5042             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5043         }
5044         if (ident.type().returnType() == type)
5045             return ident;
5046         // something like identity(Foo.class); do not bother to intern these
5047         assert (btw == Wrapper.OBJECT);
5048         return makeIdentity(type);
5049     }
5050 
5051     /**
5052      * Produces a constant method handle of the requested return type which
5053      * returns the default value for that type every time it is invoked.
5054      * The resulting constant method handle will have no side effects.
5055      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5056      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5057      * since {@code explicitCastArguments} converts {@code null} to default values.
5058      * @param type the expected return type of the desired method handle
5059      * @return a constant method handle that takes no arguments
5060      *         and returns the default value of the given type (or void, if the type is void)
5061      * @throws NullPointerException if the argument is null
5062      * @see MethodHandles#constant
5063      * @see MethodHandles#empty
5064      * @see MethodHandles#explicitCastArguments
5065      * @since 9
5066      */
5067     public static MethodHandle zero(Class<?> type) {
5068         Objects.requireNonNull(type);
5069         return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
5070     }
5071 
5072     private static MethodHandle identityOrVoid(Class<?> type) {
5073         return type == void.class ? zero(type) : identity(type);
5074     }
5075 
5076     /**
5077      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5078      * and returns a suitable default depending on the return type.
5079      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
5080      * <p>The returned method handle is equivalent to
5081      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5082      *
5083      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5084      * {@code guardWithTest(pred, target, empty(target.type())}.
5085      * @param type the type of the desired method handle
5086      * @return a constant method handle of the given type, which returns a default value of the given return type
5087      * @throws NullPointerException if the argument is null
5088      * @see MethodHandles#zero
5089      * @see MethodHandles#constant
5090      * @since 9
5091      */
5092     public static  MethodHandle empty(MethodType type) {
5093         Objects.requireNonNull(type);
5094         return dropArguments(zero(type.returnType()), 0, type.parameterList());
5095     }
5096 
5097     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5098     private static MethodHandle makeIdentity(Class<?> ptype) {
5099         MethodType mtype = methodType(ptype, ptype);
5100         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5101         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5102     }
5103 
5104     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5105         int pos = btw.ordinal();
5106         MethodHandle zero = ZERO_MHS[pos];
5107         if (zero == null) {
5108             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5109         }
5110         if (zero.type().returnType() == rtype)
5111             return zero;
5112         assert(btw == Wrapper.OBJECT);
5113         return makeZero(rtype);
5114     }
5115     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5116     private static MethodHandle makeZero(Class<?> rtype) {
5117         MethodType mtype = methodType(rtype);
5118         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5119         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
5120     }
5121 
5122     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
5123         // Simulate a CAS, to avoid racy duplication of results.
5124         MethodHandle prev = cache[pos];
5125         if (prev != null) return prev;
5126         return cache[pos] = value;
5127     }
5128 
5129     /**
5130      * Provides a target method handle with one or more <em>bound arguments</em>
5131      * in advance of the method handle's invocation.
5132      * The formal parameters to the target corresponding to the bound
5133      * arguments are called <em>bound parameters</em>.
5134      * Returns a new method handle which saves away the bound arguments.
5135      * When it is invoked, it receives arguments for any non-bound parameters,
5136      * binds the saved arguments to their corresponding parameters,
5137      * and calls the original target.
5138      * <p>
5139      * The type of the new method handle will drop the types for the bound
5140      * parameters from the original target type, since the new method handle
5141      * will no longer require those arguments to be supplied by its callers.
5142      * <p>
5143      * Each given argument object must match the corresponding bound parameter type.
5144      * If a bound parameter type is a primitive, the argument object
5145      * must be a wrapper, and will be unboxed to produce the primitive value.
5146      * <p>
5147      * The {@code pos} argument selects which parameters are to be bound.
5148      * It may range between zero and <i>N-L</i> (inclusively),
5149      * where <i>N</i> is the arity of the target method handle
5150      * and <i>L</i> is the length of the values array.
5151      * <p>
5152      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5153      * variable-arity method handle}, even if the original target method handle was.
5154      * @param target the method handle to invoke after the argument is inserted
5155      * @param pos where to insert the argument (zero for the first)
5156      * @param values the series of arguments to insert
5157      * @return a method handle which inserts an additional argument,
5158      *         before calling the original method handle
5159      * @throws NullPointerException if the target or the {@code values} array is null
5160      * @throws IllegalArgumentException if (@code pos) is less than {@code 0} or greater than
5161      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
5162      *         is the length of the values array.
5163      * @throws ClassCastException if an argument does not match the corresponding bound parameter
5164      *         type.
5165      * @see MethodHandle#bindTo
5166      */
5167     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
5168         int insCount = values.length;
5169         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
5170         if (insCount == 0)  return target;
5171         BoundMethodHandle result = target.rebind();
5172         for (int i = 0; i < insCount; i++) {
5173             Object value = values[i];
5174             Class<?> ptype = ptypes[pos+i];
5175             if (ptype.isPrimitive()) {
5176                 result = insertArgumentPrimitive(result, pos, ptype, value);
5177             } else {
5178                 value = ptype.cast(value);  // throw CCE if needed
5179                 result = result.bindArgumentL(pos, value);
5180             }
5181         }
5182         return result;
5183     }
5184 
5185     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5186                                                              Class<?> ptype, Object value) {
5187         Wrapper w = Wrapper.forPrimitiveType(ptype);
5188         // perform unboxing and/or primitive conversion
5189         value = w.convert(value, ptype);
5190         return switch (w) {
5191             case INT    -> result.bindArgumentI(pos, (int) value);
5192             case LONG   -> result.bindArgumentJ(pos, (long) value);
5193             case FLOAT  -> result.bindArgumentF(pos, (float) value);
5194             case DOUBLE -> result.bindArgumentD(pos, (double) value);
5195             default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5196         };
5197     }
5198 
5199     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5200         MethodType oldType = target.type();
5201         int outargs = oldType.parameterCount();
5202         int inargs  = outargs - insCount;
5203         if (inargs < 0)
5204             throw newIllegalArgumentException("too many values to insert");
5205         if (pos < 0 || pos > inargs)
5206             throw newIllegalArgumentException("no argument type to append");
5207         return oldType.ptypes();
5208     }
5209 
5210     /**
5211      * Produces a method handle which will discard some dummy arguments
5212      * before calling some other specified <i>target</i> method handle.
5213      * The type of the new method handle will be the same as the target's type,
5214      * except it will also include the dummy argument types,
5215      * at some given position.
5216      * <p>
5217      * The {@code pos} argument may range between zero and <i>N</i>,
5218      * where <i>N</i> is the arity of the target.
5219      * If {@code pos} is zero, the dummy arguments will precede
5220      * the target's real arguments; if {@code pos} is <i>N</i>
5221      * they will come after.
5222      * <p>
5223      * <b>Example:</b>
5224      * <blockquote><pre>{@code
5225 import static java.lang.invoke.MethodHandles.*;
5226 import static java.lang.invoke.MethodType.*;
5227 ...
5228 MethodHandle cat = lookup().findVirtual(String.class,
5229   "concat", methodType(String.class, String.class));
5230 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5231 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5232 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5233 assertEquals(bigType, d0.type());
5234 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5235      * }</pre></blockquote>
5236      * <p>
5237      * This method is also equivalent to the following code:
5238      * <blockquote><pre>
5239      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5240      * </pre></blockquote>
5241      * @param target the method handle to invoke after the arguments are dropped
5242      * @param pos position of first argument to drop (zero for the leftmost)
5243      * @param valueTypes the type(s) of the argument(s) to drop
5244      * @return a method handle which drops arguments of the given types,
5245      *         before calling the original method handle
5246      * @throws NullPointerException if the target is null,
5247      *                              or if the {@code valueTypes} list or any of its elements is null
5248      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5249      *                  or if {@code pos} is negative or greater than the arity of the target,
5250      *                  or if the new method handle's type would have too many parameters
5251      */
5252     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5253         return dropArguments0(target, pos, copyTypes(valueTypes.toArray()));
5254     }
5255 
5256     private static List<Class<?>> copyTypes(Object[] array) {
5257         return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class));
5258     }
5259 
5260     private static MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5261         MethodType oldType = target.type();  // get NPE
5262         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5263         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5264         if (dropped == 0)  return target;
5265         BoundMethodHandle result = target.rebind();
5266         LambdaForm lform = result.form;
5267         int insertFormArg = 1 + pos;
5268         for (Class<?> ptype : valueTypes) {
5269             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5270         }
5271         result = result.copyWith(newType, lform);
5272         return result;
5273     }
5274 
5275     private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
5276         int dropped = valueTypes.size();
5277         MethodType.checkSlotCount(dropped);
5278         int outargs = oldType.parameterCount();
5279         int inargs  = outargs + dropped;
5280         if (pos < 0 || pos > outargs)
5281             throw newIllegalArgumentException("no argument type to remove"
5282                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5283                     );
5284         return dropped;
5285     }
5286 
5287     /**
5288      * Produces a method handle which will discard some dummy arguments
5289      * before calling some other specified <i>target</i> method handle.
5290      * The type of the new method handle will be the same as the target's type,
5291      * except it will also include the dummy argument types,
5292      * at some given position.
5293      * <p>
5294      * The {@code pos} argument may range between zero and <i>N</i>,
5295      * where <i>N</i> is the arity of the target.
5296      * If {@code pos} is zero, the dummy arguments will precede
5297      * the target's real arguments; if {@code pos} is <i>N</i>
5298      * they will come after.
5299      * @apiNote
5300      * <blockquote><pre>{@code
5301 import static java.lang.invoke.MethodHandles.*;
5302 import static java.lang.invoke.MethodType.*;
5303 ...
5304 MethodHandle cat = lookup().findVirtual(String.class,
5305   "concat", methodType(String.class, String.class));
5306 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5307 MethodHandle d0 = dropArguments(cat, 0, String.class);
5308 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5309 MethodHandle d1 = dropArguments(cat, 1, String.class);
5310 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5311 MethodHandle d2 = dropArguments(cat, 2, String.class);
5312 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5313 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5314 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5315      * }</pre></blockquote>
5316      * <p>
5317      * This method is also equivalent to the following code:
5318      * <blockquote><pre>
5319      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5320      * </pre></blockquote>
5321      * @param target the method handle to invoke after the arguments are dropped
5322      * @param pos position of first argument to drop (zero for the leftmost)
5323      * @param valueTypes the type(s) of the argument(s) to drop
5324      * @return a method handle which drops arguments of the given types,
5325      *         before calling the original method handle
5326      * @throws NullPointerException if the target is null,
5327      *                              or if the {@code valueTypes} array or any of its elements is null
5328      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5329      *                  or if {@code pos} is negative or greater than the arity of the target,
5330      *                  or if the new method handle's type would have
5331      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
5332      */
5333     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5334         return dropArguments0(target, pos, copyTypes(valueTypes));
5335     }
5336 
5337     // private version which allows caller some freedom with error handling
5338     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
5339                                       boolean nullOnFailure) {
5340         newTypes = copyTypes(newTypes.toArray());
5341         List<Class<?>> oldTypes = target.type().parameterList();
5342         int match = oldTypes.size();
5343         if (skip != 0) {
5344             if (skip < 0 || skip > match) {
5345                 throw newIllegalArgumentException("illegal skip", skip, target);
5346             }
5347             oldTypes = oldTypes.subList(skip, match);
5348             match -= skip;
5349         }
5350         List<Class<?>> addTypes = newTypes;
5351         int add = addTypes.size();
5352         if (pos != 0) {
5353             if (pos < 0 || pos > add) {
5354                 throw newIllegalArgumentException("illegal pos", pos, newTypes);
5355             }
5356             addTypes = addTypes.subList(pos, add);
5357             add -= pos;
5358             assert(addTypes.size() == add);
5359         }
5360         // Do not add types which already match the existing arguments.
5361         if (match > add || !oldTypes.equals(addTypes.subList(0, match))) {
5362             if (nullOnFailure) {
5363                 return null;
5364             }
5365             throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes);
5366         }
5367         addTypes = addTypes.subList(match, add);
5368         add -= match;
5369         assert(addTypes.size() == add);
5370         // newTypes:     (   P*[pos], M*[match], A*[add] )
5371         // target: ( S*[skip],        M*[match]  )
5372         MethodHandle adapter = target;
5373         if (add > 0) {
5374             adapter = dropArguments0(adapter, skip+ match, addTypes);
5375         }
5376         // adapter: (S*[skip],        M*[match], A*[add] )
5377         if (pos > 0) {
5378             adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos));
5379         }
5380         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5381         return adapter;
5382     }
5383 
5384     /**
5385      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5386      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5387      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5388      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5389      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5390      * {@link #dropArguments(MethodHandle, int, Class[])}.
5391      * <p>
5392      * The resulting handle will have the same return type as the target handle.
5393      * <p>
5394      * In more formal terms, assume these two type lists:<ul>
5395      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5396      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5397      * {@code newTypes}.
5398      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5399      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5400      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5401      * sub-list.
5402      * </ul>
5403      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5404      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5405      * {@link #dropArguments(MethodHandle, int, Class[])}.
5406      *
5407      * @apiNote
5408      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5409      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5410      * <blockquote><pre>{@code
5411 import static java.lang.invoke.MethodHandles.*;
5412 import static java.lang.invoke.MethodType.*;
5413 ...
5414 ...
5415 MethodHandle h0 = constant(boolean.class, true);
5416 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5417 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5418 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5419 if (h1.type().parameterCount() < h2.type().parameterCount())
5420     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5421 else
5422     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5423 MethodHandle h3 = guardWithTest(h0, h1, h2);
5424 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5425      * }</pre></blockquote>
5426      * @param target the method handle to adapt
5427      * @param skip number of targets parameters to disregard (they will be unchanged)
5428      * @param newTypes the list of types to match {@code target}'s parameter type list to
5429      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5430      * @return a possibly adapted method handle
5431      * @throws NullPointerException if either argument is null
5432      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5433      *         or if {@code skip} is negative or greater than the arity of the target,
5434      *         or if {@code pos} is negative or greater than the newTypes list size,
5435      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5436      *         {@code pos}.
5437      * @since 9
5438      */
5439     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5440         Objects.requireNonNull(target);
5441         Objects.requireNonNull(newTypes);
5442         return dropArgumentsToMatch(target, skip, newTypes, pos, false);
5443     }
5444 
5445     /**
5446      * Drop the return value of the target handle (if any).
5447      * The returned method handle will have a {@code void} return type.
5448      *
5449      * @param target the method handle to adapt
5450      * @return a possibly adapted method handle
5451      * @throws NullPointerException if {@code target} is null
5452      * @since 16
5453      */
5454     public static MethodHandle dropReturn(MethodHandle target) {
5455         Objects.requireNonNull(target);
5456         MethodType oldType = target.type();
5457         Class<?> oldReturnType = oldType.returnType();
5458         if (oldReturnType == void.class)
5459             return target;
5460         MethodType newType = oldType.changeReturnType(void.class);
5461         BoundMethodHandle result = target.rebind();
5462         LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5463         result = result.copyWith(newType, lform);
5464         return result;
5465     }
5466 
5467     /**
5468      * Adapts a target method handle by pre-processing
5469      * one or more of its arguments, each with its own unary filter function,
5470      * and then calling the target with each pre-processed argument
5471      * replaced by the result of its corresponding filter function.
5472      * <p>
5473      * The pre-processing is performed by one or more method handles,
5474      * specified in the elements of the {@code filters} array.
5475      * The first element of the filter array corresponds to the {@code pos}
5476      * argument of the target, and so on in sequence.
5477      * The filter functions are invoked in left to right order.
5478      * <p>
5479      * Null arguments in the array are treated as identity functions,
5480      * and the corresponding arguments left unchanged.
5481      * (If there are no non-null elements in the array, the original target is returned.)
5482      * Each filter is applied to the corresponding argument of the adapter.
5483      * <p>
5484      * If a filter {@code F} applies to the {@code N}th argument of
5485      * the target, then {@code F} must be a method handle which
5486      * takes exactly one argument.  The type of {@code F}'s sole argument
5487      * replaces the corresponding argument type of the target
5488      * in the resulting adapted method handle.
5489      * The return type of {@code F} must be identical to the corresponding
5490      * parameter type of the target.
5491      * <p>
5492      * It is an error if there are elements of {@code filters}
5493      * (null or not)
5494      * which do not correspond to argument positions in the target.
5495      * <p><b>Example:</b>
5496      * <blockquote><pre>{@code
5497 import static java.lang.invoke.MethodHandles.*;
5498 import static java.lang.invoke.MethodType.*;
5499 ...
5500 MethodHandle cat = lookup().findVirtual(String.class,
5501   "concat", methodType(String.class, String.class));
5502 MethodHandle upcase = lookup().findVirtual(String.class,
5503   "toUpperCase", methodType(String.class));
5504 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5505 MethodHandle f0 = filterArguments(cat, 0, upcase);
5506 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5507 MethodHandle f1 = filterArguments(cat, 1, upcase);
5508 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5509 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5510 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5511      * }</pre></blockquote>
5512      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5513      * denotes the return type of both the {@code target} and resulting adapter.
5514      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5515      * of the parameters and arguments that precede and follow the filter position
5516      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5517      * values of the filtered parameters and arguments; they also represent the
5518      * return types of the {@code filter[i]} handles. The latter accept arguments
5519      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5520      * the resulting adapter.
5521      * <blockquote><pre>{@code
5522      * T target(P... p, A[i]... a[i], B... b);
5523      * A[i] filter[i](V[i]);
5524      * T adapter(P... p, V[i]... v[i], B... b) {
5525      *   return target(p..., filter[i](v[i])..., b...);
5526      * }
5527      * }</pre></blockquote>
5528      * <p>
5529      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5530      * variable-arity method handle}, even if the original target method handle was.
5531      *
5532      * @param target the method handle to invoke after arguments are filtered
5533      * @param pos the position of the first argument to filter
5534      * @param filters method handles to call initially on filtered arguments
5535      * @return method handle which incorporates the specified argument filtering logic
5536      * @throws NullPointerException if the target is null
5537      *                              or if the {@code filters} array is null
5538      * @throws IllegalArgumentException if a non-null element of {@code filters}
5539      *          does not match a corresponding argument type of target as described above,
5540      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5541      *          or if the resulting method handle's type would have
5542      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5543      */
5544     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5545         // In method types arguments start at index 0, while the LF
5546         // editor have the MH receiver at position 0 - adjust appropriately.
5547         final int MH_RECEIVER_OFFSET = 1;
5548         filterArgumentsCheckArity(target, pos, filters);
5549         MethodHandle adapter = target;
5550 
5551         // keep track of currently matched filters, as to optimize repeated filters
5552         int index = 0;
5553         int[] positions = new int[filters.length];
5554         MethodHandle filter = null;
5555 
5556         // process filters in reverse order so that the invocation of
5557         // the resulting adapter will invoke the filters in left-to-right order
5558         for (int i = filters.length - 1; i >= 0; --i) {
5559             MethodHandle newFilter = filters[i];
5560             if (newFilter == null) continue;  // ignore null elements of filters
5561 
5562             // flush changes on update
5563             if (filter != newFilter) {
5564                 if (filter != null) {
5565                     if (index > 1) {
5566                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5567                     } else {
5568                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5569                     }
5570                 }
5571                 filter = newFilter;
5572                 index = 0;
5573             }
5574 
5575             filterArgumentChecks(target, pos + i, newFilter);
5576             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5577         }
5578         if (index > 1) {
5579             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5580         } else if (index == 1) {
5581             adapter = filterArgument(adapter, positions[0] - 1, filter);
5582         }
5583         return adapter;
5584     }
5585 
5586     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5587         MethodType targetType = adapter.type();
5588         MethodType filterType = filter.type();
5589         BoundMethodHandle result = adapter.rebind();
5590         Class<?> newParamType = filterType.parameterType(0);
5591 
5592         Class<?>[] ptypes = targetType.ptypes().clone();
5593         for (int pos : positions) {
5594             ptypes[pos - 1] = newParamType;
5595         }
5596         MethodType newType = MethodType.makeImpl(targetType.rtype(), ptypes, true);
5597 
5598         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5599         return result.copyWithExtendL(newType, lform, filter);
5600     }
5601 
5602     /*non-public*/
5603     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5604         filterArgumentChecks(target, pos, filter);
5605         MethodType targetType = target.type();
5606         MethodType filterType = filter.type();
5607         BoundMethodHandle result = target.rebind();
5608         Class<?> newParamType = filterType.parameterType(0);
5609         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5610         MethodType newType = targetType.changeParameterType(pos, newParamType);
5611         result = result.copyWithExtendL(newType, lform, filter);
5612         return result;
5613     }
5614 
5615     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5616         MethodType targetType = target.type();
5617         int maxPos = targetType.parameterCount();
5618         if (pos + filters.length > maxPos)
5619             throw newIllegalArgumentException("too many filters");
5620     }
5621 
5622     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5623         MethodType targetType = target.type();
5624         MethodType filterType = filter.type();
5625         if (filterType.parameterCount() != 1
5626             || filterType.returnType() != targetType.parameterType(pos))
5627             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5628     }
5629 
5630     /**
5631      * Adapts a target method handle by pre-processing
5632      * a sub-sequence of its arguments with a filter (another method handle).
5633      * The pre-processed arguments are replaced by the result (if any) of the
5634      * filter function.
5635      * The target is then called on the modified (usually shortened) argument list.
5636      * <p>
5637      * If the filter returns a value, the target must accept that value as
5638      * its argument in position {@code pos}, preceded and/or followed by
5639      * any arguments not passed to the filter.
5640      * If the filter returns void, the target must accept all arguments
5641      * not passed to the filter.
5642      * No arguments are reordered, and a result returned from the filter
5643      * replaces (in order) the whole subsequence of arguments originally
5644      * passed to the adapter.
5645      * <p>
5646      * The argument types (if any) of the filter
5647      * replace zero or one argument types of the target, at position {@code pos},
5648      * in the resulting adapted method handle.
5649      * The return type of the filter (if any) must be identical to the
5650      * argument type of the target at position {@code pos}, and that target argument
5651      * is supplied by the return value of the filter.
5652      * <p>
5653      * In all cases, {@code pos} must be greater than or equal to zero, and
5654      * {@code pos} must also be less than or equal to the target's arity.
5655      * <p><b>Example:</b>
5656      * <blockquote><pre>{@code
5657 import static java.lang.invoke.MethodHandles.*;
5658 import static java.lang.invoke.MethodType.*;
5659 ...
5660 MethodHandle deepToString = publicLookup()
5661   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5662 
5663 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5664 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5665 
5666 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5667 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5668 
5669 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5670 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5671 assertEquals("[top, [up, down], strange]",
5672              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5673 
5674 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5675 assertEquals("[top, [up, down], [strange]]",
5676              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5677 
5678 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5679 assertEquals("[top, [[up, down, strange], charm], bottom]",
5680              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5681      * }</pre></blockquote>
5682      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5683      * represents the return type of the {@code target} and resulting adapter.
5684      * {@code V}/{@code v} stand for the return type and value of the
5685      * {@code filter}, which are also found in the signature and arguments of
5686      * the {@code target}, respectively, unless {@code V} is {@code void}.
5687      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5688      * and values preceding and following the collection position, {@code pos},
5689      * in the {@code target}'s signature. They also turn up in the resulting
5690      * adapter's signature and arguments, where they surround
5691      * {@code B}/{@code b}, which represent the parameter types and arguments
5692      * to the {@code filter} (if any).
5693      * <blockquote><pre>{@code
5694      * T target(A...,V,C...);
5695      * V filter(B...);
5696      * T adapter(A... a,B... b,C... c) {
5697      *   V v = filter(b...);
5698      *   return target(a...,v,c...);
5699      * }
5700      * // and if the filter has no arguments:
5701      * T target2(A...,V,C...);
5702      * V filter2();
5703      * T adapter2(A... a,C... c) {
5704      *   V v = filter2();
5705      *   return target2(a...,v,c...);
5706      * }
5707      * // and if the filter has a void return:
5708      * T target3(A...,C...);
5709      * void filter3(B...);
5710      * T adapter3(A... a,B... b,C... c) {
5711      *   filter3(b...);
5712      *   return target3(a...,c...);
5713      * }
5714      * }</pre></blockquote>
5715      * <p>
5716      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5717      * one which first "folds" the affected arguments, and then drops them, in separate
5718      * steps as follows:
5719      * <blockquote><pre>{@code
5720      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5721      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5722      * }</pre></blockquote>
5723      * If the target method handle consumes no arguments besides than the result
5724      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5725      * is equivalent to {@code filterReturnValue(coll, mh)}.
5726      * If the filter method handle {@code coll} consumes one argument and produces
5727      * a non-void result, then {@code collectArguments(mh, N, coll)}
5728      * is equivalent to {@code filterArguments(mh, N, coll)}.
5729      * Other equivalences are possible but would require argument permutation.
5730      * <p>
5731      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5732      * variable-arity method handle}, even if the original target method handle was.
5733      *
5734      * @param target the method handle to invoke after filtering the subsequence of arguments
5735      * @param pos the position of the first adapter argument to pass to the filter,
5736      *            and/or the target argument which receives the result of the filter
5737      * @param filter method handle to call on the subsequence of arguments
5738      * @return method handle which incorporates the specified argument subsequence filtering logic
5739      * @throws NullPointerException if either argument is null
5740      * @throws IllegalArgumentException if the return type of {@code filter}
5741      *          is non-void and is not the same as the {@code pos} argument of the target,
5742      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5743      *          or if the resulting method handle's type would have
5744      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5745      * @see MethodHandles#foldArguments
5746      * @see MethodHandles#filterArguments
5747      * @see MethodHandles#filterReturnValue
5748      */
5749     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5750         MethodType newType = collectArgumentsChecks(target, pos, filter);
5751         MethodType collectorType = filter.type();
5752         BoundMethodHandle result = target.rebind();
5753         LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5754         return result.copyWithExtendL(newType, lform, filter);
5755     }
5756 
5757     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5758         MethodType targetType = target.type();
5759         MethodType filterType = filter.type();
5760         Class<?> rtype = filterType.returnType();
5761         List<Class<?>> filterArgs = filterType.parameterList();
5762         if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5763                        (rtype != void.class && pos >= targetType.parameterCount())) {
5764             throw newIllegalArgumentException("position is out of range for target", target, pos);
5765         }
5766         if (rtype == void.class) {
5767             return targetType.insertParameterTypes(pos, filterArgs);
5768         }
5769         if (rtype != targetType.parameterType(pos)) {
5770             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5771         }
5772         return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
5773     }
5774 
5775     /**
5776      * Adapts a target method handle by post-processing
5777      * its return value (if any) with a filter (another method handle).
5778      * The result of the filter is returned from the adapter.
5779      * <p>
5780      * If the target returns a value, the filter must accept that value as
5781      * its only argument.
5782      * If the target returns void, the filter must accept no arguments.
5783      * <p>
5784      * The return type of the filter
5785      * replaces the return type of the target
5786      * in the resulting adapted method handle.
5787      * The argument type of the filter (if any) must be identical to the
5788      * return type of the target.
5789      * <p><b>Example:</b>
5790      * <blockquote><pre>{@code
5791 import static java.lang.invoke.MethodHandles.*;
5792 import static java.lang.invoke.MethodType.*;
5793 ...
5794 MethodHandle cat = lookup().findVirtual(String.class,
5795   "concat", methodType(String.class, String.class));
5796 MethodHandle length = lookup().findVirtual(String.class,
5797   "length", methodType(int.class));
5798 System.out.println((String) cat.invokeExact("x", "y")); // xy
5799 MethodHandle f0 = filterReturnValue(cat, length);
5800 System.out.println((int) f0.invokeExact("x", "y")); // 2
5801      * }</pre></blockquote>
5802      * <p>Here is pseudocode for the resulting adapter. In the code,
5803      * {@code T}/{@code t} represent the result type and value of the
5804      * {@code target}; {@code V}, the result type of the {@code filter}; and
5805      * {@code A}/{@code a}, the types and values of the parameters and arguments
5806      * of the {@code target} as well as the resulting adapter.
5807      * <blockquote><pre>{@code
5808      * T target(A...);
5809      * V filter(T);
5810      * V adapter(A... a) {
5811      *   T t = target(a...);
5812      *   return filter(t);
5813      * }
5814      * // and if the target has a void return:
5815      * void target2(A...);
5816      * V filter2();
5817      * V adapter2(A... a) {
5818      *   target2(a...);
5819      *   return filter2();
5820      * }
5821      * // and if the filter has a void return:
5822      * T target3(A...);
5823      * void filter3(V);
5824      * void adapter3(A... a) {
5825      *   T t = target3(a...);
5826      *   filter3(t);
5827      * }
5828      * }</pre></blockquote>
5829      * <p>
5830      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5831      * variable-arity method handle}, even if the original target method handle was.
5832      * @param target the method handle to invoke before filtering the return value
5833      * @param filter method handle to call on the return value
5834      * @return method handle which incorporates the specified return value filtering logic
5835      * @throws NullPointerException if either argument is null
5836      * @throws IllegalArgumentException if the argument list of {@code filter}
5837      *          does not match the return type of target as described above
5838      */
5839     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5840         MethodType targetType = target.type();
5841         MethodType filterType = filter.type();
5842         filterReturnValueChecks(targetType, filterType);
5843         BoundMethodHandle result = target.rebind();
5844         BasicType rtype = BasicType.basicType(filterType.returnType());
5845         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5846         MethodType newType = targetType.changeReturnType(filterType.returnType());
5847         result = result.copyWithExtendL(newType, lform, filter);
5848         return result;
5849     }
5850 
5851     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5852         Class<?> rtype = targetType.returnType();
5853         int filterValues = filterType.parameterCount();
5854         if (filterValues == 0
5855                 ? (rtype != void.class)
5856                 : (rtype != filterType.parameterType(0) || filterValues != 1))
5857             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5858     }
5859 
5860     /**
5861      * Filter the return value of a target method handle with a filter function. The filter function is
5862      * applied to the return value of the original handle; if the filter specifies more than one parameters,
5863      * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5864      * as follows:
5865      * <blockquote><pre>{@code
5866      * T target(A...)
5867      * V filter(B... , T)
5868      * V adapter(A... a, B... b) {
5869      *     T t = target(a...);
5870      *     return filter(b..., t);
5871      * }</pre></blockquote>
5872      * <p>
5873      * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
5874      *
5875      * @param target the target method handle
5876      * @param filter the filter method handle
5877      * @return the adapter method handle
5878      */
5879     /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
5880         MethodType targetType = target.type();
5881         MethodType filterType = filter.type();
5882         BoundMethodHandle result = target.rebind();
5883         LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
5884         MethodType newType = targetType.changeReturnType(filterType.returnType());
5885         if (filterType.parameterCount() > 1) {
5886             for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
5887                 newType = newType.appendParameterTypes(filterType.parameterType(i));
5888             }
5889         }
5890         result = result.copyWithExtendL(newType, lform, filter);
5891         return result;
5892     }
5893 
5894     /**
5895      * Adapts a target method handle by pre-processing
5896      * some of its arguments, and then calling the target with
5897      * the result of the pre-processing, inserted into the original
5898      * sequence of arguments.
5899      * <p>
5900      * The pre-processing is performed by {@code combiner}, a second method handle.
5901      * Of the arguments passed to the adapter, the first {@code N} arguments
5902      * are copied to the combiner, which is then called.
5903      * (Here, {@code N} is defined as the parameter count of the combiner.)
5904      * After this, control passes to the target, with any result
5905      * from the combiner inserted before the original {@code N} incoming
5906      * arguments.
5907      * <p>
5908      * If the combiner returns a value, the first parameter type of the target
5909      * must be identical with the return type of the combiner, and the next
5910      * {@code N} parameter types of the target must exactly match the parameters
5911      * of the combiner.
5912      * <p>
5913      * If the combiner has a void return, no result will be inserted,
5914      * and the first {@code N} parameter types of the target
5915      * must exactly match the parameters of the combiner.
5916      * <p>
5917      * The resulting adapter is the same type as the target, except that the
5918      * first parameter type is dropped,
5919      * if it corresponds to the result of the combiner.
5920      * <p>
5921      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
5922      * that either the combiner or the target does not wish to receive.
5923      * If some of the incoming arguments are destined only for the combiner,
5924      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
5925      * arguments will not need to be live on the stack on entry to the
5926      * target.)
5927      * <p><b>Example:</b>
5928      * <blockquote><pre>{@code
5929 import static java.lang.invoke.MethodHandles.*;
5930 import static java.lang.invoke.MethodType.*;
5931 ...
5932 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5933   "println", methodType(void.class, String.class))
5934     .bindTo(System.out);
5935 MethodHandle cat = lookup().findVirtual(String.class,
5936   "concat", methodType(String.class, String.class));
5937 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5938 MethodHandle catTrace = foldArguments(cat, trace);
5939 // also prints "boo":
5940 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5941      * }</pre></blockquote>
5942      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5943      * represents the result type of the {@code target} and resulting adapter.
5944      * {@code V}/{@code v} represent the type and value of the parameter and argument
5945      * of {@code target} that precedes the folding position; {@code V} also is
5946      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
5947      * types and values of the {@code N} parameters and arguments at the folding
5948      * position. {@code B}/{@code b} represent the types and values of the
5949      * {@code target} parameters and arguments that follow the folded parameters
5950      * and arguments.
5951      * <blockquote><pre>{@code
5952      * // there are N arguments in A...
5953      * T target(V, A[N]..., B...);
5954      * V combiner(A...);
5955      * T adapter(A... a, B... b) {
5956      *   V v = combiner(a...);
5957      *   return target(v, a..., b...);
5958      * }
5959      * // and if the combiner has a void return:
5960      * T target2(A[N]..., B...);
5961      * void combiner2(A...);
5962      * T adapter2(A... a, B... b) {
5963      *   combiner2(a...);
5964      *   return target2(a..., b...);
5965      * }
5966      * }</pre></blockquote>
5967      * <p>
5968      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5969      * variable-arity method handle}, even if the original target method handle was.
5970      * @param target the method handle to invoke after arguments are combined
5971      * @param combiner method handle to call initially on the incoming arguments
5972      * @return method handle which incorporates the specified argument folding logic
5973      * @throws NullPointerException if either argument is null
5974      * @throws IllegalArgumentException if {@code combiner}'s return type
5975      *          is non-void and not the same as the first argument type of
5976      *          the target, or if the initial {@code N} argument types
5977      *          of the target
5978      *          (skipping one matching the {@code combiner}'s return type)
5979      *          are not identical with the argument types of {@code combiner}
5980      */
5981     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
5982         return foldArguments(target, 0, combiner);
5983     }
5984 
5985     /**
5986      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
5987      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
5988      * before the folded arguments.
5989      * <p>
5990      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
5991      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
5992      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
5993      * 0.
5994      *
5995      * @apiNote Example:
5996      * <blockquote><pre>{@code
5997     import static java.lang.invoke.MethodHandles.*;
5998     import static java.lang.invoke.MethodType.*;
5999     ...
6000     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6001     "println", methodType(void.class, String.class))
6002     .bindTo(System.out);
6003     MethodHandle cat = lookup().findVirtual(String.class,
6004     "concat", methodType(String.class, String.class));
6005     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6006     MethodHandle catTrace = foldArguments(cat, 1, trace);
6007     // also prints "jum":
6008     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6009      * }</pre></blockquote>
6010      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6011      * represents the result type of the {@code target} and resulting adapter.
6012      * {@code V}/{@code v} represent the type and value of the parameter and argument
6013      * of {@code target} that precedes the folding position; {@code V} also is
6014      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6015      * types and values of the {@code N} parameters and arguments at the folding
6016      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
6017      * and values of the {@code target} parameters and arguments that precede and
6018      * follow the folded parameters and arguments starting at {@code pos},
6019      * respectively.
6020      * <blockquote><pre>{@code
6021      * // there are N arguments in A...
6022      * T target(Z..., V, A[N]..., B...);
6023      * V combiner(A...);
6024      * T adapter(Z... z, A... a, B... b) {
6025      *   V v = combiner(a...);
6026      *   return target(z..., v, a..., b...);
6027      * }
6028      * // and if the combiner has a void return:
6029      * T target2(Z..., A[N]..., B...);
6030      * void combiner2(A...);
6031      * T adapter2(Z... z, A... a, B... b) {
6032      *   combiner2(a...);
6033      *   return target2(z..., a..., b...);
6034      * }
6035      * }</pre></blockquote>
6036      * <p>
6037      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6038      * variable-arity method handle}, even if the original target method handle was.
6039      *
6040      * @param target the method handle to invoke after arguments are combined
6041      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
6042      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6043      * @param combiner method handle to call initially on the incoming arguments
6044      * @return method handle which incorporates the specified argument folding logic
6045      * @throws NullPointerException if either argument is null
6046      * @throws IllegalArgumentException if either of the following two conditions holds:
6047      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6048      *              {@code pos} of the target signature;
6049      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
6050      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
6051      *
6052      * @see #foldArguments(MethodHandle, MethodHandle)
6053      * @since 9
6054      */
6055     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
6056         MethodType targetType = target.type();
6057         MethodType combinerType = combiner.type();
6058         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
6059         BoundMethodHandle result = target.rebind();
6060         boolean dropResult = rtype == void.class;
6061         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
6062         MethodType newType = targetType;
6063         if (!dropResult) {
6064             newType = newType.dropParameterTypes(pos, pos + 1);
6065         }
6066         result = result.copyWithExtendL(newType, lform, combiner);
6067         return result;
6068     }
6069 
6070     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
6071         int foldArgs   = combinerType.parameterCount();
6072         Class<?> rtype = combinerType.returnType();
6073         int foldVals = rtype == void.class ? 0 : 1;
6074         int afterInsertPos = foldPos + foldVals;
6075         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
6076         if (ok) {
6077             for (int i = 0; i < foldArgs; i++) {
6078                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
6079                     ok = false;
6080                     break;
6081                 }
6082             }
6083         }
6084         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
6085             ok = false;
6086         if (!ok)
6087             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6088         return rtype;
6089     }
6090 
6091     /**
6092      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
6093      * of the pre-processing replacing the argument at the given position.
6094      *
6095      * @param target the method handle to invoke after arguments are combined
6096      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6097      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6098      * @param combiner method handle to call initially on the incoming arguments
6099      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6100      * @return method handle which incorporates the specified argument folding logic
6101      * @throws NullPointerException if either argument is null
6102      * @throws IllegalArgumentException if either of the following two conditions holds:
6103      *          (1) {@code combiner}'s return type is not the same as the argument type at position
6104      *              {@code pos} of the target signature;
6105      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
6106      *              not identical with the argument types of {@code combiner}.
6107      */
6108     /*non-public*/
6109     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6110         return argumentsWithCombiner(true, target, position, combiner, argPositions);
6111     }
6112 
6113     /**
6114      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
6115      * the pre-processing inserted into the original sequence of arguments at the given position.
6116      *
6117      * @param target the method handle to invoke after arguments are combined
6118      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6119      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6120      * @param combiner method handle to call initially on the incoming arguments
6121      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6122      * @return method handle which incorporates the specified argument folding logic
6123      * @throws NullPointerException if either argument is null
6124      * @throws IllegalArgumentException if either of the following two conditions holds:
6125      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6126      *              {@code pos} of the target signature;
6127      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
6128      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
6129      *              with the argument types of {@code combiner}.
6130      */
6131     /*non-public*/
6132     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6133         return argumentsWithCombiner(false, target, position, combiner, argPositions);
6134     }
6135 
6136     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6137         MethodType targetType = target.type();
6138         MethodType combinerType = combiner.type();
6139         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
6140         BoundMethodHandle result = target.rebind();
6141 
6142         MethodType newType = targetType;
6143         LambdaForm lform;
6144         if (filter) {
6145             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
6146         } else {
6147             boolean dropResult = rtype == void.class;
6148             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
6149             if (!dropResult) {
6150                 newType = newType.dropParameterTypes(position, position + 1);
6151             }
6152         }
6153         result = result.copyWithExtendL(newType, lform, combiner);
6154         return result;
6155     }
6156 
6157     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
6158         int combinerArgs = combinerType.parameterCount();
6159         if (argPos.length != combinerArgs) {
6160             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
6161         }
6162         Class<?> rtype = combinerType.returnType();
6163 
6164         for (int i = 0; i < combinerArgs; i++) {
6165             int arg = argPos[i];
6166             if (arg < 0 || arg > targetType.parameterCount()) {
6167                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
6168             }
6169             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
6170                 throw newIllegalArgumentException("target argument type at position " + arg
6171                         + " must match combiner argument type at index " + i + ": " + targetType
6172                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6173             }
6174         }
6175         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6176             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6177         }
6178         return rtype;
6179     }
6180 
6181     /**
6182      * Makes a method handle which adapts a target method handle,
6183      * by guarding it with a test, a boolean-valued method handle.
6184      * If the guard fails, a fallback handle is called instead.
6185      * All three method handles must have the same corresponding
6186      * argument and return types, except that the return type
6187      * of the test must be boolean, and the test is allowed
6188      * to have fewer arguments than the other two method handles.
6189      * <p>
6190      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6191      * represents the uniform result type of the three involved handles;
6192      * {@code A}/{@code a}, the types and values of the {@code target}
6193      * parameters and arguments that are consumed by the {@code test}; and
6194      * {@code B}/{@code b}, those types and values of the {@code target}
6195      * parameters and arguments that are not consumed by the {@code test}.
6196      * <blockquote><pre>{@code
6197      * boolean test(A...);
6198      * T target(A...,B...);
6199      * T fallback(A...,B...);
6200      * T adapter(A... a,B... b) {
6201      *   if (test(a...))
6202      *     return target(a..., b...);
6203      *   else
6204      *     return fallback(a..., b...);
6205      * }
6206      * }</pre></blockquote>
6207      * Note that the test arguments ({@code a...} in the pseudocode) cannot
6208      * be modified by execution of the test, and so are passed unchanged
6209      * from the caller to the target or fallback as appropriate.
6210      * @param test method handle used for test, must return boolean
6211      * @param target method handle to call if test passes
6212      * @param fallback method handle to call if test fails
6213      * @return method handle which incorporates the specified if/then/else logic
6214      * @throws NullPointerException if any argument is null
6215      * @throws IllegalArgumentException if {@code test} does not return boolean,
6216      *          or if all three method types do not match (with the return
6217      *          type of {@code test} changed to match that of the target).
6218      */
6219     public static MethodHandle guardWithTest(MethodHandle test,
6220                                MethodHandle target,
6221                                MethodHandle fallback) {
6222         MethodType gtype = test.type();
6223         MethodType ttype = target.type();
6224         MethodType ftype = fallback.type();
6225         if (!ttype.equals(ftype))
6226             throw misMatchedTypes("target and fallback types", ttype, ftype);
6227         if (gtype.returnType() != boolean.class)
6228             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6229         List<Class<?>> targs = ttype.parameterList();
6230         test = dropArgumentsToMatch(test, 0, targs, 0, true);
6231         if (test == null) {
6232             throw misMatchedTypes("target and test types", ttype, gtype);
6233         }
6234         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6235     }
6236 
6237     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6238         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6239     }
6240 
6241     /**
6242      * Makes a method handle which adapts a target method handle,
6243      * by running it inside an exception handler.
6244      * If the target returns normally, the adapter returns that value.
6245      * If an exception matching the specified type is thrown, the fallback
6246      * handle is called instead on the exception, plus the original arguments.
6247      * <p>
6248      * The target and handler must have the same corresponding
6249      * argument and return types, except that handler may omit trailing arguments
6250      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6251      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6252      * <p>
6253      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6254      * represents the return type of the {@code target} and {@code handler},
6255      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6256      * the types and values of arguments to the resulting handle consumed by
6257      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6258      * resulting handle discarded by {@code handler}.
6259      * <blockquote><pre>{@code
6260      * T target(A..., B...);
6261      * T handler(ExType, A...);
6262      * T adapter(A... a, B... b) {
6263      *   try {
6264      *     return target(a..., b...);
6265      *   } catch (ExType ex) {
6266      *     return handler(ex, a...);
6267      *   }
6268      * }
6269      * }</pre></blockquote>
6270      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6271      * be modified by execution of the target, and so are passed unchanged
6272      * from the caller to the handler, if the handler is invoked.
6273      * <p>
6274      * The target and handler must return the same type, even if the handler
6275      * always throws.  (This might happen, for instance, because the handler
6276      * is simulating a {@code finally} clause).
6277      * To create such a throwing handler, compose the handler creation logic
6278      * with {@link #throwException throwException},
6279      * in order to create a method handle of the correct return type.
6280      * @param target method handle to call
6281      * @param exType the type of exception which the handler will catch
6282      * @param handler method handle to call if a matching exception is thrown
6283      * @return method handle which incorporates the specified try/catch logic
6284      * @throws NullPointerException if any argument is null
6285      * @throws IllegalArgumentException if {@code handler} does not accept
6286      *          the given exception type, or if the method handle types do
6287      *          not match in their return types and their
6288      *          corresponding parameters
6289      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6290      */
6291     public static MethodHandle catchException(MethodHandle target,
6292                                 Class<? extends Throwable> exType,
6293                                 MethodHandle handler) {
6294         MethodType ttype = target.type();
6295         MethodType htype = handler.type();
6296         if (!Throwable.class.isAssignableFrom(exType))
6297             throw new ClassCastException(exType.getName());
6298         if (htype.parameterCount() < 1 ||
6299             !htype.parameterType(0).isAssignableFrom(exType))
6300             throw newIllegalArgumentException("handler does not accept exception type "+exType);
6301         if (htype.returnType() != ttype.returnType())
6302             throw misMatchedTypes("target and handler return types", ttype, htype);
6303         handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
6304         if (handler == null) {
6305             throw misMatchedTypes("target and handler types", ttype, htype);
6306         }
6307         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6308     }
6309 
6310     /**
6311      * Produces a method handle which will throw exceptions of the given {@code exType}.
6312      * The method handle will accept a single argument of {@code exType},
6313      * and immediately throw it as an exception.
6314      * The method type will nominally specify a return of {@code returnType}.
6315      * The return type may be anything convenient:  It doesn't matter to the
6316      * method handle's behavior, since it will never return normally.
6317      * @param returnType the return type of the desired method handle
6318      * @param exType the parameter type of the desired method handle
6319      * @return method handle which can throw the given exceptions
6320      * @throws NullPointerException if either argument is null
6321      */
6322     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6323         if (!Throwable.class.isAssignableFrom(exType))
6324             throw new ClassCastException(exType.getName());
6325         return MethodHandleImpl.throwException(methodType(returnType, exType));
6326     }
6327 
6328     /**
6329      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6330      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6331      * delivers the loop's result, which is the return value of the resulting handle.
6332      * <p>
6333      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6334      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6335      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6336      * terms of method handles, each clause will specify up to four independent actions:<ul>
6337      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6338      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6339      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6340      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6341      * </ul>
6342      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6343      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
6344      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6345      * <p>
6346      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6347      * this case. See below for a detailed description.
6348      * <p>
6349      * <em>Parameters optional everywhere:</em>
6350      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6351      * As an exception, the init functions cannot take any {@code v} parameters,
6352      * because those values are not yet computed when the init functions are executed.
6353      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6354      * In fact, any clause function may take no arguments at all.
6355      * <p>
6356      * <em>Loop parameters:</em>
6357      * A clause function may take all the iteration variable values it is entitled to, in which case
6358      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6359      * with their types and values notated as {@code (A...)} and {@code (a...)}.
6360      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6361      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6362      * init function is automatically a loop parameter {@code a}.)
6363      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6364      * These loop parameters act as loop-invariant values visible across the whole loop.
6365      * <p>
6366      * <em>Parameters visible everywhere:</em>
6367      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6368      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6369      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6370      * Most clause functions will not need all of this information, but they will be formally connected to it
6371      * as if by {@link #dropArguments}.
6372      * <a id="astar"></a>
6373      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6374      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6375      * In that notation, the general form of an init function parameter list
6376      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6377      * <p>
6378      * <em>Checking clause structure:</em>
6379      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6380      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6381      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6382      * met by the inputs to the loop combinator.
6383      * <p>
6384      * <em>Effectively identical sequences:</em>
6385      * <a id="effid"></a>
6386      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6387      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6388      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6389      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6390      * that longest list.
6391      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6392      * and the same is true if more sequences of the form {@code (V... A*)} are added.
6393      * <p>
6394      * <em>Step 0: Determine clause structure.</em><ol type="a">
6395      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6396      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6397      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6398      * four. Padding takes place by appending elements to the array.
6399      * <li>Clauses with all {@code null}s are disregarded.
6400      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6401      * </ol>
6402      * <p>
6403      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6404      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6405      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6406      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6407      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6408      * iteration variable type.
6409      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6410      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6411      * </ol>
6412      * <p>
6413      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6414      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6415      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6416      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6417      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6418      * (These types will be checked in step 2, along with all the clause function types.)
6419      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6420      * <li>All of the collected parameter lists must be effectively identical.
6421      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6422      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6423      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6424      * the "internal parameter list".
6425      * </ul>
6426      * <p>
6427      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6428      * <li>Examine fini function return types, disregarding omitted fini functions.
6429      * <li>If there are no fini functions, the loop return type is {@code void}.
6430      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6431      * type.
6432      * </ol>
6433      * <p>
6434      * <em>Step 1D: Check other types.</em><ol type="a">
6435      * <li>There must be at least one non-omitted pred function.
6436      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6437      * </ol>
6438      * <p>
6439      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6440      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6441      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6442      * (Note that their parameter lists are already effectively identical to this list.)
6443      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6444      * effectively identical to the internal parameter list {@code (V... A...)}.
6445      * </ol>
6446      * <p>
6447      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6448      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6449      * type.
6450      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6451      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6452      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6453      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6454      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6455      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6456      * loop return type.
6457      * </ol>
6458      * <p>
6459      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6460      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6461      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6462      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6463      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6464      * pad out the end of the list.
6465      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6466      * </ol>
6467      * <p>
6468      * <em>Final observations.</em><ol type="a">
6469      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6470      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6471      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6472      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6473      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6474      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6475      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6476      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6477      * </ol>
6478      * <p>
6479      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6480      * <ul>
6481      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6482      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6483      * (Only one {@code Pn} has to be non-{@code null}.)
6484      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6485      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6486      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6487      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6488      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6489      * the resulting loop handle's parameter types {@code (A...)}.
6490      * </ul>
6491      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6492      * which is natural if most of the loop computation happens in the steps.  For some loops,
6493      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6494      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6495      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6496      * where the init functions will need the extra parameters.  For such reasons, the rules for
6497      * determining these parameters are as symmetric as possible, across all clause parts.
6498      * In general, the loop parameters function as common invariant values across the whole
6499      * loop, while the iteration variables function as common variant values, or (if there is
6500      * no step function) as internal loop invariant temporaries.
6501      * <p>
6502      * <em>Loop execution.</em><ol type="a">
6503      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6504      * every clause function. These locals are loop invariant.
6505      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6506      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6507      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6508      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6509      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6510      * (in argument order).
6511      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6512      * returns {@code false}.
6513      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6514      * sequence {@code (v...)} of loop variables.
6515      * The updated value is immediately visible to all subsequent function calls.
6516      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6517      * (of type {@code R}) is returned from the loop as a whole.
6518      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6519      * except by throwing an exception.
6520      * </ol>
6521      * <p>
6522      * <em>Usage tips.</em>
6523      * <ul>
6524      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6525      * sometimes a step function only needs to observe the current value of its own variable.
6526      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6527      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6528      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6529      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6530      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6531      * <li>If some of the clause functions are virtual methods on an instance, the instance
6532      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6533      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6534      * will be the first iteration variable value, and it will be easy to use virtual
6535      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6536      * </ul>
6537      * <p>
6538      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6539      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6540      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6541      * <blockquote><pre>{@code
6542      * V... init...(A...);
6543      * boolean pred...(V..., A...);
6544      * V... step...(V..., A...);
6545      * R fini...(V..., A...);
6546      * R loop(A... a) {
6547      *   V... v... = init...(a...);
6548      *   for (;;) {
6549      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6550      *       v = s(v..., a...);
6551      *       if (!p(v..., a...)) {
6552      *         return f(v..., a...);
6553      *       }
6554      *     }
6555      *   }
6556      * }
6557      * }</pre></blockquote>
6558      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6559      * to their full length, even though individual clause functions may neglect to take them all.
6560      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6561      *
6562      * @apiNote Example:
6563      * <blockquote><pre>{@code
6564      * // iterative implementation of the factorial function as a loop handle
6565      * static int one(int k) { return 1; }
6566      * static int inc(int i, int acc, int k) { return i + 1; }
6567      * static int mult(int i, int acc, int k) { return i * acc; }
6568      * static boolean pred(int i, int acc, int k) { return i < k; }
6569      * static int fin(int i, int acc, int k) { return acc; }
6570      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6571      * // null initializer for counter, should initialize to 0
6572      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6573      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6574      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6575      * assertEquals(120, loop.invoke(5));
6576      * }</pre></blockquote>
6577      * The same example, dropping arguments and using combinators:
6578      * <blockquote><pre>{@code
6579      * // simplified implementation of the factorial function as a loop handle
6580      * static int inc(int i) { return i + 1; } // drop acc, k
6581      * static int mult(int i, int acc) { return i * acc; } //drop k
6582      * static boolean cmp(int i, int k) { return i < k; }
6583      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6584      * // null initializer for counter, should initialize to 0
6585      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6586      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6587      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6588      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6589      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6590      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6591      * assertEquals(720, loop.invoke(6));
6592      * }</pre></blockquote>
6593      * A similar example, using a helper object to hold a loop parameter:
6594      * <blockquote><pre>{@code
6595      * // instance-based implementation of the factorial function as a loop handle
6596      * static class FacLoop {
6597      *   final int k;
6598      *   FacLoop(int k) { this.k = k; }
6599      *   int inc(int i) { return i + 1; }
6600      *   int mult(int i, int acc) { return i * acc; }
6601      *   boolean pred(int i) { return i < k; }
6602      *   int fin(int i, int acc) { return acc; }
6603      * }
6604      * // assume MH_FacLoop is a handle to the constructor
6605      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6606      * // null initializer for counter, should initialize to 0
6607      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6608      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6609      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6610      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6611      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6612      * assertEquals(5040, loop.invoke(7));
6613      * }</pre></blockquote>
6614      *
6615      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6616      *
6617      * @return a method handle embodying the looping behavior as defined by the arguments.
6618      *
6619      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6620      *
6621      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6622      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6623      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6624      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6625      * @since 9
6626      */
6627     public static MethodHandle loop(MethodHandle[]... clauses) {
6628         // Step 0: determine clause structure.
6629         loopChecks0(clauses);
6630 
6631         List<MethodHandle> init = new ArrayList<>();
6632         List<MethodHandle> step = new ArrayList<>();
6633         List<MethodHandle> pred = new ArrayList<>();
6634         List<MethodHandle> fini = new ArrayList<>();
6635 
6636         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6637             init.add(clause[0]); // all clauses have at least length 1
6638             step.add(clause.length <= 1 ? null : clause[1]);
6639             pred.add(clause.length <= 2 ? null : clause[2]);
6640             fini.add(clause.length <= 3 ? null : clause[3]);
6641         });
6642 
6643         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6644         final int nclauses = init.size();
6645 
6646         // Step 1A: determine iteration variables (V...).
6647         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6648         for (int i = 0; i < nclauses; ++i) {
6649             MethodHandle in = init.get(i);
6650             MethodHandle st = step.get(i);
6651             if (in == null && st == null) {
6652                 iterationVariableTypes.add(void.class);
6653             } else if (in != null && st != null) {
6654                 loopChecks1a(i, in, st);
6655                 iterationVariableTypes.add(in.type().returnType());
6656             } else {
6657                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6658             }
6659         }
6660         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6661 
6662         // Step 1B: determine loop parameters (A...).
6663         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6664         loopChecks1b(init, commonSuffix);
6665 
6666         // Step 1C: determine loop return type.
6667         // Step 1D: check other types.
6668         // local variable required here; see JDK-8223553
6669         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6670                 .map(MethodType::returnType);
6671         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6672         loopChecks1cd(pred, fini, loopReturnType);
6673 
6674         // Step 2: determine parameter lists.
6675         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6676         commonParameterSequence.addAll(commonSuffix);
6677         loopChecks2(step, pred, fini, commonParameterSequence);
6678 
6679         // Step 3: fill in omitted functions.
6680         for (int i = 0; i < nclauses; ++i) {
6681             Class<?> t = iterationVariableTypes.get(i);
6682             if (init.get(i) == null) {
6683                 init.set(i, empty(methodType(t, commonSuffix)));
6684             }
6685             if (step.get(i) == null) {
6686                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6687             }
6688             if (pred.get(i) == null) {
6689                 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence));
6690             }
6691             if (fini.get(i) == null) {
6692                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6693             }
6694         }
6695 
6696         // Step 4: fill in missing parameter types.
6697         // Also convert all handles to fixed-arity handles.
6698         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6699         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6700         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6701         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6702 
6703         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6704                 allMatch(pl -> pl.equals(commonSuffix));
6705         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6706                 allMatch(pl -> pl.equals(commonParameterSequence));
6707 
6708         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6709     }
6710 
6711     private static void loopChecks0(MethodHandle[][] clauses) {
6712         if (clauses == null || clauses.length == 0) {
6713             throw newIllegalArgumentException("null or no clauses passed");
6714         }
6715         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6716             throw newIllegalArgumentException("null clauses are not allowed");
6717         }
6718         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6719             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6720         }
6721     }
6722 
6723     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6724         if (in.type().returnType() != st.type().returnType()) {
6725             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6726                     st.type().returnType());
6727         }
6728     }
6729 
6730     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6731         final List<Class<?>> empty = List.of();
6732         final List<Class<?>> longest = mhs.filter(Objects::nonNull).
6733                 // take only those that can contribute to a common suffix because they are longer than the prefix
6734                         map(MethodHandle::type).
6735                         filter(t -> t.parameterCount() > skipSize).
6736                         map(MethodType::parameterList).
6737                         reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6738         return longest.isEmpty() ? empty : longest.subList(skipSize, longest.size());
6739     }
6740 
6741     private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) {
6742         final List<Class<?>> empty = List.of();
6743         return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6744     }
6745 
6746     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6747         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6748         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6749         return longestParameterList(Arrays.asList(longest1, longest2));
6750     }
6751 
6752     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6753         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6754                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6755             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6756                     " (common suffix: " + commonSuffix + ")");
6757         }
6758     }
6759 
6760     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6761         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6762                 anyMatch(t -> t != loopReturnType)) {
6763             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6764                     loopReturnType + ")");
6765         }
6766 
6767         if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
6768             throw newIllegalArgumentException("no predicate found", pred);
6769         }
6770         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6771                 anyMatch(t -> t != boolean.class)) {
6772             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6773         }
6774     }
6775 
6776     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6777         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6778                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6779             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6780                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6781         }
6782     }
6783 
6784     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6785         return hs.stream().map(h -> {
6786             int pc = h.type().parameterCount();
6787             int tpsize = targetParams.size();
6788             return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h;
6789         }).toList();
6790     }
6791 
6792     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6793         return hs.stream().map(MethodHandle::asFixedArity).toList();
6794     }
6795 
6796     /**
6797      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6798      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6799      * <p>
6800      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6801      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6802      * evaluates to {@code true}).
6803      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6804      * <p>
6805      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6806      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6807      * and updated with the value returned from its invocation. The result of loop execution will be
6808      * the final value of the additional loop-local variable (if present).
6809      * <p>
6810      * The following rules hold for these argument handles:<ul>
6811      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6812      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6813      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6814      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6815      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6816      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6817      * It will constrain the parameter lists of the other loop parts.
6818      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6819      * list {@code (A...)} is called the <em>external parameter list</em>.
6820      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6821      * additional state variable of the loop.
6822      * The body must both accept and return a value of this type {@code V}.
6823      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6824      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6825      * <a href="MethodHandles.html#effid">effectively identical</a>
6826      * to the external parameter list {@code (A...)}.
6827      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6828      * {@linkplain #empty default value}.
6829      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6830      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6831      * effectively identical to the internal parameter list.
6832      * </ul>
6833      * <p>
6834      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6835      * <li>The loop handle's result type is the result type {@code V} of the body.
6836      * <li>The loop handle's parameter types are the types {@code (A...)},
6837      * from the external parameter list.
6838      * </ul>
6839      * <p>
6840      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6841      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6842      * passed to the loop.
6843      * <blockquote><pre>{@code
6844      * V init(A...);
6845      * boolean pred(V, A...);
6846      * V body(V, A...);
6847      * V whileLoop(A... a...) {
6848      *   V v = init(a...);
6849      *   while (pred(v, a...)) {
6850      *     v = body(v, a...);
6851      *   }
6852      *   return v;
6853      * }
6854      * }</pre></blockquote>
6855      *
6856      * @apiNote Example:
6857      * <blockquote><pre>{@code
6858      * // implement the zip function for lists as a loop handle
6859      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6860      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6861      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6862      *   zip.add(a.next());
6863      *   zip.add(b.next());
6864      *   return zip;
6865      * }
6866      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6867      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6868      * List<String> a = Arrays.asList("a", "b", "c", "d");
6869      * List<String> b = Arrays.asList("e", "f", "g", "h");
6870      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6871      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6872      * }</pre></blockquote>
6873      *
6874      *
6875      * @apiNote The implementation of this method can be expressed as follows:
6876      * <blockquote><pre>{@code
6877      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6878      *     MethodHandle fini = (body.type().returnType() == void.class
6879      *                         ? null : identity(body.type().returnType()));
6880      *     MethodHandle[]
6881      *         checkExit = { null, null, pred, fini },
6882      *         varBody   = { init, body };
6883      *     return loop(checkExit, varBody);
6884      * }
6885      * }</pre></blockquote>
6886      *
6887      * @param init optional initializer, providing the initial value of the loop variable.
6888      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6889      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6890      *             above for other constraints.
6891      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6892      *             See above for other constraints.
6893      *
6894      * @return a method handle implementing the {@code while} loop as described by the arguments.
6895      * @throws IllegalArgumentException if the rules for the arguments are violated.
6896      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6897      *
6898      * @see #loop(MethodHandle[][])
6899      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6900      * @since 9
6901      */
6902     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6903         whileLoopChecks(init, pred, body);
6904         MethodHandle fini = identityOrVoid(body.type().returnType());
6905         MethodHandle[] checkExit = { null, null, pred, fini };
6906         MethodHandle[] varBody = { init, body };
6907         return loop(checkExit, varBody);
6908     }
6909 
6910     /**
6911      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
6912      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6913      * <p>
6914      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6915      * method will, in each iteration, first execute its body and then evaluate the predicate.
6916      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
6917      * <p>
6918      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6919      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6920      * and updated with the value returned from its invocation. The result of loop execution will be
6921      * the final value of the additional loop-local variable (if present).
6922      * <p>
6923      * The following rules hold for these argument handles:<ul>
6924      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6925      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6926      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6927      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6928      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6929      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6930      * It will constrain the parameter lists of the other loop parts.
6931      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6932      * list {@code (A...)} is called the <em>external parameter list</em>.
6933      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6934      * additional state variable of the loop.
6935      * The body must both accept and return a value of this type {@code V}.
6936      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6937      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6938      * <a href="MethodHandles.html#effid">effectively identical</a>
6939      * to the external parameter list {@code (A...)}.
6940      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6941      * {@linkplain #empty default value}.
6942      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6943      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6944      * effectively identical to the internal parameter list.
6945      * </ul>
6946      * <p>
6947      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6948      * <li>The loop handle's result type is the result type {@code V} of the body.
6949      * <li>The loop handle's parameter types are the types {@code (A...)},
6950      * from the external parameter list.
6951      * </ul>
6952      * <p>
6953      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6954      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6955      * passed to the loop.
6956      * <blockquote><pre>{@code
6957      * V init(A...);
6958      * boolean pred(V, A...);
6959      * V body(V, A...);
6960      * V doWhileLoop(A... a...) {
6961      *   V v = init(a...);
6962      *   do {
6963      *     v = body(v, a...);
6964      *   } while (pred(v, a...));
6965      *   return v;
6966      * }
6967      * }</pre></blockquote>
6968      *
6969      * @apiNote Example:
6970      * <blockquote><pre>{@code
6971      * // int i = 0; while (i < limit) { ++i; } return i; => limit
6972      * static int zero(int limit) { return 0; }
6973      * static int step(int i, int limit) { return i + 1; }
6974      * static boolean pred(int i, int limit) { return i < limit; }
6975      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
6976      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
6977      * assertEquals(23, loop.invoke(23));
6978      * }</pre></blockquote>
6979      *
6980      *
6981      * @apiNote The implementation of this method can be expressed as follows:
6982      * <blockquote><pre>{@code
6983      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
6984      *     MethodHandle fini = (body.type().returnType() == void.class
6985      *                         ? null : identity(body.type().returnType()));
6986      *     MethodHandle[] clause = { init, body, pred, fini };
6987      *     return loop(clause);
6988      * }
6989      * }</pre></blockquote>
6990      *
6991      * @param init optional initializer, providing the initial value of the loop variable.
6992      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6993      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6994      *             See above for other constraints.
6995      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6996      *             above for other constraints.
6997      *
6998      * @return a method handle implementing the {@code while} loop as described by the arguments.
6999      * @throws IllegalArgumentException if the rules for the arguments are violated.
7000      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7001      *
7002      * @see #loop(MethodHandle[][])
7003      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
7004      * @since 9
7005      */
7006     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7007         whileLoopChecks(init, pred, body);
7008         MethodHandle fini = identityOrVoid(body.type().returnType());
7009         MethodHandle[] clause = {init, body, pred, fini };
7010         return loop(clause);
7011     }
7012 
7013     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
7014         Objects.requireNonNull(pred);
7015         Objects.requireNonNull(body);
7016         MethodType bodyType = body.type();
7017         Class<?> returnType = bodyType.returnType();
7018         List<Class<?>> innerList = bodyType.parameterList();
7019         List<Class<?>> outerList = innerList;
7020         if (returnType == void.class) {
7021             // OK
7022         } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
7023             // leading V argument missing => error
7024             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7025             throw misMatchedTypes("body function", bodyType, expected);
7026         } else {
7027             outerList = innerList.subList(1, innerList.size());
7028         }
7029         MethodType predType = pred.type();
7030         if (predType.returnType() != boolean.class ||
7031                 !predType.effectivelyIdenticalParameters(0, innerList)) {
7032             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
7033         }
7034         if (init != null) {
7035             MethodType initType = init.type();
7036             if (initType.returnType() != returnType ||
7037                     !initType.effectivelyIdenticalParameters(0, outerList)) {
7038                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7039             }
7040         }
7041     }
7042 
7043     /**
7044      * Constructs a loop that runs a given number of iterations.
7045      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7046      * <p>
7047      * The number of iterations is determined by the {@code iterations} handle evaluation result.
7048      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
7049      * It will be initialized to 0 and incremented by 1 in each iteration.
7050      * <p>
7051      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7052      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7053      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7054      * <p>
7055      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7056      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7057      * iteration variable.
7058      * The result of the loop handle execution will be the final {@code V} value of that variable
7059      * (or {@code void} if there is no {@code V} variable).
7060      * <p>
7061      * The following rules hold for the argument handles:<ul>
7062      * <li>The {@code iterations} handle must not be {@code null}, and must return
7063      * the type {@code int}, referred to here as {@code I} in parameter type lists.
7064      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7065      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7066      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7067      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7068      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7069      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7070      * of types called the <em>internal parameter list</em>.
7071      * It will constrain the parameter lists of the other loop parts.
7072      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7073      * with no additional {@code A} types, then the internal parameter list is extended by
7074      * the argument types {@code A...} of the {@code iterations} handle.
7075      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7076      * list {@code (A...)} is called the <em>external parameter list</em>.
7077      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7078      * additional state variable of the loop.
7079      * The body must both accept a leading parameter and return a value of this type {@code V}.
7080      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7081      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7082      * <a href="MethodHandles.html#effid">effectively identical</a>
7083      * to the external parameter list {@code (A...)}.
7084      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7085      * {@linkplain #empty default value}.
7086      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
7087      * effectively identical to the external parameter list {@code (A...)}.
7088      * </ul>
7089      * <p>
7090      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7091      * <li>The loop handle's result type is the result type {@code V} of the body.
7092      * <li>The loop handle's parameter types are the types {@code (A...)},
7093      * from the external parameter list.
7094      * </ul>
7095      * <p>
7096      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7097      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7098      * arguments passed to the loop.
7099      * <blockquote><pre>{@code
7100      * int iterations(A...);
7101      * V init(A...);
7102      * V body(V, int, A...);
7103      * V countedLoop(A... a...) {
7104      *   int end = iterations(a...);
7105      *   V v = init(a...);
7106      *   for (int i = 0; i < end; ++i) {
7107      *     v = body(v, i, a...);
7108      *   }
7109      *   return v;
7110      * }
7111      * }</pre></blockquote>
7112      *
7113      * @apiNote Example with a fully conformant body method:
7114      * <blockquote><pre>{@code
7115      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7116      * // => a variation on a well known theme
7117      * static String step(String v, int counter, String init) { return "na " + v; }
7118      * // assume MH_step is a handle to the method above
7119      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
7120      * MethodHandle start = MethodHandles.identity(String.class);
7121      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
7122      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
7123      * }</pre></blockquote>
7124      *
7125      * @apiNote Example with the simplest possible body method type,
7126      * and passing the number of iterations to the loop invocation:
7127      * <blockquote><pre>{@code
7128      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7129      * // => a variation on a well known theme
7130      * static String step(String v, int counter ) { return "na " + v; }
7131      * // assume MH_step is a handle to the method above
7132      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
7133      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
7134      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
7135      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
7136      * }</pre></blockquote>
7137      *
7138      * @apiNote Example that treats the number of iterations, string to append to, and string to append
7139      * as loop parameters:
7140      * <blockquote><pre>{@code
7141      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7142      * // => a variation on a well known theme
7143      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
7144      * // assume MH_step is a handle to the method above
7145      * MethodHandle count = MethodHandles.identity(int.class);
7146      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
7147      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
7148      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
7149      * }</pre></blockquote>
7150      *
7151      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
7152      * to enforce a loop type:
7153      * <blockquote><pre>{@code
7154      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7155      * // => a variation on a well known theme
7156      * static String step(String v, int counter, String pre) { return pre + " " + v; }
7157      * // assume MH_step is a handle to the method above
7158      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
7159      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
7160      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
7161      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
7162      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
7163      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
7164      * }</pre></blockquote>
7165      *
7166      * @apiNote The implementation of this method can be expressed as follows:
7167      * <blockquote><pre>{@code
7168      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7169      *     return countedLoop(empty(iterations.type()), iterations, init, body);
7170      * }
7171      * }</pre></blockquote>
7172      *
7173      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
7174      *                   result type must be {@code int}. See above for other constraints.
7175      * @param init optional initializer, providing the initial value of the loop variable.
7176      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7177      * @param body body of the loop, which may not be {@code null}.
7178      *             It controls the loop parameters and result type in the standard case (see above for details).
7179      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7180      *             and may accept any number of additional types.
7181      *             See above for other constraints.
7182      *
7183      * @return a method handle representing the loop.
7184      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7185      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7186      *
7187      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7188      * @since 9
7189      */
7190     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7191         return countedLoop(empty(iterations.type()), iterations, init, body);
7192     }
7193 
7194     /**
7195      * Constructs a loop that counts over a range of numbers.
7196      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7197      * <p>
7198      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7199      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7200      * values of the loop counter.
7201      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7202      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7203      * <p>
7204      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7205      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7206      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7207      * <p>
7208      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7209      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7210      * iteration variable.
7211      * The result of the loop handle execution will be the final {@code V} value of that variable
7212      * (or {@code void} if there is no {@code V} variable).
7213      * <p>
7214      * The following rules hold for the argument handles:<ul>
7215      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7216      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7217      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7218      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7219      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7220      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7221      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7222      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7223      * of types called the <em>internal parameter list</em>.
7224      * It will constrain the parameter lists of the other loop parts.
7225      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7226      * with no additional {@code A} types, then the internal parameter list is extended by
7227      * the argument types {@code A...} of the {@code end} handle.
7228      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7229      * list {@code (A...)} is called the <em>external parameter list</em>.
7230      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7231      * additional state variable of the loop.
7232      * The body must both accept a leading parameter and return a value of this type {@code V}.
7233      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7234      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7235      * <a href="MethodHandles.html#effid">effectively identical</a>
7236      * to the external parameter list {@code (A...)}.
7237      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7238      * {@linkplain #empty default value}.
7239      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7240      * effectively identical to the external parameter list {@code (A...)}.
7241      * <li>Likewise, the parameter list of {@code end} must be effectively identical
7242      * to the external parameter list.
7243      * </ul>
7244      * <p>
7245      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7246      * <li>The loop handle's result type is the result type {@code V} of the body.
7247      * <li>The loop handle's parameter types are the types {@code (A...)},
7248      * from the external parameter list.
7249      * </ul>
7250      * <p>
7251      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7252      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7253      * arguments passed to the loop.
7254      * <blockquote><pre>{@code
7255      * int start(A...);
7256      * int end(A...);
7257      * V init(A...);
7258      * V body(V, int, A...);
7259      * V countedLoop(A... a...) {
7260      *   int e = end(a...);
7261      *   int s = start(a...);
7262      *   V v = init(a...);
7263      *   for (int i = s; i < e; ++i) {
7264      *     v = body(v, i, a...);
7265      *   }
7266      *   return v;
7267      * }
7268      * }</pre></blockquote>
7269      *
7270      * @apiNote The implementation of this method can be expressed as follows:
7271      * <blockquote><pre>{@code
7272      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7273      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7274      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7275      *     // the following semantics:
7276      *     // MH_increment: (int limit, int counter) -> counter + 1
7277      *     // MH_predicate: (int limit, int counter) -> counter < limit
7278      *     Class<?> counterType = start.type().returnType();  // int
7279      *     Class<?> returnType = body.type().returnType();
7280      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7281      *     if (returnType != void.class) {  // ignore the V variable
7282      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7283      *         pred = dropArguments(pred, 1, returnType);  // ditto
7284      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7285      *     }
7286      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
7287      *     MethodHandle[]
7288      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7289      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
7290      *         indexVar   = { start, incr };           // i = start(); i = i + 1
7291      *     return loop(loopLimit, bodyClause, indexVar);
7292      * }
7293      * }</pre></blockquote>
7294      *
7295      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7296      *              See above for other constraints.
7297      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7298      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
7299      * @param init optional initializer, providing the initial value of the loop variable.
7300      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7301      * @param body body of the loop, which may not be {@code null}.
7302      *             It controls the loop parameters and result type in the standard case (see above for details).
7303      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7304      *             and may accept any number of additional types.
7305      *             See above for other constraints.
7306      *
7307      * @return a method handle representing the loop.
7308      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7309      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7310      *
7311      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7312      * @since 9
7313      */
7314     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7315         countedLoopChecks(start, end, init, body);
7316         Class<?> counterType = start.type().returnType();  // int, but who's counting?
7317         Class<?> limitType   = end.type().returnType();    // yes, int again
7318         Class<?> returnType  = body.type().returnType();
7319         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7320         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7321         MethodHandle retv = null;
7322         if (returnType != void.class) {
7323             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7324             pred = dropArguments(pred, 1, returnType);  // ditto
7325             retv = dropArguments(identity(returnType), 0, counterType);
7326         }
7327         body = dropArguments(body, 0, counterType);  // ignore the limit variable
7328         MethodHandle[]
7329             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7330             bodyClause = { init, body },            // v = init(); v = body(v, i)
7331             indexVar   = { start, incr };           // i = start(); i = i + 1
7332         return loop(loopLimit, bodyClause, indexVar);
7333     }
7334 
7335     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7336         Objects.requireNonNull(start);
7337         Objects.requireNonNull(end);
7338         Objects.requireNonNull(body);
7339         Class<?> counterType = start.type().returnType();
7340         if (counterType != int.class) {
7341             MethodType expected = start.type().changeReturnType(int.class);
7342             throw misMatchedTypes("start function", start.type(), expected);
7343         } else if (end.type().returnType() != counterType) {
7344             MethodType expected = end.type().changeReturnType(counterType);
7345             throw misMatchedTypes("end function", end.type(), expected);
7346         }
7347         MethodType bodyType = body.type();
7348         Class<?> returnType = bodyType.returnType();
7349         List<Class<?>> innerList = bodyType.parameterList();
7350         // strip leading V value if present
7351         int vsize = (returnType == void.class ? 0 : 1);
7352         if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7353             // argument list has no "V" => error
7354             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7355             throw misMatchedTypes("body function", bodyType, expected);
7356         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7357             // missing I type => error
7358             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7359             throw misMatchedTypes("body function", bodyType, expected);
7360         }
7361         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7362         if (outerList.isEmpty()) {
7363             // special case; take lists from end handle
7364             outerList = end.type().parameterList();
7365             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7366         }
7367         MethodType expected = methodType(counterType, outerList);
7368         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7369             throw misMatchedTypes("start parameter types", start.type(), expected);
7370         }
7371         if (end.type() != start.type() &&
7372             !end.type().effectivelyIdenticalParameters(0, outerList)) {
7373             throw misMatchedTypes("end parameter types", end.type(), expected);
7374         }
7375         if (init != null) {
7376             MethodType initType = init.type();
7377             if (initType.returnType() != returnType ||
7378                 !initType.effectivelyIdenticalParameters(0, outerList)) {
7379                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7380             }
7381         }
7382     }
7383 
7384     /**
7385      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7386      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7387      * <p>
7388      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7389      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7390      * <p>
7391      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7392      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7393      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7394      * <p>
7395      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7396      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7397      * iteration variable.
7398      * The result of the loop handle execution will be the final {@code V} value of that variable
7399      * (or {@code void} if there is no {@code V} variable).
7400      * <p>
7401      * The following rules hold for the argument handles:<ul>
7402      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7403      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7404      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7405      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7406      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7407      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7408      * of types called the <em>internal parameter list</em>.
7409      * It will constrain the parameter lists of the other loop parts.
7410      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7411      * with no additional {@code A} types, then the internal parameter list is extended by
7412      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7413      * single type {@code Iterable} is added and constitutes the {@code A...} list.
7414      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7415      * list {@code (A...)} is called the <em>external parameter list</em>.
7416      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7417      * additional state variable of the loop.
7418      * The body must both accept a leading parameter and return a value of this type {@code V}.
7419      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7420      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7421      * <a href="MethodHandles.html#effid">effectively identical</a>
7422      * to the external parameter list {@code (A...)}.
7423      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7424      * {@linkplain #empty default value}.
7425      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7426      * type {@code java.util.Iterator} or a subtype thereof.
7427      * The iterator it produces when the loop is executed will be assumed
7428      * to yield values which can be converted to type {@code T}.
7429      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7430      * effectively identical to the external parameter list {@code (A...)}.
7431      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7432      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7433      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7434      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7435      * the {@link MethodHandle#asType asType} conversion method.
7436      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7437      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7438      * </ul>
7439      * <p>
7440      * The type {@code T} may be either a primitive or reference.
7441      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7442      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7443      * as if by the {@link MethodHandle#asType asType} conversion method.
7444      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7445      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7446      * <p>
7447      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7448      * <li>The loop handle's result type is the result type {@code V} of the body.
7449      * <li>The loop handle's parameter types are the types {@code (A...)},
7450      * from the external parameter list.
7451      * </ul>
7452      * <p>
7453      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7454      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7455      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7456      * <blockquote><pre>{@code
7457      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7458      * V init(A...);
7459      * V body(V,T,A...);
7460      * V iteratedLoop(A... a...) {
7461      *   Iterator<T> it = iterator(a...);
7462      *   V v = init(a...);
7463      *   while (it.hasNext()) {
7464      *     T t = it.next();
7465      *     v = body(v, t, a...);
7466      *   }
7467      *   return v;
7468      * }
7469      * }</pre></blockquote>
7470      *
7471      * @apiNote Example:
7472      * <blockquote><pre>{@code
7473      * // get an iterator from a list
7474      * static List<String> reverseStep(List<String> r, String e) {
7475      *   r.add(0, e);
7476      *   return r;
7477      * }
7478      * static List<String> newArrayList() { return new ArrayList<>(); }
7479      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7480      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7481      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7482      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7483      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7484      * }</pre></blockquote>
7485      *
7486      * @apiNote The implementation of this method can be expressed approximately as follows:
7487      * <blockquote><pre>{@code
7488      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7489      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7490      *     Class<?> returnType = body.type().returnType();
7491      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7492      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7493      *     MethodHandle retv = null, step = body, startIter = iterator;
7494      *     if (returnType != void.class) {
7495      *         // the simple thing first:  in (I V A...), drop the I to get V
7496      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7497      *         // body type signature (V T A...), internal loop types (I V A...)
7498      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7499      *     }
7500      *     if (startIter == null)  startIter = MH_getIter;
7501      *     MethodHandle[]
7502      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7503      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7504      *     return loop(iterVar, bodyClause);
7505      * }
7506      * }</pre></blockquote>
7507      *
7508      * @param iterator an optional handle to return the iterator to start the loop.
7509      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7510      *                 See above for other constraints.
7511      * @param init optional initializer, providing the initial value of the loop variable.
7512      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7513      * @param body body of the loop, which may not be {@code null}.
7514      *             It controls the loop parameters and result type in the standard case (see above for details).
7515      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7516      *             and may accept any number of additional types.
7517      *             See above for other constraints.
7518      *
7519      * @return a method handle embodying the iteration loop functionality.
7520      * @throws NullPointerException if the {@code body} handle is {@code null}.
7521      * @throws IllegalArgumentException if any argument violates the above requirements.
7522      *
7523      * @since 9
7524      */
7525     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7526         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7527         Class<?> returnType = body.type().returnType();
7528         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7529         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7530         MethodHandle startIter;
7531         MethodHandle nextVal;
7532         {
7533             MethodType iteratorType;
7534             if (iterator == null) {
7535                 // derive argument type from body, if available, else use Iterable
7536                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7537                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7538             } else {
7539                 // force return type to the internal iterator class
7540                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7541                 startIter = iterator;
7542             }
7543             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7544             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7545 
7546             // perform the asType transforms under an exception transformer, as per spec.:
7547             try {
7548                 startIter = startIter.asType(iteratorType);
7549                 nextVal = nextRaw.asType(nextValType);
7550             } catch (WrongMethodTypeException ex) {
7551                 throw new IllegalArgumentException(ex);
7552             }
7553         }
7554 
7555         MethodHandle retv = null, step = body;
7556         if (returnType != void.class) {
7557             // the simple thing first:  in (I V A...), drop the I to get V
7558             retv = dropArguments(identity(returnType), 0, Iterator.class);
7559             // body type signature (V T A...), internal loop types (I V A...)
7560             step = swapArguments(body, 0, 1);  // swap V <-> T
7561         }
7562 
7563         MethodHandle[]
7564             iterVar    = { startIter, null, hasNext, retv },
7565             bodyClause = { init, filterArgument(step, 0, nextVal) };
7566         return loop(iterVar, bodyClause);
7567     }
7568 
7569     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7570         Objects.requireNonNull(body);
7571         MethodType bodyType = body.type();
7572         Class<?> returnType = bodyType.returnType();
7573         List<Class<?>> internalParamList = bodyType.parameterList();
7574         // strip leading V value if present
7575         int vsize = (returnType == void.class ? 0 : 1);
7576         if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7577             // argument list has no "V" => error
7578             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7579             throw misMatchedTypes("body function", bodyType, expected);
7580         } else if (internalParamList.size() <= vsize) {
7581             // missing T type => error
7582             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7583             throw misMatchedTypes("body function", bodyType, expected);
7584         }
7585         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7586         Class<?> iterableType = null;
7587         if (iterator != null) {
7588             // special case; if the body handle only declares V and T then
7589             // the external parameter list is obtained from iterator handle
7590             if (externalParamList.isEmpty()) {
7591                 externalParamList = iterator.type().parameterList();
7592             }
7593             MethodType itype = iterator.type();
7594             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7595                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7596             }
7597             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7598                 MethodType expected = methodType(itype.returnType(), externalParamList);
7599                 throw misMatchedTypes("iterator parameters", itype, expected);
7600             }
7601         } else {
7602             if (externalParamList.isEmpty()) {
7603                 // special case; if the iterator handle is null and the body handle
7604                 // only declares V and T then the external parameter list consists
7605                 // of Iterable
7606                 externalParamList = Arrays.asList(Iterable.class);
7607                 iterableType = Iterable.class;
7608             } else {
7609                 // special case; if the iterator handle is null and the external
7610                 // parameter list is not empty then the first parameter must be
7611                 // assignable to Iterable
7612                 iterableType = externalParamList.get(0);
7613                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7614                     throw newIllegalArgumentException(
7615                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7616                 }
7617             }
7618         }
7619         if (init != null) {
7620             MethodType initType = init.type();
7621             if (initType.returnType() != returnType ||
7622                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7623                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7624             }
7625         }
7626         return iterableType;  // help the caller a bit
7627     }
7628 
7629     /*non-public*/
7630     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7631         // there should be a better way to uncross my wires
7632         int arity = mh.type().parameterCount();
7633         int[] order = new int[arity];
7634         for (int k = 0; k < arity; k++)  order[k] = k;
7635         order[i] = j; order[j] = i;
7636         Class<?>[] types = mh.type().parameterArray();
7637         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7638         MethodType swapType = methodType(mh.type().returnType(), types);
7639         return permuteArguments(mh, swapType, order);
7640     }
7641 
7642     /**
7643      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7644      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7645      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7646      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7647      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7648      * {@code try-finally} handle.
7649      * <p>
7650      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7651      * The first is the exception thrown during the
7652      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7653      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7654      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7655      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7656      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7657      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7658      * <p>
7659      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7660      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7661      * two extra leading parameters:<ul>
7662      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7663      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7664      * the result from the execution of the {@code target} handle.
7665      * This parameter is not present if the {@code target} returns {@code void}.
7666      * </ul>
7667      * <p>
7668      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7669      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7670      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7671      * the cleanup.
7672      * <blockquote><pre>{@code
7673      * V target(A..., B...);
7674      * V cleanup(Throwable, V, A...);
7675      * V adapter(A... a, B... b) {
7676      *   V result = (zero value for V);
7677      *   Throwable throwable = null;
7678      *   try {
7679      *     result = target(a..., b...);
7680      *   } catch (Throwable t) {
7681      *     throwable = t;
7682      *     throw t;
7683      *   } finally {
7684      *     result = cleanup(throwable, result, a...);
7685      *   }
7686      *   return result;
7687      * }
7688      * }</pre></blockquote>
7689      * <p>
7690      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7691      * be modified by execution of the target, and so are passed unchanged
7692      * from the caller to the cleanup, if it is invoked.
7693      * <p>
7694      * The target and cleanup must return the same type, even if the cleanup
7695      * always throws.
7696      * To create such a throwing cleanup, compose the cleanup logic
7697      * with {@link #throwException throwException},
7698      * in order to create a method handle of the correct return type.
7699      * <p>
7700      * Note that {@code tryFinally} never converts exceptions into normal returns.
7701      * In rare cases where exceptions must be converted in that way, first wrap
7702      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7703      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7704      * <p>
7705      * It is recommended that the first parameter type of {@code cleanup} be
7706      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7707      * {@code cleanup} will always be invoked with whatever exception that
7708      * {@code target} throws.  Declaring a narrower type may result in a
7709      * {@code ClassCastException} being thrown by the {@code try-finally}
7710      * handle if the type of the exception thrown by {@code target} is not
7711      * assignable to the first parameter type of {@code cleanup}.  Note that
7712      * various exception types of {@code VirtualMachineError},
7713      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7714      * thrown by almost any kind of Java code, and a finally clause that
7715      * catches (say) only {@code IOException} would mask any of the others
7716      * behind a {@code ClassCastException}.
7717      *
7718      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7719      * @param cleanup the handle that is invoked in the finally block.
7720      *
7721      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7722      * @throws NullPointerException if any argument is null
7723      * @throws IllegalArgumentException if {@code cleanup} does not accept
7724      *          the required leading arguments, or if the method handle types do
7725      *          not match in their return types and their
7726      *          corresponding trailing parameters
7727      *
7728      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7729      * @since 9
7730      */
7731     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7732         List<Class<?>> targetParamTypes = target.type().parameterList();
7733         Class<?> rtype = target.type().returnType();
7734 
7735         tryFinallyChecks(target, cleanup);
7736 
7737         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7738         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7739         // target parameter list.
7740         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
7741 
7742         // Ensure that the intrinsic type checks the instance thrown by the
7743         // target against the first parameter of cleanup
7744         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7745 
7746         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7747         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7748     }
7749 
7750     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7751         Class<?> rtype = target.type().returnType();
7752         if (rtype != cleanup.type().returnType()) {
7753             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7754         }
7755         MethodType cleanupType = cleanup.type();
7756         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7757             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7758         }
7759         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7760             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7761         }
7762         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7763         // target parameter list.
7764         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7765         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7766             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7767                     cleanup.type(), target.type());
7768         }
7769     }
7770 
7771     /**
7772      * Creates a table switch method handle, which can be used to switch over a set of target
7773      * method handles, based on a given target index, called selector.
7774      * <p>
7775      * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7776      * and where {@code N} is the number of target method handles, the table switch method
7777      * handle will invoke the n-th target method handle from the list of target method handles.
7778      * <p>
7779      * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7780      * method handle will invoke the given fallback method handle.
7781      * <p>
7782      * All method handles passed to this method must have the same type, with the additional
7783      * requirement that the leading parameter be of type {@code int}. The leading parameter
7784      * represents the selector.
7785      * <p>
7786      * Any trailing parameters present in the type will appear on the returned table switch
7787      * method handle as well. Any arguments assigned to these parameters will be forwarded,
7788      * together with the selector value, to the selected method handle when invoking it.
7789      *
7790      * @apiNote Example:
7791      * The cases each drop the {@code selector} value they are given, and take an additional
7792      * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7793      * to a specific constant label string for each case:
7794      * <blockquote><pre>{@code
7795      * MethodHandles.Lookup lookup = MethodHandles.lookup();
7796      * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7797      *         MethodType.methodType(String.class, String.class));
7798      * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7799      *
7800      * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7801      * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7802      * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7803      *
7804      * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7805      *     caseDefault,
7806      *     case0,
7807      *     case1
7808      * );
7809      *
7810      * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7811      * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7812      * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7813      * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7814      * }</pre></blockquote>
7815      *
7816      * @param fallback the fallback method handle that is called when the selector is not
7817      *                 within the range {@code [0, N)}.
7818      * @param targets array of target method handles.
7819      * @return the table switch method handle.
7820      * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7821      *                              any of the elements of the {@code targets} array are
7822      *                              {@code null}.
7823      * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7824      *                                  parameter of the fallback handle or any of the target
7825      *                                  handles is not {@code int}, or if the types of
7826      *                                  the fallback handle and all of target handles are
7827      *                                  not the same.
7828      */
7829     public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7830         Objects.requireNonNull(fallback);
7831         Objects.requireNonNull(targets);
7832         targets = targets.clone();
7833         MethodType type = tableSwitchChecks(fallback, targets);
7834         return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7835     }
7836 
7837     private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7838         if (caseActions.length == 0)
7839             throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7840 
7841         MethodType expectedType = defaultCase.type();
7842 
7843         if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7844             throw new IllegalArgumentException(
7845                 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7846 
7847         for (MethodHandle mh : caseActions) {
7848             Objects.requireNonNull(mh);
7849             if (mh.type() != expectedType)
7850                 throw new IllegalArgumentException(
7851                     "Case actions must have the same type: " + Arrays.toString(caseActions));
7852         }
7853 
7854         return expectedType;
7855     }
7856 
7857 }