rev 58768 : 8238358: Implementation of JEP 371: Hidden Classes
Reviewed-by: alanb, cjplummer, coleenp, dholmes, dlong, forax, jlahoda, psandoz, plevart, vromero
Contributed-by: mandy.chung@oracle.com, lois.foltan@oracle.com, david.holmes@oracle.com, harold.seigel@oracle.com, serguei.spitsyn@oracle.com, alex.buckley@oracle.com, jamsheed.c.m@oracle.com, jan.lahoda@oracle.com, amy.lu@oracle.com
rev 58769 : [mq]: type-descriptor-name

   1 /*
   2  * Copyright (c) 2008, 2020, 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.JavaLangAccess;
  29 import jdk.internal.access.SharedSecrets;
  30 import jdk.internal.misc.VM;
  31 import jdk.internal.module.IllegalAccessLogger;
  32 import jdk.internal.org.objectweb.asm.ClassReader;
  33 import jdk.internal.org.objectweb.asm.Opcodes;
  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.invoke.LambdaForm.BasicType;
  44 import java.lang.reflect.Constructor;
  45 import java.lang.reflect.Field;
  46 import java.lang.reflect.Member;
  47 import java.lang.reflect.Method;
  48 import java.lang.reflect.Modifier;
  49 import java.lang.reflect.ReflectPermission;
  50 import java.nio.ByteOrder;
  51 import java.security.ProtectionDomain;
  52 import java.util.ArrayList;
  53 import java.util.Arrays;
  54 import java.util.BitSet;
  55 import java.util.Iterator;
  56 import java.util.List;
  57 import java.util.Objects;
  58 import java.util.Set;
  59 import java.util.concurrent.ConcurrentHashMap;
  60 import java.util.stream.Collectors;
  61 import java.util.stream.Stream;
  62 
  63 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  64 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  65 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  66 import static java.lang.invoke.MethodType.methodType;
  67 
  68 /**
  69  * This class consists exclusively of static methods that operate on or return
  70  * method handles. They fall into several categories:
  71  * <ul>
  72  * <li>Lookup methods which help create method handles for methods and fields.
  73  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  74  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  75  * </ul>
  76  * A lookup, combinator, or factory method will fail and throw an
  77  * {@code IllegalArgumentException} if the created method handle's type
  78  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  79  *
  80  * @author John Rose, JSR 292 EG
  81  * @since 1.7
  82  */
  83 public class MethodHandles {
  84 
  85     private MethodHandles() { }  // do not instantiate
  86 
  87     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  88 
  89     // See IMPL_LOOKUP below.
  90 
  91     //// Method handle creation from ordinary methods.
  92 
  93     /**
  94      * Returns a {@link Lookup lookup object} with
  95      * full capabilities to emulate all supported bytecode behaviors of the caller.
  96      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
  97      * Factory methods on the lookup object can create
  98      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
  99      * for any member that the caller has access to via bytecodes,
 100      * including protected and private fields and methods.
 101      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 102      * Do not store it in place where untrusted code can access it.
 103      * <p>
 104      * This method is caller sensitive, which means that it may return different
 105      * values to different callers.
 106      * @return a lookup object for the caller of this method, with
 107      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 108      */
 109     @CallerSensitive
 110     @ForceInline // to ensure Reflection.getCallerClass optimization
 111     public static Lookup lookup() {
 112         return new Lookup(Reflection.getCallerClass());
 113     }
 114 
 115     /**
 116      * This reflected$lookup method is the alternate implementation of
 117      * the lookup method when being invoked by reflection.
 118      */
 119     @CallerSensitive
 120     private static Lookup reflected$lookup() {
 121         Class<?> caller = Reflection.getCallerClass();
 122         if (caller.getClassLoader() == null) {
 123             throw newIllegalArgumentException("illegal lookupClass: "+caller);
 124         }
 125         return new Lookup(caller);
 126     }
 127 
 128     /**
 129      * Returns a {@link Lookup lookup object} which is trusted minimally.
 130      * The lookup has the {@code UNCONDITIONAL} mode.
 131      * It can only be used to create method handles to public members of
 132      * public classes in packages that are exported unconditionally.
 133      * <p>
 134      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 135      * of this lookup object will be {@link java.lang.Object}.
 136      *
 137      * @apiNote The use of Object is conventional, and because the lookup modes are
 138      * limited, there is no special access provided to the internals of Object, its package
 139      * or its module.  This public lookup object or other lookup object with
 140      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 141      * is not used to determine the lookup context.
 142      *
 143      * <p style="font-size:smaller;">
 144      * <em>Discussion:</em>
 145      * The lookup class can be changed to any other class {@code C} using an expression of the form
 146      * {@link Lookup#in publicLookup().in(C.class)}.
 147      * A public lookup object is always subject to
 148      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 149      * Also, it cannot access
 150      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 151      * @return a lookup object which is trusted minimally
 152      *
 153      * @revised 9
 154      * @spec JPMS
 155      */
 156     public static Lookup publicLookup() {
 157         return Lookup.PUBLIC_LOOKUP;
 158     }
 159 
 160     /**
 161      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 162      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 163      * The returned lookup object can provide access to classes in modules and packages,
 164      * and members of those classes, outside the normal rules of Java access control,
 165      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 166      * <p>
 167      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 168      * allowed to do deep reflection on module {@code M2} and package of the target class
 169      * if and only if all of the following conditions are {@code true}:
 170      * <ul>
 171      * <li>If there is a security manager, its {@code checkPermission} method is
 172      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 173      * that must return normally.
 174      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 175      * full privilege access}.  Specifically:
 176      *   <ul>
 177      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 178      *         (This is because otherwise there would be no way to ensure the original lookup
 179      *         creator was a member of any particular module, and so any subsequent checks
 180      *         for readability and qualified exports would become ineffective.)
 181      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 182      *         (This is because an application intending to share intra-module access
 183      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 184      *         deep reflection to its own module.)
 185      *   </ul>
 186      * <li>The target class must be a proper class, not a primitive or array class.
 187      * (Thus, {@code M2} is well-defined.)
 188      * <li>If the caller module {@code M1} differs from
 189      * the target module {@code M2} then both of the following must be true:
 190      *   <ul>
 191      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 192      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 193      *         containing the target class to at least {@code M1}.</li>
 194      *   </ul>
 195      * </ul>
 196      * <p>
 197      * If any of the above checks is violated, this method fails with an
 198      * exception.
 199      * <p>
 200      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 201      * returns a {@code Lookup} on {@code targetClass} with
 202      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} and
 203      * {@code null} previous lookup class.
 204      * <p>
 205      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 206      * returns a {@code Lookup} on {@code targetClass} that records
 207      * the lookup class of the caller as the new previous lookup class and
 208      * drops {@code MODULE} access from the full privilege access.
 209      *
 210      * @param targetClass the target class
 211      * @param caller the caller lookup object
 212      * @return a lookup object for the target class, with private access
 213      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 214      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 215      * @throws SecurityException if denied by the security manager
 216      * @throws IllegalAccessException if any of the other access checks specified above fails
 217      * @since 9
 218      * @spec JPMS
 219      * @see Lookup#dropLookupMode
 220      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 221      */
 222     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 223         if (caller.allowedModes == Lookup.TRUSTED) {
 224             return new Lookup(targetClass);
 225         }
 226 
 227         SecurityManager sm = System.getSecurityManager();
 228         if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
 229         if (targetClass.isPrimitive())
 230             throw new IllegalArgumentException(targetClass + " is a primitive class");
 231         if (targetClass.isArray())
 232             throw new IllegalArgumentException(targetClass + " is an array class");
 233         // Ensure that we can reason accurately about private and module access.
 234         if (!caller.hasFullPrivilegeAccess())
 235             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 236 
 237         // previous lookup class is never set if it has MODULE access
 238         assert caller.previousLookupClass() == null;
 239 
 240         Class<?> callerClass = caller.lookupClass();
 241         Module callerModule = callerClass.getModule();  // M1
 242         Module targetModule = targetClass.getModule();  // M2
 243         Class<?> newPreviousClass = null;
 244         int newModes = Lookup.FULL_POWER_MODES;
 245 
 246         if (targetModule != callerModule) {
 247             if (!callerModule.canRead(targetModule))
 248                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 249             if (targetModule.isNamed()) {
 250                 String pn = targetClass.getPackageName();
 251                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 252                 if (!targetModule.isOpen(pn, callerModule))
 253                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 254             }
 255 
 256             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 257             newPreviousClass = callerClass;
 258             newModes &= ~Lookup.MODULE;
 259         }
 260 
 261         if (!callerModule.isNamed() && targetModule.isNamed()) {
 262             IllegalAccessLogger logger = IllegalAccessLogger.illegalAccessLogger();
 263             if (logger != null) {
 264                 logger.logIfOpenedForIllegalAccess(caller, targetClass);
 265             }
 266         }
 267         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 268     }
 269 
 270     /**
 271      * Returns the <em>class data</em> associated with the lookup class
 272      * of the specified {@code Lookup} object, or {@code null}.
 273      *
 274      * <p> Classes can be created with class data by calling
 275      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, Lookup.ClassOption...)
 276      * Lookup::defineHiddenClassWithClassData}.
 277      * A hidden class with a class data behaves as if the hidden class
 278      * has a private static final unnamed field pre-initialized with
 279      * the class data and this method is equivalent as if calling
 280      * {@link ConstantBootstraps#getStaticFinal(Lookup, String, Class)} to
 281      * obtain the value of such field corresponding to the class data.
 282      *
 283      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 284      * must have {@link Lookup#ORIGINAL ORIGINAL} access in order to retrieve
 285      * the class data.
 286      *
 287      * @apiNote
 288      * This method can be called as a bootstrap method for a dynamically computed
 289      * constant.  A framework can create a hidden class with class data, for
 290      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 291      * one live object.  The class data is accessible only to the lookup object
 292      * created by the original caller but inaccessible to other members
 293      * in the same nest.  If a framework passes security sensitive live objects
 294      * to a hidden class via class data, it is recommended to load the value
 295      * of class data as a dynamically computed constant instead of storing
 296      * the live objects in private fields which are accessible to other
 297      * nestmates.
 298      *
 299      * @param <T> the type to cast the class data object to
 300      * @param caller the lookup context describing the class performing the
 301      * operation (normally stacked by the JVM)
 302      * @param name ignored
 303      * @param type the type of the class data
 304      * @return the value of the class data if present in the lookup class;
 305      * otherwise {@code null}
 306      * @throws IllegalAccessException if the lookup context does not have
 307      * original caller access
 308      * @throws ClassCastException if the class data cannot be converted to
 309      * the specified {@code type}
 310      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, Lookup.ClassOption...)
 311      * @since 15
 312      */
 313     static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 314         if (!caller.hasFullPrivilegeAccess()) {
 315             throw new IllegalAccessException(caller + " does not have full privilege access");
 316         }
 317         Object classData = MethodHandleNatives.classData(caller.lookupClass);
 318         return type.cast(classData);
 319     }
 320 
 321     /**
 322      * Performs an unchecked "crack" of a
 323      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 324      * The result is as if the user had obtained a lookup object capable enough
 325      * to crack the target method handle, called
 326      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 327      * on the target to obtain its symbolic reference, and then called
 328      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 329      * to resolve the symbolic reference to a member.
 330      * <p>
 331      * If there is a security manager, its {@code checkPermission} method
 332      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 333      * @param <T> the desired type of the result, either {@link Member} or a subtype
 334      * @param target a direct method handle to crack into symbolic reference components
 335      * @param expected a class object representing the desired result type {@code T}
 336      * @return a reference to the method, constructor, or field object
 337      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 338      * @throws    NullPointerException if either argument is {@code null}
 339      * @throws    IllegalArgumentException if the target is not a direct method handle
 340      * @throws    ClassCastException if the member is not of the expected type
 341      * @since 1.8
 342      */
 343     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 344         SecurityManager smgr = System.getSecurityManager();
 345         if (smgr != null)  smgr.checkPermission(ACCESS_PERMISSION);
 346         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 347         return lookup.revealDirect(target).reflectAs(expected, lookup);
 348     }
 349     // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
 350     private static final java.security.Permission ACCESS_PERMISSION =
 351         new ReflectPermission("suppressAccessChecks");
 352 
 353     /**
 354      * A <em>lookup object</em> is a factory for creating method handles,
 355      * when the creation requires access checking.
 356      * Method handles do not perform
 357      * access checks when they are called, but rather when they are created.
 358      * Therefore, method handle access
 359      * restrictions must be enforced when a method handle is created.
 360      * The caller class against which those restrictions are enforced
 361      * is known as the {@linkplain #lookupClass() lookup class}.
 362      * <p>
 363      * A lookup class which needs to create method handles will call
 364      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 365      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 366      * determined, and securely stored in the {@code Lookup} object.
 367      * The lookup class (or its delegates) may then use factory methods
 368      * on the {@code Lookup} object to create method handles for access-checked members.
 369      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 370      * even private ones.
 371      *
 372      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 373      * The factory methods on a {@code Lookup} object correspond to all major
 374      * use cases for methods, constructors, and fields.
 375      * Each method handle created by a factory method is the functional
 376      * equivalent of a particular <em>bytecode behavior</em>.
 377      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 378      * the Java Virtual Machine Specification.)
 379      * Here is a summary of the correspondence between these factory methods and
 380      * the behavior of the resulting method handles:
 381      * <table class="striped">
 382      * <caption style="display:none">lookup method behaviors</caption>
 383      * <thead>
 384      * <tr>
 385      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 386      *     <th scope="col">member</th>
 387      *     <th scope="col">bytecode behavior</th>
 388      * </tr>
 389      * </thead>
 390      * <tbody>
 391      * <tr>
 392      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 393      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 394      * </tr>
 395      * <tr>
 396      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 397      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 398      * </tr>
 399      * <tr>
 400      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 401      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 402      * </tr>
 403      * <tr>
 404      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 405      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 406      * </tr>
 407      * <tr>
 408      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 409      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 410      * </tr>
 411      * <tr>
 412      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 413      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 414      * </tr>
 415      * <tr>
 416      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 417      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 418      * </tr>
 419      * <tr>
 420      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 421      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 422      * </tr>
 423      * <tr>
 424      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 425      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 426      * </tr>
 427      * <tr>
 428      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 429      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 430      * </tr>
 431      * <tr>
 432      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 433      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 434      * </tr>
 435      * <tr>
 436      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 437      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 438      * </tr>
 439      * <tr>
 440      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 441      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 442      * </tr>
 443      * <tr>
 444      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 445      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 446      * </tr>
 447      * </tbody>
 448      * </table>
 449      *
 450      * Here, the type {@code C} is the class or interface being searched for a member,
 451      * documented as a parameter named {@code refc} in the lookup methods.
 452      * The method type {@code MT} is composed from the return type {@code T}
 453      * and the sequence of argument types {@code A*}.
 454      * The constructor also has a sequence of argument types {@code A*} and
 455      * is deemed to return the newly-created object of type {@code C}.
 456      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 457      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 458      * if it is present, it is always the leading argument to the method handle invocation.
 459      * (In the case of some {@code protected} members, {@code this} may be
 460      * restricted in type to the lookup class; see below.)
 461      * The name {@code arg} stands for all the other method handle arguments.
 462      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 463      * stands for a null reference if the accessed method or field is static,
 464      * and {@code this} otherwise.
 465      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 466      * for reflective objects corresponding to the given members declared in type {@code C}.
 467      * <p>
 468      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 469      * as if by {@code ldc CONSTANT_Class}.
 470      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 471      * <p>
 472      * In cases where the given member is of variable arity (i.e., a method or constructor)
 473      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 474      * In all other cases, the returned method handle will be of fixed arity.
 475      * <p style="font-size:smaller;">
 476      * <em>Discussion:</em>
 477      * The equivalence between looked-up method handles and underlying
 478      * class members and bytecode behaviors
 479      * can break down in a few ways:
 480      * <ul style="font-size:smaller;">
 481      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 482      * the lookup can still succeed, even when there is no equivalent
 483      * Java expression or bytecoded constant.
 484      * <li>Likewise, if {@code T} or {@code MT}
 485      * is not symbolically accessible from the lookup class's loader,
 486      * the lookup can still succeed.
 487      * For example, lookups for {@code MethodHandle.invokeExact} and
 488      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 489      * <li>If there is a security manager installed, it can forbid the lookup
 490      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 491      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 492      * constant is not subject to security manager checks.
 493      * <li>If the looked-up method has a
 494      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 495      * the method handle creation may fail with an
 496      * {@code IllegalArgumentException}, due to the method handle type having
 497      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 498      * </ul>
 499      *
 500      * <h2><a id="access"></a>Access checking</h2>
 501      * Access checks are applied in the factory methods of {@code Lookup},
 502      * when a method handle is created.
 503      * This is a key difference from the Core Reflection API, since
 504      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 505      * performs access checking against every caller, on every call.
 506      * <p>
 507      * All access checks start from a {@code Lookup} object, which
 508      * compares its recorded lookup class against all requests to
 509      * create method handles.
 510      * A single {@code Lookup} object can be used to create any number
 511      * of access-checked method handles, all checked against a single
 512      * lookup class.
 513      * <p>
 514      * A {@code Lookup} object can be shared with other trusted code,
 515      * such as a metaobject protocol.
 516      * A shared {@code Lookup} object delegates the capability
 517      * to create method handles on private members of the lookup class.
 518      * Even if privileged code uses the {@code Lookup} object,
 519      * the access checking is confined to the privileges of the
 520      * original lookup class.
 521      * <p>
 522      * A lookup can fail, because
 523      * the containing class is not accessible to the lookup class, or
 524      * because the desired class member is missing, or because the
 525      * desired class member is not accessible to the lookup class, or
 526      * because the lookup object is not trusted enough to access the member.
 527      * In the case of a field setter function on a {@code final} field,
 528      * finality enforcement is treated as a kind of access control,
 529      * and the lookup will fail, except in special cases of
 530      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 531      * In any of these cases, a {@code ReflectiveOperationException} will be
 532      * thrown from the attempted lookup.  The exact class will be one of
 533      * the following:
 534      * <ul>
 535      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 536      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 537      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 538      * </ul>
 539      * <p>
 540      * In general, the conditions under which a method handle may be
 541      * looked up for a method {@code M} are no more restrictive than the conditions
 542      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 543      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 544      * a method handle lookup will generally raise a corresponding
 545      * checked exception, such as {@code NoSuchMethodException}.
 546      * And the effect of invoking the method handle resulting from the lookup
 547      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 548      * to executing the compiled, verified, and resolved call to {@code M}.
 549      * The same point is true of fields and constructors.
 550      * <p style="font-size:smaller;">
 551      * <em>Discussion:</em>
 552      * Access checks only apply to named and reflected methods,
 553      * constructors, and fields.
 554      * Other method handle creation methods, such as
 555      * {@link MethodHandle#asType MethodHandle.asType},
 556      * do not require any access checks, and are used
 557      * independently of any {@code Lookup} object.
 558      * <p>
 559      * If the desired member is {@code protected}, the usual JVM rules apply,
 560      * including the requirement that the lookup class must either be in the
 561      * same package as the desired member, or must inherit that member.
 562      * (See the Java Virtual Machine Specification, sections {@jvms
 563      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 564      * In addition, if the desired member is a non-static field or method
 565      * in a different package, the resulting method handle may only be applied
 566      * to objects of the lookup class or one of its subclasses.
 567      * This requirement is enforced by narrowing the type of the leading
 568      * {@code this} parameter from {@code C}
 569      * (which will necessarily be a superclass of the lookup class)
 570      * to the lookup class itself.
 571      * <p>
 572      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 573      * that the receiver argument must match both the resolved method <em>and</em>
 574      * the current class.  Again, this requirement is enforced by narrowing the
 575      * type of the leading parameter to the resulting method handle.
 576      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 577      * <p>
 578      * The JVM represents constructors and static initializer blocks as internal methods
 579      * with special names ({@code "<init>"} and {@code "<clinit>"}).
 580      * The internal syntax of invocation instructions allows them to refer to such internal
 581      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 582      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 583      * <p>
 584      * If the relationship between nested types is expressed directly through the
 585      * {@code NestHost} and {@code NestMembers} attributes
 586      * (see the Java Virtual Machine Specification, sections {@jvms
 587      * 4.7.28} and {@jvms 4.7.29}),
 588      * then the associated {@code Lookup} object provides direct access to
 589      * the lookup class and all of its nestmates
 590      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 591      * Otherwise, access between nested classes is obtained by the Java compiler creating
 592      * a wrapper method to access a private method of another class in the same nest.
 593      * For example, a nested class {@code C.D}
 594      * can access private members within other related classes such as
 595      * {@code C}, {@code C.D.E}, or {@code C.B},
 596      * but the Java compiler may need to generate wrapper methods in
 597      * those related classes.  In such cases, a {@code Lookup} object on
 598      * {@code C.E} would be unable to access those private members.
 599      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 600      * which can transform a lookup on {@code C.E} into one on any of those other
 601      * classes, without special elevation of privilege.
 602      * <p>
 603      * The accesses permitted to a given lookup object may be limited,
 604      * according to its set of {@link #lookupModes lookupModes},
 605      * to a subset of members normally accessible to the lookup class.
 606      * For example, the {@link MethodHandles#publicLookup publicLookup}
 607      * method produces a lookup object which is only allowed to access
 608      * public members in public classes of exported packages.
 609      * The caller sensitive method {@link MethodHandles#lookup lookup}
 610      * produces a lookup object with full capabilities relative to
 611      * its caller class, to emulate all supported bytecode behaviors.
 612      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 613      * with fewer access modes than the original lookup object.
 614      *
 615      * <p style="font-size:smaller;">
 616      * <a id="privacc"></a>
 617      * <em>Discussion of private and module access:</em>
 618      * We say that a lookup has <em>private access</em>
 619      * if its {@linkplain #lookupModes lookup modes}
 620      * include the possibility of accessing {@code private} members
 621      * (which includes the private members of nestmates).
 622      * As documented in the relevant methods elsewhere,
 623      * only lookups with private access possess the following capabilities:
 624      * <ul style="font-size:smaller;">
 625      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 626      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 627      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 628      *     for classes accessible to the lookup class
 629      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 630      *     within the same package member
 631      * </ul>
 632      * <p style="font-size:smaller;">
 633      * Similarly, a lookup with module access ensures that the original lookup creator was
 634      * a member in the same module as the lookup class.
 635      * <p style="font-size:smaller;">
 636      * Private and module access are independently determined modes; a lookup may have
 637      * either or both or neither.  A lookup which possesses both access modes is said to
 638      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.  Such a lookup has
 639      * the following additional capability:
 640      * <ul style="font-size:smaller;">
 641      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 642      *     such as {@code Class.forName}
 643      * </ul>
 644      * <p style="font-size:smaller;">
 645      * Each of these permissions is a consequence of the fact that a lookup object
 646      * with private access can be securely traced back to an originating class,
 647      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 648      * can be reliably determined and emulated by method handles.
 649      *
 650      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 651      * When a lookup class in one module {@code M1} accesses a class in another module
 652      * {@code M2}, extra access checking is performed beyond the access mode bits.
 653      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 654      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 655      * and when the type is in a package of {@code M2} that is exported to
 656      * at least {@code M1}.
 657      * <p>
 658      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 659      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 660      * MethodHandles.privateLookupIn} methods.
 661      * Teleporting across modules will always record the original lookup class as
 662      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 663      * and drops {@link Lookup#MODULE MODULE} access.
 664      * If the target class is in the same module as the lookup class {@code C},
 665      * then the target class becomes the new lookup class
 666      * and there is no change to the previous lookup class.
 667      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 668      * {@code C} becomes the new previous lookup class
 669      * and the target class becomes the new lookup class.
 670      * In that case, if there was already a previous lookup class in {@code M0},
 671      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 672      * drops all privileges.
 673      * For example,
 674      * <blockquote><pre>
 675      * {@code
 676      * Lookup lookup = MethodHandles.lookup();   // in class C
 677      * Lookup lookup2 = lookup.in(D.class);
 678      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 679      * }</pre></blockquote>
 680      * <p>
 681      * The {@link #lookup()} factory method produces a {@code Lookup} object
 682      * with {@code null} previous lookup class.
 683      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 684      * to class {@code D} without elevation of privileges.
 685      * If {@code C} and {@code D} are in the same module,
 686      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 687      * same previous lookup class as the original {@code lookup}, or
 688      * {@code null} if not present.
 689      * <p>
 690      * When a {@code Lookup} teleports from a class
 691      * in one nest to another nest, {@code PRIVATE} access is dropped.
 692      * When a {@code Lookup} teleports from a class in one package to
 693      * another package, {@code PACKAGE} access is dropped.
 694      * When a {@code Lookup} teleports from a class in one module to another module,
 695      * {@code MODULE} access is dropped.
 696      * Teleporting across modules drops the ability to access non-exported classes
 697      * in both the module of the new lookup class and the module of the old lookup class
 698      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 699      * A {@code Lookup} can teleport back and forth to a class in the module of
 700      * the lookup class and the module of the previous class lookup.
 701      * Teleporting across modules can only decrease access but cannot increase it.
 702      * Teleporting to some third module drops all accesses.
 703      * <p>
 704      * In the above example, if {@code C} and {@code D} are in different modules,
 705      * {@code lookup2} records {@code D} as its lookup class and
 706      * {@code C} as its previous lookup class and {@code lookup2} has only
 707      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 708      * {@code C}'s module and {@code D}'s module.
 709      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 710      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 711      * class {@code D} is recorded as its previous lookup class.
 712      * <p>
 713      * Teleporting across modules restricts access to the public types that
 714      * both the lookup class and the previous lookup class can equally access
 715      * (see below).
 716      * <p>
 717      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 718      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 719      * and create a new {@code Lookup} with <a href="#privacc">private access</a>
 720      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 721      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 722      * to call {@code privateLookupIn}.
 723      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 724      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 725      * produces a new {@code Lookup} on {@code T} with full capabilities.
 726      * A {@code lookup} on {@code C} is also allowed
 727      * to do deep reflection on {@code T} in another module {@code M2} if
 728      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 729      * the package containing {@code T} to at least {@code M1}.
 730      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 731      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 732      * The resulting {@code Lookup} can be used to do member lookup or teleport
 733      * to another lookup class by calling {@link #in Lookup::in}.  But
 734      * it cannot be used to obtain another private {@code Lookup} by calling
 735      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 736      * because it has no {@code MODULE} access.
 737      *
 738      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 739      *
 740      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 741      * allows cross-module access. The access checking is performed with respect
 742      * to both the lookup class and the previous lookup class if present.
 743      * <p>
 744      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 745      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 746      * exported unconditionally}.
 747      * <p>
 748      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 749      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 750      * that are readable to {@code M1} and the type is in a package that is exported
 751      * at least to {@code M1}.
 752      * <p>
 753      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 754      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 755      * the intersection of all public types that are accessible to {@code M1}
 756      * with all public types that are accessible to {@code M0}. {@code M0}
 757      * reads {@code M1} and hence the set of accessible types includes:
 758      *
 759      * <table class="striped">
 760      * <caption style="display:none">
 761      * Public types in the following packages are accessible to the
 762      * lookup class and the previous lookup class.
 763      * </caption>
 764      * <thead>
 765      * <tr>
 766      * <th scope="col">Equally accessible types to {@code M0} and {@code M1}</th>
 767      * </tr>
 768      * </thead>
 769      * <tbody>
 770      * <tr>
 771      * <th scope="row" style="text-align:left">unconditional-exported packages from {@code M1}</th>
 772      * </tr>
 773      * <tr>
 774      * <th scope="row" style="text-align:left">unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</th>
 775      * </tr>
 776      * <tr>
 777      * <th scope="row" style="text-align:left">unconditional-exported packages from a third module {@code M2}
 778      * if both {@code M0} and {@code M1} read {@code M2}</th>
 779      * </tr>
 780      * <tr>
 781      * <th scope="row" style="text-align:left">qualified-exported packages from {@code M1} to {@code M0}</th>
 782      * </tr>
 783      * <tr>
 784      * <th scope="row" style="text-align:left">qualified-exported packages from {@code M0} to {@code M1}
 785      * if {@code M1} reads {@code M0}</th>
 786      * </tr>
 787      * <tr>
 788      * <th scope="row" style="text-align:left">qualified-exported packages from a third module {@code M2} to
 789      * both {@code M0} and {@code M1} if both {@code M0} and {@code M1} read {@code M2}</th>
 790      * </tr>
 791      * </tbody>
 792      * </table>
 793      *
 794      * <h2><a id="access-modes"></a>Access modes</h2>
 795      *
 796      * The table below shows the access modes of a {@code Lookup} produced by
 797      * any of the following factory or transformation methods:
 798      * <ul>
 799      * <li>{@link #lookup() MethodHandles::lookup}</li>
 800      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 801      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 802      * <li>{@link Lookup#in Lookup::in}</li>
 803      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 804      * </ul>
 805      *
 806      * <table class="striped">
 807      * <caption style="display:none">
 808      * Access mode summary
 809      * </caption>
 810      * <thead>
 811      * <tr>
 812      * <th scope="col">Lookup object</th>
 813      * <th style="text-align:center">protected</th>
 814      * <th style="text-align:center">private</th>
 815      * <th style="text-align:center">package</th>
 816      * <th style="text-align:center">module</th>
 817      * <th style="text-align:center">public</th>
 818      * </tr>
 819      * </thead>
 820      * <tbody>
 821      * <tr>
 822      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 823      * <td style="text-align:center">PRO</td>
 824      * <td style="text-align:center">PRI</td>
 825      * <td style="text-align:center">PAC</td>
 826      * <td style="text-align:center">MOD</td>
 827      * <td style="text-align:center">1R</td>
 828      * </tr>
 829      * <tr>
 830      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 831      * <td></td>
 832      * <td></td>
 833      * <td style="text-align:center">PAC</td>
 834      * <td style="text-align:center">MOD</td>
 835      * <td style="text-align:center">1R</td>
 836      * </tr>
 837      * <tr>
 838      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 839      * <td></td>
 840      * <td></td>
 841      * <td></td>
 842      * <td style="text-align:center">MOD</td>
 843      * <td style="text-align:center">1R</td>
 844      * </tr>
 845      * <tr>
 846      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 847      * <td></td>
 848      * <td></td>
 849      * <td></td>
 850      * <td></td>
 851      * <td style="text-align:center">2R</td>
 852      * </tr>
 853      * <tr>
 854      * <td>{@code CL.in(D).in(C)} hop back to module</td>
 855      * <td></td>
 856      * <td></td>
 857      * <td></td>
 858      * <td></td>
 859      * <td style="text-align:center">2R</td>
 860      * </tr>
 861      * <tr>
 862      * <td>{@code PRI1 = privateLookupIn(C1,CL)}</td>
 863      * <td style="text-align:center">PRO</td>
 864      * <td style="text-align:center">PRI</td>
 865      * <td style="text-align:center">PAC</td>
 866      * <td style="text-align:center">MOD</td>
 867      * <td style="text-align:center">1R</td>
 868      * </tr>
 869      * <tr>
 870      * <td>{@code PRI1a = privateLookupIn(C,PRI1)}</td>
 871      * <td style="text-align:center">PRO</td>
 872      * <td style="text-align:center">PRI</td>
 873      * <td style="text-align:center">PAC</td>
 874      * <td style="text-align:center">MOD</td>
 875      * <td style="text-align:center">1R</td>
 876      * </tr>
 877      * <tr>
 878      * <td>{@code PRI1.in(C1)} same package</td>
 879      * <td></td>
 880      * <td></td>
 881      * <td style="text-align:center">PAC</td>
 882      * <td style="text-align:center">MOD</td>
 883      * <td style="text-align:center">1R</td>
 884      * </tr>
 885      * <tr>
 886      * <td>{@code PRI1.in(C1)} different package</td>
 887      * <td></td>
 888      * <td></td>
 889      * <td></td>
 890      * <td style="text-align:center">MOD</td>
 891      * <td style="text-align:center">1R</td>
 892      * </tr>
 893      * <tr>
 894      * <td>{@code PRI1.in(D)} different module</td>
 895      * <td></td>
 896      * <td></td>
 897      * <td></td>
 898      * <td></td>
 899      * <td style="text-align:center">2R</td>
 900      * </tr>
 901      * <tr>
 902      * <td>{@code PRI1.dropLookupMode(PROTECTED)}</td>
 903      * <td></td>
 904      * <td style="text-align:center">PRI</td>
 905      * <td style="text-align:center">PAC</td>
 906      * <td style="text-align:center">MOD</td>
 907      * <td style="text-align:center">1R</td>
 908      * </tr>
 909      * <tr>
 910      * <td>{@code PRI1.dropLookupMode(PRIVATE)}</td>
 911      * <td></td>
 912      * <td></td>
 913      * <td style="text-align:center">PAC</td>
 914      * <td style="text-align:center">MOD</td>
 915      * <td style="text-align:center">1R</td>
 916      * </tr>
 917      * <tr>
 918      * <td>{@code PRI1.dropLookupMode(PACKAGE)}</td>
 919      * <td></td>
 920      * <td></td>
 921      * <td></td>
 922      * <td style="text-align:center">MOD</td>
 923      * <td style="text-align:center">1R</td>
 924      * </tr>
 925      * <tr>
 926      * <td>{@code PRI1.dropLookupMode(MODULE)}</td>
 927      * <td></td>
 928      * <td></td>
 929      * <td></td>
 930      * <td></td>
 931      * <td style="text-align:center">1R</td>
 932      * </tr>
 933      * <tr>
 934      * <td>{@code PRI1.dropLookupMode(PUBLIC)}</td>
 935      * <td></td>
 936      * <td></td>
 937      * <td></td>
 938      * <td></td>
 939      * <td style="text-align:center">none</td>
 940      * <tr>
 941      * <td>{@code PRI2 = privateLookupIn(D,CL)}</td>
 942      * <td style="text-align:center">PRO</td>
 943      * <td style="text-align:center">PRI</td>
 944      * <td style="text-align:center">PAC</td>
 945      * <td></td>
 946      * <td style="text-align:center">2R</td>
 947      * </tr>
 948      * <tr>
 949      * <td>{@code privateLookupIn(D,PRI1)}</td>
 950      * <td style="text-align:center">PRO</td>
 951      * <td style="text-align:center">PRI</td>
 952      * <td style="text-align:center">PAC</td>
 953      * <td></td>
 954      * <td style="text-align:center">2R</td>
 955      * </tr>
 956      * <tr>
 957      * <td>{@code privateLookupIn(C,PRI2)} fails</td>
 958      * <td></td>
 959      * <td></td>
 960      * <td></td>
 961      * <td></td>
 962      * <td style="text-align:center">IAE</td>
 963      * </tr>
 964      * <tr>
 965      * <td>{@code PRI2.in(D2)} same package</td>
 966      * <td></td>
 967      * <td></td>
 968      * <td style="text-align:center">PAC</td>
 969      * <td></td>
 970      * <td style="text-align:center">2R</td>
 971      * </tr>
 972      * <tr>
 973      * <td>{@code PRI2.in(D2)} different package</td>
 974      * <td></td>
 975      * <td></td>
 976      * <td></td>
 977      * <td></td>
 978      * <td style="text-align:center">2R</td>
 979      * </tr>
 980      * <tr>
 981      * <td>{@code PRI2.in(C1)} hop back to module</td>
 982      * <td></td>
 983      * <td></td>
 984      * <td></td>
 985      * <td></td>
 986      * <td style="text-align:center">2R</td>
 987      * </tr>
 988      * <tr>
 989      * <td>{@code PRI2.in(E)} hop to third module</td>
 990      * <td></td>
 991      * <td></td>
 992      * <td></td>
 993      * <td></td>
 994      * <td style="text-align:center">none</td>
 995      * </tr>
 996      * <tr>
 997      * <td>{@code PRI2.dropLookupMode(PROTECTED)}</td>
 998      * <td></td>
 999      * <td style="text-align:center">PRI</td>
1000      * <td style="text-align:center">PAC</td>
1001      * <td></td>
1002      * <td style="text-align:center">2R</td>
1003      * </tr>
1004      * <tr>
1005      * <td>{@code PRI2.dropLookupMode(PRIVATE)}</td>
1006      * <td></td>
1007      * <td></td>
1008      * <td style="text-align:center">PAC</td>
1009      * <td></td>
1010      * <td style="text-align:center">2R</td>
1011      * </tr>
1012      * <tr>
1013      * <td>{@code PRI2.dropLookupMode(PACKAGE)}</td>
1014      * <td></td>
1015      * <td></td>
1016      * <td></td>
1017      * <td></td>
1018      * <td style="text-align:center">2R</td>
1019      * </tr>
1020      * <tr>
1021      * <td>{@code PRI2.dropLookupMode(MODULE)}</td>
1022      * <td></td>
1023      * <td></td>
1024      * <td></td>
1025      * <td></td>
1026      * <td style="text-align:center">2R</td>
1027      * </tr>
1028      * <tr>
1029      * <td>{@code PRI2.dropLookupMode(PUBLIC)}</td>
1030      * <td></td>
1031      * <td></td>
1032      * <td></td>
1033      * <td></td>
1034      * <td style="text-align:center">none</td>
1035      * </tr>
1036      * <tr>
1037      * <td>{@code CL.dropLookupMode(PROTECTED)}</td>
1038      * <td></td>
1039      * <td style="text-align:center">PRI</td>
1040      * <td style="text-align:center">PAC</td>
1041      * <td style="text-align:center">MOD</td>
1042      * <td style="text-align:center">1R</td>
1043      * </tr>
1044      * <tr>
1045      * <td>{@code CL.dropLookupMode(PRIVATE)}</td>
1046      * <td></td>
1047      * <td></td>
1048      * <td style="text-align:center">PAC</td>
1049      * <td style="text-align:center">MOD</td>
1050      * <td style="text-align:center">1R</td>
1051      * </tr>
1052      * <tr>
1053      * <td>{@code CL.dropLookupMode(PACKAGE)}</td>
1054      * <td></td>
1055      * <td></td>
1056      * <td></td>
1057      * <td style="text-align:center">MOD</td>
1058      * <td style="text-align:center">1R</td>
1059      * </tr>
1060      * <tr>
1061      * <td>{@code CL.dropLookupMode(MODULE)}</td>
1062      * <td></td>
1063      * <td></td>
1064      * <td></td>
1065      * <td></td>
1066      * <td style="text-align:center">1R</td>
1067      * </tr>
1068      * <tr>
1069      * <td>{@code CL.dropLookupMode(PUBLIC)}</td>
1070      * <td></td>
1071      * <td></td>
1072      * <td></td>
1073      * <td></td>
1074      * <td style="text-align:center">none</td>
1075      * </tr>
1076      * <tr>
1077      * <td>{@code PUB = publicLookup()}</td>
1078      * <td></td>
1079      * <td></td>
1080      * <td></td>
1081      * <td></td>
1082      * <td style="text-align:center">U</td>
1083      * </tr>
1084      * <tr>
1085      * <td>{@code PUB.in(D)} different module</td>
1086      * <td></td>
1087      * <td></td>
1088      * <td></td>
1089      * <td></td>
1090      * <td style="text-align:center">U</td>
1091      * </tr>
1092      * <tr>
1093      * <td>{@code PUB.in(D).in(E)} third module</td>
1094      * <td></td>
1095      * <td></td>
1096      * <td></td>
1097      * <td></td>
1098      * <td style="text-align:center">U</td>
1099      * </tr>
1100      * <tr>
1101      * <td>{@code PUB.dropLookupMode(UNCONDITIONAL)}</td>
1102      * <td></td>
1103      * <td></td>
1104      * <td></td>
1105      * <td></td>
1106      * <td style="text-align:center">none</td>
1107      * </tr>
1108      * <tr>
1109      * <td>{@code privateLookupIn(C1,PUB)} fails</td>
1110      * <td></td>
1111      * <td></td>
1112      * <td></td>
1113      * <td></td>
1114      * <td style="text-align:center">IAE</td>
1115      * </tr>
1116      * <tr>
1117      * <td>{@code ANY.in(X)}, for inaccessible {@code X}</td>
1118      * <td></td>
1119      * <td></td>
1120      * <td></td>
1121      * <td></td>
1122      * <td style="text-align:center">none</td>
1123      * </tr>
1124      * </tbody>
1125      * </table>
1126      *
1127      * <p>
1128      * Notes:
1129      * <ul>
1130      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1131      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1132      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1133      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1134      * <li>{@code PRO} indicates {@link #PROTECTED} bit set,
1135      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1136      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1137      *     {@code MOD} indicates {@link #MODULE} bit set,
1138      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1139      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1140      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1141      * <li>Public access comes in three kinds:
1142      * <ul>
1143      * <li>unconditional ({@code U}): the lookup assumes readability.
1144      *     The lookup has {@code null} previous lookup class.
1145      * <li>one-module-reads ({@code 1R}): the module access checking is
1146      *     performed with respect to the lookup class.  The lookup has {@code null}
1147      *     previous lookup class.
1148      * <li>two-module-reads ({@code 2R}): the module access checking is
1149      *     performed with respect to the lookup class and the previous lookup class.
1150      *     The lookup has a non-null previous lookup class which is in a
1151      *     different module from the current lookup class.
1152      * </ul>
1153      * <li>Any attempt to reach a third module loses all access.</li>
1154      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1155      * all access modes are dropped.</li>
1156      * </ul>
1157      *
1158      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1159      * Although bytecode instructions can only refer to classes in
1160      * a related class loader, this API can search for methods in any
1161      * class, as long as a reference to its {@code Class} object is
1162      * available.  Such cross-loader references are also possible with the
1163      * Core Reflection API, and are impossible to bytecode instructions
1164      * such as {@code invokestatic} or {@code getfield}.
1165      * There is a {@linkplain java.lang.SecurityManager security manager API}
1166      * to allow applications to check such cross-loader references.
1167      * These checks apply to both the {@code MethodHandles.Lookup} API
1168      * and the Core Reflection API
1169      * (as found on {@link java.lang.Class Class}).
1170      * <p>
1171      * If a security manager is present, member and class lookups are subject to
1172      * additional checks.
1173      * From one to three calls are made to the security manager.
1174      * Any of these calls can refuse access by throwing a
1175      * {@link java.lang.SecurityException SecurityException}.
1176      * Define {@code smgr} as the security manager,
1177      * {@code lookc} as the lookup class of the current lookup object,
1178      * {@code refc} as the containing class in which the member
1179      * is being sought, and {@code defc} as the class in which the
1180      * member is actually defined.
1181      * (If a class or other type is being accessed,
1182      * the {@code refc} and {@code defc} values are the class itself.)
1183      * The value {@code lookc} is defined as <em>not present</em>
1184      * if the current lookup object does not have
1185      * {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1186      * The calls are made according to the following rules:
1187      * <ul>
1188      * <li><b>Step 1:</b>
1189      *     If {@code lookc} is not present, or if its class loader is not
1190      *     the same as or an ancestor of the class loader of {@code refc},
1191      *     then {@link SecurityManager#checkPackageAccess
1192      *     smgr.checkPackageAccess(refcPkg)} is called,
1193      *     where {@code refcPkg} is the package of {@code refc}.
1194      * <li><b>Step 2a:</b>
1195      *     If the retrieved member is not public and
1196      *     {@code lookc} is not present, then
1197      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1198      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
1199      * <li><b>Step 2b:</b>
1200      *     If the retrieved class has a {@code null} class loader,
1201      *     and {@code lookc} is not present, then
1202      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1203      *     with {@code RuntimePermission("getClassLoader")} is called.
1204      * <li><b>Step 3:</b>
1205      *     If the retrieved member is not public,
1206      *     and if {@code lookc} is not present,
1207      *     and if {@code defc} and {@code refc} are different,
1208      *     then {@link SecurityManager#checkPackageAccess
1209      *     smgr.checkPackageAccess(defcPkg)} is called,
1210      *     where {@code defcPkg} is the package of {@code defc}.
1211      * </ul>
1212      * Security checks are performed after other access checks have passed.
1213      * Therefore, the above rules presuppose a member or class that is public,
1214      * or else that is being accessed from a lookup class that has
1215      * rights to access the member or class.
1216      * <p>
1217      * If a security manager is present and the current lookup object does not have
1218      * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then
1219      * {@link #defineClass(byte[]) defineClass}
1220      * calls {@link SecurityManager#checkPermission smgr.checkPermission}
1221      * with {@code RuntimePermission("defineClass")}.
1222      *
1223      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1224      * A small number of Java methods have a special property called caller sensitivity.
1225      * A <em>caller-sensitive</em> method can behave differently depending on the
1226      * identity of its immediate caller.
1227      * <p>
1228      * If a method handle for a caller-sensitive method is requested,
1229      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1230      * but they take account of the lookup class in a special way.
1231      * The resulting method handle behaves as if it were called
1232      * from an instruction contained in the lookup class,
1233      * so that the caller-sensitive method detects the lookup class.
1234      * (By contrast, the invoker of the method handle is disregarded.)
1235      * Thus, in the case of caller-sensitive methods,
1236      * different lookup classes may give rise to
1237      * differently behaving method handles.
1238      * <p>
1239      * In cases where the lookup object is
1240      * {@link MethodHandles#publicLookup() publicLookup()},
1241      * or some other lookup object without the
1242      * {@linkplain #hasFullPrivilegeAccess() full privilege access},
1243      * the lookup class is disregarded.
1244      * In such cases, no caller-sensitive method handle can be created,
1245      * access is forbidden, and the lookup fails with an
1246      * {@code IllegalAccessException}.
1247      * <p style="font-size:smaller;">
1248      * <em>Discussion:</em>
1249      * For example, the caller-sensitive method
1250      * {@link java.lang.Class#forName(String) Class.forName(x)}
1251      * can return varying classes or throw varying exceptions,
1252      * depending on the class loader of the class that calls it.
1253      * A public lookup of {@code Class.forName} will fail, because
1254      * there is no reasonable way to determine its bytecode behavior.
1255      * <p style="font-size:smaller;">
1256      * If an application caches method handles for broad sharing,
1257      * it should use {@code publicLookup()} to create them.
1258      * If there is a lookup of {@code Class.forName}, it will fail,
1259      * and the application must take appropriate action in that case.
1260      * It may be that a later lookup, perhaps during the invocation of a
1261      * bootstrap method, can incorporate the specific identity
1262      * of the caller, making the method accessible.
1263      * <p style="font-size:smaller;">
1264      * The function {@code MethodHandles.lookup} is caller sensitive
1265      * so that there can be a secure foundation for lookups.
1266      * Nearly all other methods in the JSR 292 API rely on lookup
1267      * objects to check access requests.
1268      *
1269      * @revised 9
1270      */
1271     public static final
1272     class Lookup {
1273         /** The class on behalf of whom the lookup is being performed. */
1274         private final Class<?> lookupClass;
1275 
1276         /** previous lookup class */
1277         private final Class<?> prevLookupClass;
1278 
1279         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1280         private final int allowedModes;
1281 
1282         static {
1283             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1284         }
1285 
1286         /** A single-bit mask representing {@code public} access,
1287          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1288          *  The value, {@code 0x01}, happens to be the same as the value of the
1289          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1290          *  <p>
1291          *  A {@code Lookup} with this lookup mode performs cross-module access check
1292          *  with respect to the {@linkplain #lookupClass() lookup class} and
1293          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1294          */
1295         public static final int PUBLIC = Modifier.PUBLIC;
1296 
1297         /** A single-bit mask representing {@code private} access,
1298          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1299          *  The value, {@code 0x02}, happens to be the same as the value of the
1300          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1301          */
1302         public static final int PRIVATE = Modifier.PRIVATE;
1303 
1304         /** A single-bit mask representing {@code protected} access,
1305          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1306          *  The value, {@code 0x04}, happens to be the same as the value of the
1307          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1308          */
1309         public static final int PROTECTED = Modifier.PROTECTED;
1310 
1311         /** A single-bit mask representing {@code package} access (default access),
1312          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1313          *  The value is {@code 0x08}, which does not correspond meaningfully to
1314          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1315          */
1316         public static final int PACKAGE = Modifier.STATIC;
1317 
1318         /** A single-bit mask representing {@code module} access,
1319          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1320          *  The value is {@code 0x10}, which does not correspond meaningfully to
1321          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1322          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1323          *  with this lookup mode can access all public types in the module of the
1324          *  lookup class and public types in packages exported by other modules
1325          *  to the module of the lookup class.
1326          *  <p>
1327          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1328          *  previous lookup class} is always {@code null}.
1329          *
1330          *  @since 9
1331          *  @spec JPMS
1332          */
1333         public static final int MODULE = PACKAGE << 1;
1334 
1335         /** A single-bit mask representing {@code unconditional} access
1336          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1337          *  The value is {@code 0x20}, which does not correspond meaningfully to
1338          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1339          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1340          *  java.lang.Module#canRead(java.lang.Module) readability}.
1341          *  This lookup mode can access all public members of public types
1342          *  of all modules when the type is in a package that is {@link
1343          *  java.lang.Module#isExported(String) exported unconditionally}.
1344          *
1345          *  <p>
1346          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1347          *  previous lookup class} is always {@code null}.
1348          *
1349          *  @since 9
1350          *  @spec JPMS
1351          *  @see #publicLookup()
1352          */
1353         public static final int UNCONDITIONAL = PACKAGE << 2;
1354 
1355         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL);
1356         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);
1357         private static final int TRUSTED   = -1;
1358 
1359         /*
1360          * Adjust PUBLIC => PUBLIC|MODULE|UNCONDITIONAL
1361          * Adjust 0 => PACKAGE
1362          */
1363         private static int fixmods(int mods) {
1364             mods &= (ALL_MODES - PACKAGE - MODULE - UNCONDITIONAL);
1365             if (Modifier.isPublic(mods))
1366                 mods |= UNCONDITIONAL;
1367             return (mods != 0) ? mods : PACKAGE;
1368         }
1369 
1370         /** Tells which class is performing the lookup.  It is this class against
1371          *  which checks are performed for visibility and access permissions.
1372          *  <p>
1373          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1374          *  access checks are performed against both the lookup class and the previous lookup class.
1375          *  <p>
1376          *  The class implies a maximum level of access permission,
1377          *  but the permissions may be additionally limited by the bitmask
1378          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1379          *  can be accessed.
1380          *  @return the lookup class, on behalf of which this lookup object finds members
1381          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1382          */
1383         public Class<?> lookupClass() {
1384             return lookupClass;
1385         }
1386 
1387         /** Reports a lookup class in another module that this lookup object
1388          * was previously teleported from, or {@code null}.
1389          * <p>
1390          * A {@code Lookup} object produced by the factory methods, such as the
1391          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1392          * has {@code null} previous lookup class.
1393          * A {@code Lookup} object has a non-null previous lookup class
1394          * when this lookup was teleported from an old lookup class
1395          * in one module to a new lookup class in another module.
1396          *
1397          * @return the lookup class in another module that this lookup object was
1398          *         previously teleported from, or {@code null}
1399          * @since 14
1400          * @see #in(Class)
1401          * @see MethodHandles#privateLookupIn(Class, Lookup)
1402          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1403          */
1404         public Class<?> previousLookupClass() {
1405             return prevLookupClass;
1406         }
1407 
1408         // This is just for calling out to MethodHandleImpl.
1409         private Class<?> lookupClassOrNull() {
1410             if (allowedModes == TRUSTED) {
1411                 return null;
1412             }
1413             if (allowedModes == UNCONDITIONAL) {
1414                 // use Object as the caller to pass to VM doing resolution
1415                 return Object.class;
1416             }
1417             return lookupClass;
1418         }
1419 
1420         /** Tells which access-protection classes of members this lookup object can produce.
1421          *  The result is a bit-mask of the bits
1422          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1423          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1424          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1425          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1426          *  {@linkplain #MODULE MODULE (0x10)},
1427          *  and {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}.
1428          *  <p>
1429          *  A freshly-created lookup object
1430          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1431          *  all possible bits set, except {@code UNCONDITIONAL}.
1432          *  A lookup object on a new lookup class
1433          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1434          *  may have some mode bits set to zero.
1435          *  Mode bits can also be
1436          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1437          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1438          *  The purpose of this is to restrict access via the new lookup object,
1439          *  so that it can access only names which can be reached by the original
1440          *  lookup object, and also by the new lookup class.
1441          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1442          *  @see #in
1443          *  @see #dropLookupMode
1444          *
1445          *  @revised 9
1446          *  @spec JPMS
1447          */
1448         public int lookupModes() {
1449             return allowedModes & ALL_MODES;
1450         }
1451 
1452         /** Embody the current class (the lookupClass) as a lookup class
1453          * for method handle creation.
1454          * Must be called by from a method in this package,
1455          * which in turn is called by a method not in this package.
1456          */
1457         Lookup(Class<?> lookupClass) {
1458             this(lookupClass, null, FULL_POWER_MODES);
1459         }
1460 
1461         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1462             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1463                     && prevLookupClass.getModule() != lookupClass.getModule());
1464             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1465             this.lookupClass = lookupClass;
1466             this.prevLookupClass = prevLookupClass;
1467             this.allowedModes = allowedModes;
1468         }
1469 
1470         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1471             // make sure we haven't accidentally picked up a privileged class:
1472             checkUnprivilegedlookupClass(lookupClass);
1473             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1474         }
1475 
1476         /**
1477          * Creates a lookup on the specified new lookup class.
1478          * The resulting object will report the specified
1479          * class as its own {@link #lookupClass() lookupClass}.
1480          *
1481          * <p>
1482          * However, the resulting {@code Lookup} object is guaranteed
1483          * to have no more access capabilities than the original.
1484          * In particular, access capabilities can be lost as follows:<ul>
1485          * <li>If the new lookup class is in a different module from the old one,
1486          * i.e. {@link #MODULE MODULE} access is lost.
1487          * <li>If the new lookup class is in a different package
1488          * than the old one, protected and default (package) members will not be accessible,
1489          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1490          * <li>If the new lookup class is not within the same package member
1491          * as the old one, private members will not be accessible, and protected members
1492          * will not be accessible by virtue of inheritance,
1493          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1494          * (Protected members may continue to be accessible because of package sharing.)
1495          * <li>If the new lookup class is not
1496          * {@linkplain #accessClass(Class) accessible} to this lookup,
1497          * then no members, not even public members, will be accessible
1498          * i.e. all access modes are lost.
1499          * <li>If the new lookup class, the old lookup class and the previous lookup class
1500          * are all in different modules i.e. teleporting to a third module,
1501          * all access modes are lost.
1502          * </ul>
1503          * <p>
1504          * The new previous lookup class is chosen as follows:
1505          * <ul>
1506          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1507          * the new previous lookup class is {@code null}.
1508          * <li>If the new lookup class is in the same module as the old lookup class,
1509          * the new previous lookup class is the old previous lookup class.
1510          * <li>If the new lookup class is in a different module from the old lookup class,
1511          * the new previous lookup class is the old lookup class.
1512          *</ul>
1513          * <p>
1514          * The resulting lookup's capabilities for loading classes
1515          * (used during {@link #findClass} invocations)
1516          * are determined by the lookup class' loader,
1517          * which may change due to this operation.
1518          * <p>
1519          * @param requestedLookupClass the desired lookup class for the new lookup object
1520          * @return a lookup object which reports the desired lookup class, or the same object
1521          * if there is no change
1522          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1523          * @throws NullPointerException if the argument is null
1524          *
1525          * @revised 9
1526          * @spec JPMS
1527          * @see #accessClass(Class)
1528          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1529          */
1530         public Lookup in(Class<?> requestedLookupClass) {
1531             Objects.requireNonNull(requestedLookupClass);
1532             if (requestedLookupClass.isPrimitive())
1533                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1534             if (requestedLookupClass.isArray())
1535                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1536 
1537             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1538                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1539             if (requestedLookupClass == this.lookupClass)
1540                 return this;  // keep same capabilities
1541             int newModes = (allowedModes & FULL_POWER_MODES);
1542             Module fromModule = this.lookupClass.getModule();
1543             Module targetModule = requestedLookupClass.getModule();
1544             Class<?> plc = this.previousLookupClass();
1545             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1546                 assert plc == null;
1547                 newModes = UNCONDITIONAL;
1548             } else if (fromModule != targetModule) {
1549                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1550                     // allow hopping back and forth between fromModule and plc's module
1551                     // but not the third module
1552                     newModes = 0;
1553                 }
1554                 // drop MODULE access
1555                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1556                 // teleport from this lookup class
1557                 plc = this.lookupClass;
1558             }
1559             if ((newModes & PACKAGE) != 0
1560                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1561                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1562             }
1563             // Allow nestmate lookups to be created without special privilege:
1564             if ((newModes & PRIVATE) != 0
1565                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1566                 newModes &= ~(PRIVATE|PROTECTED);
1567             }
1568             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1569                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1570                 // The requested class it not accessible from the lookup class.
1571                 // No permissions.
1572                 newModes = 0;
1573             }
1574             return newLookup(requestedLookupClass, plc, newModes);
1575         }
1576 
1577         /**
1578          * Creates a lookup on the same lookup class which this lookup object
1579          * finds members, but with a lookup mode that has lost the given lookup mode.
1580          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1581          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1582          * {@link #PRIVATE PRIVATE}, or {@link #UNCONDITIONAL UNCONDITIONAL}.
1583          *
1584          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1585          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1586          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1587          * lookup has no access.
1588          *
1589          * <p> If this lookup is not a public lookup, then the following applies
1590          * regardless of its {@linkplain #lookupModes() lookup modes}.
1591          * {@link #PROTECTED PROTECTED} is always dropped and so the resulting lookup
1592          * mode will never have this access capability. When dropping {@code PACKAGE}
1593          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1594          * access. When dropping {@code MODULE} then the resulting lookup will not
1595          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1596          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1597          *
1598          * @apiNote
1599          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1600          * delegate non-public access within the package of the lookup class without
1601          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1602          * A lookup with {@code MODULE} but not
1603          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1604          * the module of the lookup class without conferring package access.
1605          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1606          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1607          * to public classes accessible to both the module of the lookup class
1608          * and the module of the previous lookup class.
1609          *
1610          * @param modeToDrop the lookup mode to drop
1611          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1612          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1613          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE} or {@code UNCONDITIONAL}
1614          * @see MethodHandles#privateLookupIn
1615          * @since 9
1616          */
1617         public Lookup dropLookupMode(int modeToDrop) {
1618             int oldModes = lookupModes();
1619             int newModes = oldModes & ~(modeToDrop | PROTECTED);
1620             switch (modeToDrop) {
1621                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1622                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1623                 case PACKAGE: newModes &= ~(PRIVATE); break;
1624                 case PROTECTED:
1625                 case PRIVATE:
1626                 case UNCONDITIONAL: break;
1627                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1628             }
1629             if (newModes == oldModes) return this;  // return self if no change
1630             return newLookup(lookupClass(), previousLookupClass(), newModes);
1631         }
1632 
1633         /**
1634          * Creates a class or interface from {@code bytes}
1635          * with the same class loader and in the same runtime package and
1636          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1637          * {@linkplain #lookupClass() lookup class} as if calling
1638          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1639          * ClassLoader::defineClass}.
1640          *
1641          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1642          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1643          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1644          * that the lookup object was created by a caller in the runtime package (or derived
1645          * from a lookup originally created by suitably privileged code to a target class in
1646          * the runtime package). </p>
1647          *
1648          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1649          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1650          * same package as the lookup class. </p>
1651          *
1652          * <p> This method does not run the class initializer. The class initializer may
1653          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1654          * Specification</em>. </p>
1655          *
1656          * <p> If there is a security manager and this lookup does not have {@linkplain
1657          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1658          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1659          *
1660          * @param bytes the class bytes
1661          * @return the {@code Class} object for the class
1662          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1663          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1664          * @throws IllegalArgumentException the bytes are for a class in a different package
1665          * to the lookup class
1666          * @throws VerifyError if the newly created class cannot be verified
1667          * @throws LinkageError if the newly created class cannot be linked for any other reason
1668          * @throws SecurityException if a security manager is present and it
1669          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1670          * @throws NullPointerException if {@code bytes} is {@code null}
1671          * @since 9
1672          * @spec JPMS
1673          * @see Lookup#privateLookupIn
1674          * @see Lookup#dropLookupMode
1675          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1676          */
1677         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1678             ensureDefineClassPermission();
1679             if ((lookupModes() & PACKAGE) == 0)
1680                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1681             return makeClassDefiner(bytes.clone()).defineClass(false);
1682         }
1683 
1684         private void ensureDefineClassPermission() {
1685             if (allowedModes == TRUSTED)  return;
1686 
1687             if (!hasFullPrivilegeAccess()) {
1688                 SecurityManager sm = System.getSecurityManager();
1689                 if (sm != null)
1690                     sm.checkPermission(new RuntimePermission("defineClass"));
1691             }
1692         }
1693 
1694         /**
1695          * The set of class options that specify whether a hidden class created by
1696          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1697          * Lookup::defineHiddenClass} method is dynamically added as a new member
1698          * to the nest of a lookup class and/or whether a hidden class has
1699          * a strong relationship with the class loader marked as its defining loader.
1700          *
1701          * @since 15
1702          */
1703         public enum ClassOption {
1704             /**
1705              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1706              * of a lookup class as a nestmate.
1707              *
1708              * <p> A hidden nestmate class has access to the private members of all
1709              * classes and interfaces in the same nest.
1710              *
1711              * @see Class#getNestHost()
1712              */
1713             NESTMATE(NESTMATE_CLASS),
1714 
1715             /**
1716              * Specifies that a hidden class has a <em>strong</em>
1717              * relationship with the class loader marked as its defining loader,
1718              * as a normal class or interface has with its own defining loader.
1719              * This means that the hidden class may be unloaded if and only if
1720              * its defining loader is not reachable and thus may be reclaimed
1721              * by a garbage collector (JLS 12.7).
1722              *
1723              * <p> By default, a hidden class or interface may be unloaded
1724              * even if the class loader that is marked as its defining loader is
1725              * <a href="../ref/package.html#reachability">reachable</a>.
1726 
1727              *
1728              * @jls 12.7 Unloading of Classes and Interfaces
1729              */
1730             STRONG(STRONG_LOADER_LINK);
1731 
1732             /* the flag value is used by VM at define class time */
1733             private final int flag;
1734             ClassOption(int flag) {
1735                 this.flag = flag;
1736             }
1737 
1738             static int optionsToFlag(Set<ClassOption> options) {
1739                 int flags = 0;
1740                 for (ClassOption cp : options) {
1741                     flags |= cp.flag;
1742                 }
1743                 return flags;
1744             }
1745         }
1746 
1747         /**
1748          * Creates a <em>hidden</em> class or interface from {@code bytes},
1749          * returning a {@code Lookup} on the newly created class or interface.
1750          *
1751          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1752          * which either defines {@code C} directly or delegates to another class loader.
1753          * A class loader defines {@code C} directly by invoking
1754          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1755          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1756          * to derive {@code C} from a purported representation in {@code class} file format.
1757          * In situations where use of a class loader is undesirable, a class or interface
1758          * {@code C} can be created by this method instead. This method is capable of
1759          * defining {@code C}, and thereby creating it, without invoking
1760          * {@code ClassLoader::defineClass}.
1761          * Instead, this method defines {@code C} as if by arranging for
1762          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1763          * from a purported representation in {@code class} file format
1764          * using the following rules:
1765          *
1766          * <ol>
1767          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1768          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1769          * This level of access is needed to create {@code C} in the module
1770          * of the lookup class of this {@code Lookup}.</li>
1771          *
1772          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1773          * structure of a supported major and minor version. The major and minor version
1774          * may differ from the {@code class} file version of the lookup class of this
1775          * {@code Lookup}.</li>
1776          *
1777          * <li> The value of {@code this_class} must be a valid index in the
1778          * {@code constant_pool} table, and the entry at that index must be a valid
1779          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1780          * encoded in internal form that is specified by this structure. {@code N} must
1781          * denote a class or interface in the same package as the lookup class.</li>
1782          *
1783          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1784          * where {@code <suffix>} is an unqualified name.
1785          *
1786          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1787          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1788          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1789          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1790          * refers to the new {@code CONSTANT_Utf8_info} structure.
1791          *
1792          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1793          *
1794          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1795          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1796          * with the following adjustments:
1797          * <ul>
1798          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1799          * that includes a single {@code "."} character, even though this is not a valid
1800          * binary class or interface name in internal form.</li>
1801          *
1802          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1803          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1804          *
1805          * <li> {@code C} is considered to have the same runtime
1806          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1807          * and {@linkplain java.security.ProtectionDomain protection domain}
1808          * as the lookup class of this {@code Lookup}.
1809          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1810          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1811          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1812          * <ul>
1813          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1814          *      even though this is not a valid binary class or interface name.</li>
1815          * <li> {@link Class#descriptorString()} returns the string
1816          *      {@code "L" + N + "." + <suffix> + ";"},
1817          *      even though this is not a valid type descriptor name.</li>
1818          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
1819          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
1820          * </ul>
1821          * </ul>
1822          * </li>
1823          * </ol>
1824          *
1825          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1826          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
1827          * <ul>
1828          * <li> During verification, whenever it is necessary to load the class named
1829          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
1830          * made of any class loader.</li>
1831          *
1832          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
1833          * by {@code this_class}, the symbolic reference is considered to be resolved to
1834          * {@code C} and resolution always succeeds immediately.</li>
1835          * </ul>
1836          *
1837          * <p> If the {@code initialize} parameter is {@code true},
1838          * then {@code C} is initialized by the Java Virtual Machine.
1839          *
1840          * <p> The newly created class or interface {@code C} serves as the
1841          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
1842          * returned by this method. {@code C} is <em>hidden</em> in the sense that
1843          * no other class or interface can refer to {@code C} via a constant pool entry.
1844          * That is, a hidden class or interface cannot be named as a supertype, a field type,
1845          * a method parameter type, or a method return type by any other class.
1846          * This is because a hidden class or interface does not have a binary name, so
1847          * there is no internal form available to record in any class's constant pool.
1848          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
1849          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
1850          * is not {@linkplain java.lang.instrument.Instrumentation#isModifiableClass(Class)
1851          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
1852          * JVM Tool Interface</a>.
1853          *
1854          * <p> A class or interface created by
1855          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1856          * a class loader} has a strong relationship with that class loader.
1857          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
1858          * that {@linkplain Class#getClassLoader() defined it}.
1859          * This means that a class created by a class loader may be unloaded if and
1860          * only if its defining loader is not reachable and thus may be reclaimed
1861          * by a garbage collector (JLS 12.7).
1862          *
1863          * By default, however, a hidden class or interface may be unloaded even if
1864          * the class loader that is marked as its defining loader is
1865          * <a href="../ref/package.html#reachability">reachable</a>.
1866          * This behavior is useful when a hidden class or interface serves multiple
1867          * classes defined by arbitrary class loaders.  In other cases, a hidden
1868          * class or interface may be linked to a single class (or a small number of classes)
1869          * with the same defining loader as the hidden class or interface.
1870          * In such cases, where the hidden class or interface must be coterminous
1871          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
1872          * option may be passed in {@code options}.
1873          * This arranges for a hidden class to have the same strong relationship
1874          * with the class loader marked as its defining loader,
1875          * as a normal class or interface has with its own defining loader.
1876          *
1877          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
1878          * may still prevent a hidden class or interface from being
1879          * unloaded by ensuring that the {@code Class} object is reachable.
1880          *
1881          * <p> The unloading characteristics are set for each hidden class when it is
1882          * defined, and cannot be changed later.  An advantage of allowing hidden classes
1883          * to be unloaded independently of the class loader marked as their defining loader
1884          * is that a very large number of hidden classes may be created by an application.
1885          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
1886          * just as if normal classes were created by class loaders.
1887          *
1888          * <p> Classes and interfaces in a nest are allowed to have mutual access to
1889          * their private members.  The nest relationship is determined by
1890          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
1891          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
1892          * By default, a hidden class belongs to a nest consisting only of itself
1893          * because a hidden class has no binary name.
1894          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
1895          * to create a hidden class or interface {@code C} as a member of a nest.
1896          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
1897          * in the {@code ClassFile} structure from which {@code C} was derived.
1898          * Instead, the following rules determine the nest host of {@code C}:
1899          * <ul>
1900          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
1901          *     been determined, then let {@code H} be the nest host of the lookup class.
1902          *     Otherwise, the nest host of the lookup class is determined using the
1903          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
1904          * <li>The nest host of {@code C} is determined to be {@code H},
1905          *     the nest host of the lookup class.</li>
1906          * </ul>
1907          *
1908          * <p> A hidden class or interface may be serializable, but this requires a custom
1909          * serialization mechanism in order to ensure that instances are properly serialized
1910          * and deserialized. The default serialization mechanism supports only classes and
1911          * interfaces that are discoverable by their class name.
1912          *
1913          * @param bytes the bytes that make up the class data,
1914          * in the format of a valid {@code class} file as defined by
1915          * <cite>The Java Virtual Machine Specification</cite>.
1916          * @param initialize if {@code true} the class will be initialized.
1917          * @param options {@linkplain ClassOption class options}
1918          * @return the {@code Lookup} object on the hidden class
1919          *
1920          * @throws IllegalAccessException if this {@code Lookup} does not have
1921          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
1922          * @throws SecurityException if a security manager is present and it
1923          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1924          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1925          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
1926          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
1927          * {@bytes} denotes a class in a different package than the lookup class
1928          * @throws IncompatibleClassChangeError if the class or interface named as
1929          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
1930          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
1931          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
1932          * {@code C} is {@code C} itself
1933          * @throws VerifyError if the newly created class cannot be verified
1934          * @throws LinkageError if the newly created class cannot be linked for any other reason
1935          * @throws NullPointerException if any parameter is {@code null}
1936          *
1937          * @since 15
1938          * @see Class#isHidden()
1939          * @jvms 4.2.1 Binary Class and Interface Names
1940          * @jvms 4.2.2 Unqualified Names
1941          * @jvms 4.7.28 The {@code NestHost} Attribute
1942          * @jvms 4.7.29 The {@code NestMembers} Attribute
1943          * @jvms 5.4.3.1 Class and Interface Resolution
1944          * @jvms 5.4.4 Access Control
1945          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
1946          * @jvms 5.4 Linking
1947          * @jvms 5.5 Initialization
1948          * @jls 12.7 Unloading of Classes and Interfaces
1949          */
1950         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
1951                 throws IllegalAccessException
1952         {
1953             Objects.requireNonNull(bytes);
1954             Objects.requireNonNull(options);
1955 
1956             ensureDefineClassPermission();
1957             if (!hasFullPrivilegeAccess()) {
1958                 throw new IllegalAccessException(this + " does not have full privilege access");
1959             }
1960 
1961             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
1962         }
1963 
1964         /**
1965          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
1966          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
1967          * returning a {@code Lookup} on the newly created class or interface.
1968          *
1969          * <p> This method is equivalent to calling
1970          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, true, options)}
1971          * as if the hidden class has a private static final unnamed field whose value
1972          * is initialized to {@code classData} right before the class initializer is
1973          * executed.  The newly created class is linked and initialized by the Java
1974          * Virtual Machine.
1975          *
1976          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
1977          * method can be used to retrieve the {@code classData}.
1978          *
1979          * @param bytes     the class bytes
1980          * @param classData pre-initialized class data
1981          * @param options   {@linkplain ClassOption class options}
1982          * @return the {@code Lookup} object on the hidden class
1983          *
1984          * @throws IllegalAccessException if this {@code Lookup} does not have
1985          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
1986          * @throws SecurityException if a security manager is present and it
1987          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1988          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1989          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
1990          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
1991          * {@bytes} denotes a class in a different package than the lookup class
1992          * @throws IncompatibleClassChangeError if the class or interface named as
1993          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
1994          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
1995          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
1996          * {@code C} is {@code C} itself
1997          * @throws VerifyError if the newly created class cannot be verified
1998          * @throws LinkageError if the newly created class cannot be linked for any other reason
1999          * @throws NullPointerException if any parameter is {@code null}
2000          *
2001          * @since 15
2002          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2003          * @see Class#isHidden()
2004          */
2005         /* package-private */ Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, ClassOption... options)
2006                 throws IllegalAccessException
2007         {
2008             Objects.requireNonNull(bytes);
2009             Objects.requireNonNull(classData);
2010             Objects.requireNonNull(options);
2011 
2012             ensureDefineClassPermission();
2013             if (!hasFullPrivilegeAccess()) {
2014                 throw new IllegalAccessException(this + " does not have full privilege access");
2015             }
2016 
2017             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2018                        .defineClassAsLookup(true, classData);
2019         }
2020 
2021         /*
2022          * Validates the given bytes to be a class or interface and the class name
2023          * is in the same package as the lookup class.
2024          *
2025          * This method returns the class name.
2026          */
2027         private String validateAndGetClassName(byte[] bytes) {
2028             try {
2029                 ClassReader reader = new ClassReader(bytes);
2030                 if ((reader.getAccess() & Opcodes.ACC_MODULE) != 0) {
2031                     throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2032                 }
2033                 String name = reader.getClassName().replace('/', '.');
2034                 int index = name.lastIndexOf('.');
2035                 String pn = (index == -1) ? "" : name.substring(0, index);
2036                 if (!pn.equals(lookupClass.getPackageName())) {
2037                     throw newIllegalArgumentException(name + " not in same package as lookup class: " +
2038                             lookupClass.getName());
2039                 }
2040                 return name;
2041             } catch (IllegalArgumentException e) {
2042                 throw e;
2043             } catch (RuntimeException e) {
2044                 // ASM exceptions are poorly specified
2045                 ClassFormatError cfe = new ClassFormatError();
2046                 cfe.initCause(e);
2047                 throw cfe;
2048             }
2049         }
2050 
2051 
2052         /*
2053          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2054          * from the given bytes.
2055          *
2056          * Caller should make a defensive copy of the arguments if needed
2057          * before calling this factory method.
2058          *
2059          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2060          * {@bytes} denotes a class in a different package than the lookup class
2061          */
2062         private ClassDefiner makeClassDefiner(byte[] bytes) {
2063             return new ClassDefiner(this, validateAndGetClassName(bytes), bytes, STRONG_LOADER_LINK);
2064         }
2065 
2066         /**
2067          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2068          * from the given bytes.  The name must be in the same package as the lookup class.
2069          *
2070          * Caller should make a defensive copy of the arguments if needed
2071          * before calling this factory method.
2072          *
2073          * @param bytes   class bytes
2074          * @return ClassDefiner that defines a hidden class of the given bytes.
2075          *
2076          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2077          * {@bytes} denotes a class in a different package than the lookup class
2078          */
2079         ClassDefiner makeHiddenClassDefiner(byte[] bytes) {
2080             return makeHiddenClassDefiner(validateAndGetClassName(bytes), bytes, Set.of(), false);
2081         }
2082 
2083         /**
2084          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2085          * from the given bytes and options.
2086          * The name must be in the same package as the lookup class.
2087          *
2088          * Caller should make a defensive copy of the arguments if needed
2089          * before calling this factory method.
2090          *
2091          * @param bytes   class bytes
2092          * @param options class options
2093          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2094          * @return ClassDefiner that defines a hidden class of the given bytes and options
2095          *
2096          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2097          * {@bytes} denotes a class in a different package than the lookup class
2098          */
2099         ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2100                                             Set<ClassOption> options,
2101                                             boolean accessVmAnnotations) {
2102             return makeHiddenClassDefiner(validateAndGetClassName(bytes), bytes, options, accessVmAnnotations);
2103         }
2104 
2105         /**
2106          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2107          * from the given bytes.  No package name check on the given name.
2108          *
2109          * @param name    fully-qualified name that specifies the prefix of the hidden class
2110          * @param bytes   class bytes
2111          * @return ClassDefiner that defines a hidden class of the given bytes.
2112          */
2113         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes) {
2114             return makeHiddenClassDefiner(name, bytes, Set.of(), false);
2115         }
2116 
2117         /**
2118          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2119          * from the given bytes and options.  No package name check on the given name.
2120          *
2121          * @param name the name of the class and the name in the class bytes is ignored.
2122          * @param bytes class bytes
2123          * @param options class options
2124          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2125          */
2126         ClassDefiner makeHiddenClassDefiner(String name,
2127                                             byte[] bytes,
2128                                             Set<ClassOption> options,
2129                                             boolean accessVmAnnotations) {
2130             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2131             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2132                 // jdk.internal.vm.annotations are permitted for classes
2133                 // defined to boot loader and platform loader
2134                 flags |= ACCESS_VM_ANNOTATIONS;
2135             }
2136 
2137             return new ClassDefiner(this, name, bytes, flags);
2138         }
2139 
2140         static class ClassDefiner {
2141             private final Lookup lookup;
2142             private final String name;
2143             private final byte[] bytes;
2144             private final int classFlags;
2145 
2146             private ClassDefiner(Lookup lookup, String name, byte[] bytes, int flags) {
2147                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2148                 this.lookup = lookup;
2149                 this.bytes = bytes;
2150                 this.classFlags = flags;
2151                 this.name = name;
2152             }
2153 
2154             String className() {
2155                 return name;
2156             }
2157 
2158             Class<?> defineClass(boolean initialize) {
2159                 return defineClass(initialize, null);
2160             }
2161 
2162             Lookup defineClassAsLookup(boolean initialize) {
2163                 Class<?> c = defineClass(initialize, null);
2164                 return new Lookup(c, null, FULL_POWER_MODES);
2165             }
2166 
2167             /**
2168              * Defines the class of the given bytes and the given classData.
2169              * If {@code initialize} parameter is true, then the class will be initialized.
2170              *
2171              * @param initialize true if the class to be initialized
2172              * @param classData classData or null
2173              * @return the class
2174              *
2175              * @throws LinkageError linkage error
2176              */
2177             Class<?> defineClass(boolean initialize, Object classData) {
2178                 Class<?> lookupClass = lookup.lookupClass();
2179                 ClassLoader loader = lookupClass.getClassLoader();
2180                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2181                 Class<?> c = JLA.defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2182                 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2183                 return c;
2184             }
2185 
2186             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2187                 // initialize must be true if classData is non-null
2188                 assert classData == null || initialize == true;
2189                 Class<?> c = defineClass(initialize, classData);
2190                 return new Lookup(c, null, FULL_POWER_MODES);
2191             }
2192 
2193             private boolean isNestmate() {
2194                 return (classFlags & NESTMATE_CLASS) != 0;
2195             }
2196         }
2197 
2198         private ProtectionDomain lookupClassProtectionDomain() {
2199             ProtectionDomain pd = cachedProtectionDomain;
2200             if (pd == null) {
2201                 cachedProtectionDomain = pd = JLA.protectionDomain(lookupClass);
2202             }
2203             return pd;
2204         }
2205 
2206         // cached protection domain
2207         private volatile ProtectionDomain cachedProtectionDomain;
2208 
2209         // Make sure outer class is initialized first.
2210         static { IMPL_NAMES.getClass(); }
2211 
2212         /** Package-private version of lookup which is trusted. */
2213         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2214 
2215         /** Version of lookup which is trusted minimally.
2216          *  It can only be used to create method handles to publicly accessible
2217          *  members in packages that are exported unconditionally.
2218          */
2219         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2220 
2221         static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
2222 
2223         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2224             String name = lookupClass.getName();
2225             if (name.startsWith("java.lang.invoke."))
2226                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2227         }
2228 
2229         /**
2230          * Displays the name of the class from which lookups are to be made.
2231          * followed with "/" and the name of the {@linkplain #previousLookupClass()
2232          * previous lookup class} if present.
2233          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2234          * If there are restrictions on the access permitted to this lookup,
2235          * this is indicated by adding a suffix to the class name, consisting
2236          * of a slash and a keyword.  The keyword represents the strongest
2237          * allowed access, and is chosen as follows:
2238          * <ul>
2239          * <li>If no access is allowed, the suffix is "/noaccess".
2240          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2241          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2242          * <li>If only public and module access are allowed, the suffix is "/module".
2243          * <li>If public and package access are allowed, the suffix is "/package".
2244          * <li>If public, package, and private access are allowed, the suffix is "/private".
2245          * </ul>
2246          * If none of the above cases apply, it is the case that full access
2247          * (public, module, package, private, and protected) is allowed.
2248          * In this case, no suffix is added.
2249          * This is true only of an object obtained originally from
2250          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2251          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2252          * always have restricted access, and will display a suffix.
2253          * <p>
2254          * (It may seem strange that protected access should be
2255          * stronger than private access.  Viewed independently from
2256          * package access, protected access is the first to be lost,
2257          * because it requires a direct subclass relationship between
2258          * caller and callee.)
2259          * @see #in
2260          *
2261          * @revised 9
2262          * @spec JPMS
2263          */
2264         @Override
2265         public String toString() {
2266             String cname = lookupClass.getName();
2267             if (prevLookupClass != null)
2268                 cname += "/" + prevLookupClass.getName();
2269             switch (allowedModes) {
2270             case 0:  // no privileges
2271                 return cname + "/noaccess";
2272             case UNCONDITIONAL:
2273                 return cname + "/publicLookup";
2274             case PUBLIC:
2275                 return cname + "/public";
2276             case PUBLIC|MODULE:
2277                 return cname + "/module";
2278             case PUBLIC|PACKAGE:
2279             case PUBLIC|MODULE|PACKAGE:
2280                 return cname + "/package";
2281             case FULL_POWER_MODES & (~PROTECTED):
2282             case FULL_POWER_MODES & ~(PROTECTED|MODULE):
2283                 return cname + "/private";
2284             case FULL_POWER_MODES:
2285             case FULL_POWER_MODES & (~MODULE):
2286                 return cname;
2287             case TRUSTED:
2288                 return "/trusted";  // internal only; not exported
2289             default:  // Should not happen, but it's a bitfield...
2290                 cname = cname + "/" + Integer.toHexString(allowedModes);
2291                 assert(false) : cname;
2292                 return cname;
2293             }
2294         }
2295 
2296         /**
2297          * Produces a method handle for a static method.
2298          * The type of the method handle will be that of the method.
2299          * (Since static methods do not take receivers, there is no
2300          * additional receiver argument inserted into the method handle type,
2301          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2302          * The method and all its argument types must be accessible to the lookup object.
2303          * <p>
2304          * The returned method handle will have
2305          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2306          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2307          * <p>
2308          * If the returned method handle is invoked, the method's class will
2309          * be initialized, if it has not already been initialized.
2310          * <p><b>Example:</b>
2311          * <blockquote><pre>{@code
2312 import static java.lang.invoke.MethodHandles.*;
2313 import static java.lang.invoke.MethodType.*;
2314 ...
2315 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2316   "asList", methodType(List.class, Object[].class));
2317 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2318          * }</pre></blockquote>
2319          * @param refc the class from which the method is accessed
2320          * @param name the name of the method
2321          * @param type the type of the method
2322          * @return the desired method handle
2323          * @throws NoSuchMethodException if the method does not exist
2324          * @throws IllegalAccessException if access checking fails,
2325          *                                or if the method is not {@code static},
2326          *                                or if the method's variable arity modifier bit
2327          *                                is set and {@code asVarargsCollector} fails
2328          * @throws    SecurityException if a security manager is present and it
2329          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2330          * @throws NullPointerException if any argument is null
2331          */
2332         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2333             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2334             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2335         }
2336 
2337         /**
2338          * Produces a method handle for a virtual method.
2339          * The type of the method handle will be that of the method,
2340          * with the receiver type (usually {@code refc}) prepended.
2341          * The method and all its argument types must be accessible to the lookup object.
2342          * <p>
2343          * When called, the handle will treat the first argument as a receiver
2344          * and, for non-private methods, dispatch on the receiver's type to determine which method
2345          * implementation to enter.
2346          * For private methods the named method in {@code refc} will be invoked on the receiver.
2347          * (The dispatching action is identical with that performed by an
2348          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2349          * <p>
2350          * The first argument will be of type {@code refc} if the lookup
2351          * class has full privileges to access the member.  Otherwise
2352          * the member must be {@code protected} and the first argument
2353          * will be restricted in type to the lookup class.
2354          * <p>
2355          * The returned method handle will have
2356          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2357          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2358          * <p>
2359          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2360          * instructions and method handles produced by {@code findVirtual},
2361          * if the class is {@code MethodHandle} and the name string is
2362          * {@code invokeExact} or {@code invoke}, the resulting
2363          * method handle is equivalent to one produced by
2364          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2365          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2366          * with the same {@code type} argument.
2367          * <p>
2368          * If the class is {@code VarHandle} and the name string corresponds to
2369          * the name of a signature-polymorphic access mode method, the resulting
2370          * method handle is equivalent to one produced by
2371          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2372          * the access mode corresponding to the name string and with the same
2373          * {@code type} arguments.
2374          * <p>
2375          * <b>Example:</b>
2376          * <blockquote><pre>{@code
2377 import static java.lang.invoke.MethodHandles.*;
2378 import static java.lang.invoke.MethodType.*;
2379 ...
2380 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2381   "concat", methodType(String.class, String.class));
2382 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2383   "hashCode", methodType(int.class));
2384 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2385   "hashCode", methodType(int.class));
2386 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2387 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2388 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2389 // interface method:
2390 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2391   "subSequence", methodType(CharSequence.class, int.class, int.class));
2392 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2393 // constructor "internal method" must be accessed differently:
2394 MethodType MT_newString = methodType(void.class); //()V for new String()
2395 try { assertEquals("impossible", lookup()
2396         .findVirtual(String.class, "<init>", MT_newString));
2397  } catch (NoSuchMethodException ex) { } // OK
2398 MethodHandle MH_newString = publicLookup()
2399   .findConstructor(String.class, MT_newString);
2400 assertEquals("", (String) MH_newString.invokeExact());
2401          * }</pre></blockquote>
2402          *
2403          * @param refc the class or interface from which the method is accessed
2404          * @param name the name of the method
2405          * @param type the type of the method, with the receiver argument omitted
2406          * @return the desired method handle
2407          * @throws NoSuchMethodException if the method does not exist
2408          * @throws IllegalAccessException if access checking fails,
2409          *                                or if the method is {@code static},
2410          *                                or if the method's variable arity modifier bit
2411          *                                is set and {@code asVarargsCollector} fails
2412          * @throws    SecurityException if a security manager is present and it
2413          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2414          * @throws NullPointerException if any argument is null
2415          */
2416         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2417             if (refc == MethodHandle.class) {
2418                 MethodHandle mh = findVirtualForMH(name, type);
2419                 if (mh != null)  return mh;
2420             } else if (refc == VarHandle.class) {
2421                 MethodHandle mh = findVirtualForVH(name, type);
2422                 if (mh != null)  return mh;
2423             }
2424             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2425             MemberName method = resolveOrFail(refKind, refc, name, type);
2426             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2427         }
2428         private MethodHandle findVirtualForMH(String name, MethodType type) {
2429             // these names require special lookups because of the implicit MethodType argument
2430             if ("invoke".equals(name))
2431                 return invoker(type);
2432             if ("invokeExact".equals(name))
2433                 return exactInvoker(type);
2434             assert(!MemberName.isMethodHandleInvokeName(name));
2435             return null;
2436         }
2437         private MethodHandle findVirtualForVH(String name, MethodType type) {
2438             try {
2439                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2440             } catch (IllegalArgumentException e) {
2441                 return null;
2442             }
2443         }
2444 
2445         /**
2446          * Produces a method handle which creates an object and initializes it, using
2447          * the constructor of the specified type.
2448          * The parameter types of the method handle will be those of the constructor,
2449          * while the return type will be a reference to the constructor's class.
2450          * The constructor and all its argument types must be accessible to the lookup object.
2451          * <p>
2452          * The requested type must have a return type of {@code void}.
2453          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2454          * <p>
2455          * The returned method handle will have
2456          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2457          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2458          * <p>
2459          * If the returned method handle is invoked, the constructor's class will
2460          * be initialized, if it has not already been initialized.
2461          * <p><b>Example:</b>
2462          * <blockquote><pre>{@code
2463 import static java.lang.invoke.MethodHandles.*;
2464 import static java.lang.invoke.MethodType.*;
2465 ...
2466 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2467   ArrayList.class, methodType(void.class, Collection.class));
2468 Collection orig = Arrays.asList("x", "y");
2469 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2470 assert(orig != copy);
2471 assertEquals(orig, copy);
2472 // a variable-arity constructor:
2473 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2474   ProcessBuilder.class, methodType(void.class, String[].class));
2475 ProcessBuilder pb = (ProcessBuilder)
2476   MH_newProcessBuilder.invoke("x", "y", "z");
2477 assertEquals("[x, y, z]", pb.command().toString());
2478          * }</pre></blockquote>
2479          * @param refc the class or interface from which the method is accessed
2480          * @param type the type of the method, with the receiver argument omitted, and a void return type
2481          * @return the desired method handle
2482          * @throws NoSuchMethodException if the constructor does not exist
2483          * @throws IllegalAccessException if access checking fails
2484          *                                or if the method's variable arity modifier bit
2485          *                                is set and {@code asVarargsCollector} fails
2486          * @throws    SecurityException if a security manager is present and it
2487          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2488          * @throws NullPointerException if any argument is null
2489          */
2490         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2491             if (refc.isArray()) {
2492                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2493             }
2494             String name = "<init>";
2495             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2496             return getDirectConstructor(refc, ctor);
2497         }
2498 
2499         /**
2500          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2501          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2502          * Such a resolution, as specified in JVMS 5.4.3.1 section, attempts to locate and load the class,
2503          * and then determines whether the class is accessible to this lookup object.
2504          * <p>
2505          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2506          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2507          *
2508          * @param targetName the fully qualified name of the class to be looked up.
2509          * @return the requested class.
2510          * @throws SecurityException if a security manager is present and it
2511          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2512          * @throws LinkageError if the linkage fails
2513          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2514          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2515          * modes.
2516          * @since 9
2517          * @jvms 5.4.3.1 Class and Interface Resolution
2518          */
2519         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2520             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2521             return accessClass(targetClass);
2522         }
2523 
2524         /**
2525          * Determines if a class can be accessed from the lookup context defined by
2526          * this {@code Lookup} object. The static initializer of the class is not run.
2527          * <p>
2528          * If the {@code targetClass} is in the same module as the lookup class,
2529          * the lookup class is {@code LC} in module {@code M1} and
2530          * the previous lookup class is in module {@code M0} or
2531          * {@code null} if not present,
2532          * {@code targetClass} is accessible if and only if one of the following is true:
2533          * <ul>
2534          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2535          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2536          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2537          *     in the same runtime package of {@code LC}.</li>
2538          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2539          *     a public type in {@code M1}.</li>
2540          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2541          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2542          *     if the previous lookup class is present; otherwise, {@code targetClass}
2543          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2544          * </ul>
2545          *
2546          * <p>
2547          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2548          * can access public types in all modules when the type is in a package
2549          * that is exported unconditionally.
2550          * <p>
2551          * Otherwise, the target class is in a different module from {@code lookupClass},
2552          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2553          * is inaccessible.
2554          * <p>
2555          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2556          * {@code M1} is the module containing {@code lookupClass} and
2557          * {@code M2} is the module containing {@code targetClass},
2558          * then {@code targetClass} is accessible if and only if
2559          * <ul>
2560          * <li>{@code M1} reads {@code M2}, and
2561          * <li>{@code targetClass} is public and in a package exported by
2562          *     {@code M2} at least to {@code M1}.
2563          * </ul>
2564          * <p>
2565          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2566          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2567          * containing the previous lookup class, then {@code targetClass} is accessible
2568          * if and only if one of the following is true:
2569          * <ul>
2570          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2571          *     {@linkplain Module#reads reads} {@code M0} and the type is
2572          *     in a package that is exported to at least {@code M1}.
2573          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2574          *     {@linkplain Module#reads reads} {@code M1} and the type is
2575          *     in a package that is exported to at least {@code M0}.
2576          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2577          *     and {@code M1} reads {@code M2} and the type is in a package
2578          *     that is exported to at least both {@code M0} and {@code M2}.
2579          * </ul>
2580          * <p>
2581          * Otherwise, {@code targetClass} is not accessible.
2582          *
2583          * @param targetClass the class to be access-checked
2584          * @return the class that has been access-checked
2585          * @throws IllegalAccessException if the class is not accessible from the lookup class
2586          * and previous lookup class, if present, using the allowed access modes.
2587          * @throws    SecurityException if a security manager is present and it
2588          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2589          * @since 9
2590          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
2591          */
2592         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
2593             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2594                 throw new MemberName(targetClass).makeAccessException("access violation", this);
2595             }
2596             checkSecurityManager(targetClass, null);
2597             return targetClass;
2598         }
2599 
2600         /**
2601          * Produces an early-bound method handle for a virtual method.
2602          * It will bypass checks for overriding methods on the receiver,
2603          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
2604          * instruction from within the explicitly specified {@code specialCaller}.
2605          * The type of the method handle will be that of the method,
2606          * with a suitably restricted receiver type prepended.
2607          * (The receiver type will be {@code specialCaller} or a subtype.)
2608          * The method and all its argument types must be accessible
2609          * to the lookup object.
2610          * <p>
2611          * Before method resolution,
2612          * if the explicitly specified caller class is not identical with the
2613          * lookup class, or if this lookup object does not have
2614          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
2615          * privileges, the access fails.
2616          * <p>
2617          * The returned method handle will have
2618          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2619          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2620          * <p style="font-size:smaller;">
2621          * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
2622          * even though the {@code invokespecial} instruction can refer to them
2623          * in special circumstances.  Use {@link #findConstructor findConstructor}
2624          * to access instance initialization methods in a safe manner.)</em>
2625          * <p><b>Example:</b>
2626          * <blockquote><pre>{@code
2627 import static java.lang.invoke.MethodHandles.*;
2628 import static java.lang.invoke.MethodType.*;
2629 ...
2630 static class Listie extends ArrayList {
2631   public String toString() { return "[wee Listie]"; }
2632   static Lookup lookup() { return MethodHandles.lookup(); }
2633 }
2634 ...
2635 // no access to constructor via invokeSpecial:
2636 MethodHandle MH_newListie = Listie.lookup()
2637   .findConstructor(Listie.class, methodType(void.class));
2638 Listie l = (Listie) MH_newListie.invokeExact();
2639 try { assertEquals("impossible", Listie.lookup().findSpecial(
2640         Listie.class, "<init>", methodType(void.class), Listie.class));
2641  } catch (NoSuchMethodException ex) { } // OK
2642 // access to super and self methods via invokeSpecial:
2643 MethodHandle MH_super = Listie.lookup().findSpecial(
2644   ArrayList.class, "toString" , methodType(String.class), Listie.class);
2645 MethodHandle MH_this = Listie.lookup().findSpecial(
2646   Listie.class, "toString" , methodType(String.class), Listie.class);
2647 MethodHandle MH_duper = Listie.lookup().findSpecial(
2648   Object.class, "toString" , methodType(String.class), Listie.class);
2649 assertEquals("[]", (String) MH_super.invokeExact(l));
2650 assertEquals(""+l, (String) MH_this.invokeExact(l));
2651 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
2652 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
2653         String.class, "toString", methodType(String.class), Listie.class));
2654  } catch (IllegalAccessException ex) { } // OK
2655 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
2656 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
2657          * }</pre></blockquote>
2658          *
2659          * @param refc the class or interface from which the method is accessed
2660          * @param name the name of the method (which must not be "&lt;init&gt;")
2661          * @param type the type of the method, with the receiver argument omitted
2662          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
2663          * @return the desired method handle
2664          * @throws NoSuchMethodException if the method does not exist
2665          * @throws IllegalAccessException if access checking fails,
2666          *                                or if the method is {@code static},
2667          *                                or if the method's variable arity modifier bit
2668          *                                is set and {@code asVarargsCollector} fails
2669          * @throws    SecurityException if a security manager is present and it
2670          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2671          * @throws NullPointerException if any argument is null
2672          */
2673         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
2674                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
2675             checkSpecialCaller(specialCaller, refc);
2676             Lookup specialLookup = this.in(specialCaller);
2677             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
2678             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
2679         }
2680 
2681         /**
2682          * Produces a method handle giving read access to a non-static field.
2683          * The type of the method handle will have a return type of the field's
2684          * value type.
2685          * The method handle's single argument will be the instance containing
2686          * the field.
2687          * Access checking is performed immediately on behalf of the lookup class.
2688          * @param refc the class or interface from which the method is accessed
2689          * @param name the field's name
2690          * @param type the field's type
2691          * @return a method handle which can load values from the field
2692          * @throws NoSuchFieldException if the field does not exist
2693          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
2694          * @throws    SecurityException if a security manager is present and it
2695          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2696          * @throws NullPointerException if any argument is null
2697          * @see #findVarHandle(Class, String, Class)
2698          */
2699         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
2700             MemberName field = resolveOrFail(REF_getField, refc, name, type);
2701             return getDirectField(REF_getField, refc, field);
2702         }
2703 
2704         /**
2705          * Produces a method handle giving write access to a non-static field.
2706          * The type of the method handle will have a void return type.
2707          * The method handle will take two arguments, the instance containing
2708          * the field, and the value to be stored.
2709          * The second argument will be of the field's value type.
2710          * Access checking is performed immediately on behalf of the lookup class.
2711          * @param refc the class or interface from which the method is accessed
2712          * @param name the field's name
2713          * @param type the field's type
2714          * @return a method handle which can store values into the field
2715          * @throws NoSuchFieldException if the field does not exist
2716          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
2717          *                                or {@code final}
2718          * @throws    SecurityException if a security manager is present and it
2719          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2720          * @throws NullPointerException if any argument is null
2721          * @see #findVarHandle(Class, String, Class)
2722          */
2723         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
2724             MemberName field = resolveOrFail(REF_putField, refc, name, type);
2725             return getDirectField(REF_putField, refc, field);
2726         }
2727 
2728         /**
2729          * Produces a VarHandle giving access to a non-static field {@code name}
2730          * of type {@code type} declared in a class of type {@code recv}.
2731          * The VarHandle's variable type is {@code type} and it has one
2732          * coordinate type, {@code recv}.
2733          * <p>
2734          * Access checking is performed immediately on behalf of the lookup
2735          * class.
2736          * <p>
2737          * Certain access modes of the returned VarHandle are unsupported under
2738          * the following conditions:
2739          * <ul>
2740          * <li>if the field is declared {@code final}, then the write, atomic
2741          *     update, numeric atomic update, and bitwise atomic update access
2742          *     modes are unsupported.
2743          * <li>if the field type is anything other than {@code byte},
2744          *     {@code short}, {@code char}, {@code int}, {@code long},
2745          *     {@code float}, or {@code double} then numeric atomic update
2746          *     access modes are unsupported.
2747          * <li>if the field type is anything other than {@code boolean},
2748          *     {@code byte}, {@code short}, {@code char}, {@code int} or
2749          *     {@code long} then bitwise atomic update access modes are
2750          *     unsupported.
2751          * </ul>
2752          * <p>
2753          * If the field is declared {@code volatile} then the returned VarHandle
2754          * will override access to the field (effectively ignore the
2755          * {@code volatile} declaration) in accordance to its specified
2756          * access modes.
2757          * <p>
2758          * If the field type is {@code float} or {@code double} then numeric
2759          * and atomic update access modes compare values using their bitwise
2760          * representation (see {@link Float#floatToRawIntBits} and
2761          * {@link Double#doubleToRawLongBits}, respectively).
2762          * @apiNote
2763          * Bitwise comparison of {@code float} values or {@code double} values,
2764          * as performed by the numeric and atomic update access modes, differ
2765          * from the primitive {@code ==} operator and the {@link Float#equals}
2766          * and {@link Double#equals} methods, specifically with respect to
2767          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
2768          * Care should be taken when performing a compare and set or a compare
2769          * and exchange operation with such values since the operation may
2770          * unexpectedly fail.
2771          * There are many possible NaN values that are considered to be
2772          * {@code NaN} in Java, although no IEEE 754 floating-point operation
2773          * provided by Java can distinguish between them.  Operation failure can
2774          * occur if the expected or witness value is a NaN value and it is
2775          * transformed (perhaps in a platform specific manner) into another NaN
2776          * value, and thus has a different bitwise representation (see
2777          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
2778          * details).
2779          * The values {@code -0.0} and {@code +0.0} have different bitwise
2780          * representations but are considered equal when using the primitive
2781          * {@code ==} operator.  Operation failure can occur if, for example, a
2782          * numeric algorithm computes an expected value to be say {@code -0.0}
2783          * and previously computed the witness value to be say {@code +0.0}.
2784          * @param recv the receiver class, of type {@code R}, that declares the
2785          * non-static field
2786          * @param name the field's name
2787          * @param type the field's type, of type {@code T}
2788          * @return a VarHandle giving access to non-static fields.
2789          * @throws NoSuchFieldException if the field does not exist
2790          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
2791          * @throws    SecurityException if a security manager is present and it
2792          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2793          * @throws NullPointerException if any argument is null
2794          * @since 9
2795          */
2796         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
2797             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
2798             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
2799             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
2800         }
2801 
2802         /**
2803          * Produces a method handle giving read access to a static field.
2804          * The type of the method handle will have a return type of the field's
2805          * value type.
2806          * The method handle will take no arguments.
2807          * Access checking is performed immediately on behalf of the lookup class.
2808          * <p>
2809          * If the returned method handle is invoked, the field's class will
2810          * be initialized, if it has not already been initialized.
2811          * @param refc the class or interface from which the method is accessed
2812          * @param name the field's name
2813          * @param type the field's type
2814          * @return a method handle which can load values from the field
2815          * @throws NoSuchFieldException if the field does not exist
2816          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
2817          * @throws    SecurityException if a security manager is present and it
2818          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2819          * @throws NullPointerException if any argument is null
2820          */
2821         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
2822             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
2823             return getDirectField(REF_getStatic, refc, field);
2824         }
2825 
2826         /**
2827          * Produces a method handle giving write access to a static field.
2828          * The type of the method handle will have a void return type.
2829          * The method handle will take a single
2830          * argument, of the field's value type, the value to be stored.
2831          * Access checking is performed immediately on behalf of the lookup class.
2832          * <p>
2833          * If the returned method handle is invoked, the field's class will
2834          * be initialized, if it has not already been initialized.
2835          * @param refc the class or interface from which the method is accessed
2836          * @param name the field's name
2837          * @param type the field's type
2838          * @return a method handle which can store values into the field
2839          * @throws NoSuchFieldException if the field does not exist
2840          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
2841          *                                or is {@code final}
2842          * @throws    SecurityException if a security manager is present and it
2843          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2844          * @throws NullPointerException if any argument is null
2845          */
2846         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
2847             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
2848             return getDirectField(REF_putStatic, refc, field);
2849         }
2850 
2851         /**
2852          * Produces a VarHandle giving access to a static field {@code name} of
2853          * type {@code type} declared in a class of type {@code decl}.
2854          * The VarHandle's variable type is {@code type} and it has no
2855          * coordinate types.
2856          * <p>
2857          * Access checking is performed immediately on behalf of the lookup
2858          * class.
2859          * <p>
2860          * If the returned VarHandle is operated on, the declaring class will be
2861          * initialized, if it has not already been initialized.
2862          * <p>
2863          * Certain access modes of the returned VarHandle are unsupported under
2864          * the following conditions:
2865          * <ul>
2866          * <li>if the field is declared {@code final}, then the write, atomic
2867          *     update, numeric atomic update, and bitwise atomic update access
2868          *     modes are unsupported.
2869          * <li>if the field type is anything other than {@code byte},
2870          *     {@code short}, {@code char}, {@code int}, {@code long},
2871          *     {@code float}, or {@code double}, then numeric atomic update
2872          *     access modes are unsupported.
2873          * <li>if the field type is anything other than {@code boolean},
2874          *     {@code byte}, {@code short}, {@code char}, {@code int} or
2875          *     {@code long} then bitwise atomic update access modes are
2876          *     unsupported.
2877          * </ul>
2878          * <p>
2879          * If the field is declared {@code volatile} then the returned VarHandle
2880          * will override access to the field (effectively ignore the
2881          * {@code volatile} declaration) in accordance to its specified
2882          * access modes.
2883          * <p>
2884          * If the field type is {@code float} or {@code double} then numeric
2885          * and atomic update access modes compare values using their bitwise
2886          * representation (see {@link Float#floatToRawIntBits} and
2887          * {@link Double#doubleToRawLongBits}, respectively).
2888          * @apiNote
2889          * Bitwise comparison of {@code float} values or {@code double} values,
2890          * as performed by the numeric and atomic update access modes, differ
2891          * from the primitive {@code ==} operator and the {@link Float#equals}
2892          * and {@link Double#equals} methods, specifically with respect to
2893          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
2894          * Care should be taken when performing a compare and set or a compare
2895          * and exchange operation with such values since the operation may
2896          * unexpectedly fail.
2897          * There are many possible NaN values that are considered to be
2898          * {@code NaN} in Java, although no IEEE 754 floating-point operation
2899          * provided by Java can distinguish between them.  Operation failure can
2900          * occur if the expected or witness value is a NaN value and it is
2901          * transformed (perhaps in a platform specific manner) into another NaN
2902          * value, and thus has a different bitwise representation (see
2903          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
2904          * details).
2905          * The values {@code -0.0} and {@code +0.0} have different bitwise
2906          * representations but are considered equal when using the primitive
2907          * {@code ==} operator.  Operation failure can occur if, for example, a
2908          * numeric algorithm computes an expected value to be say {@code -0.0}
2909          * and previously computed the witness value to be say {@code +0.0}.
2910          * @param decl the class that declares the static field
2911          * @param name the field's name
2912          * @param type the field's type, of type {@code T}
2913          * @return a VarHandle giving access to a static field
2914          * @throws NoSuchFieldException if the field does not exist
2915          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
2916          * @throws    SecurityException if a security manager is present and it
2917          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2918          * @throws NullPointerException if any argument is null
2919          * @since 9
2920          */
2921         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
2922             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
2923             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
2924             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
2925         }
2926 
2927         /**
2928          * Produces an early-bound method handle for a non-static method.
2929          * The receiver must have a supertype {@code defc} in which a method
2930          * of the given name and type is accessible to the lookup class.
2931          * The method and all its argument types must be accessible to the lookup object.
2932          * The type of the method handle will be that of the method,
2933          * without any insertion of an additional receiver parameter.
2934          * The given receiver will be bound into the method handle,
2935          * so that every call to the method handle will invoke the
2936          * requested method on the given receiver.
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          * <em>and</em> the trailing array argument is not the only argument.
2942          * (If the trailing array argument is the only argument,
2943          * the given receiver value will be bound to it.)
2944          * <p>
2945          * This is almost equivalent to the following code, with some differences noted below:
2946          * <blockquote><pre>{@code
2947 import static java.lang.invoke.MethodHandles.*;
2948 import static java.lang.invoke.MethodType.*;
2949 ...
2950 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
2951 MethodHandle mh1 = mh0.bindTo(receiver);
2952 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
2953 return mh1;
2954          * }</pre></blockquote>
2955          * where {@code defc} is either {@code receiver.getClass()} or a super
2956          * type of that class, in which the requested method is accessible
2957          * to the lookup class.
2958          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
2959          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
2960          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
2961          * the receiver is restricted by {@code findVirtual} to the lookup class.)
2962          * @param receiver the object from which the method is accessed
2963          * @param name the name of the method
2964          * @param type the type of the method, with the receiver argument omitted
2965          * @return the desired method handle
2966          * @throws NoSuchMethodException if the method does not exist
2967          * @throws IllegalAccessException if access checking fails
2968          *                                or if the method's variable arity modifier bit
2969          *                                is set and {@code asVarargsCollector} fails
2970          * @throws    SecurityException if a security manager is present and it
2971          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2972          * @throws NullPointerException if any argument is null
2973          * @see MethodHandle#bindTo
2974          * @see #findVirtual
2975          */
2976         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2977             Class<? extends Object> refc = receiver.getClass(); // may get NPE
2978             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
2979             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
2980             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
2981                 throw new IllegalAccessException("The restricted defining class " +
2982                                                  mh.type().leadingReferenceParameter().getName() +
2983                                                  " is not assignable from receiver class " +
2984                                                  receiver.getClass().getName());
2985             }
2986             return mh.bindArgumentL(0, receiver).setVarargs(method);
2987         }
2988 
2989         /**
2990          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
2991          * to <i>m</i>, if the lookup class has permission.
2992          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
2993          * If <i>m</i> is virtual, overriding is respected on every call.
2994          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
2995          * The type of the method handle will be that of the method,
2996          * with the receiver type prepended (but only if it is non-static).
2997          * If the method's {@code accessible} flag is not set,
2998          * access checking is performed immediately on behalf of the lookup class.
2999          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3000          * <p>
3001          * The returned method handle will have
3002          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3003          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3004          * <p>
3005          * If <i>m</i> is static, and
3006          * if the returned method handle is invoked, the method's class will
3007          * be initialized, if it has not already been initialized.
3008          * @param m the reflected method
3009          * @return a method handle which can invoke the reflected method
3010          * @throws IllegalAccessException if access checking fails
3011          *                                or if the method's variable arity modifier bit
3012          *                                is set and {@code asVarargsCollector} fails
3013          * @throws NullPointerException if the argument is null
3014          */
3015         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3016             if (m.getDeclaringClass() == MethodHandle.class) {
3017                 MethodHandle mh = unreflectForMH(m);
3018                 if (mh != null)  return mh;
3019             }
3020             if (m.getDeclaringClass() == VarHandle.class) {
3021                 MethodHandle mh = unreflectForVH(m);
3022                 if (mh != null)  return mh;
3023             }
3024             MemberName method = new MemberName(m);
3025             byte refKind = method.getReferenceKind();
3026             if (refKind == REF_invokeSpecial)
3027                 refKind = REF_invokeVirtual;
3028             assert(method.isMethod());
3029             @SuppressWarnings("deprecation")
3030             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3031             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3032         }
3033         private MethodHandle unreflectForMH(Method m) {
3034             // these names require special lookups because they throw UnsupportedOperationException
3035             if (MemberName.isMethodHandleInvokeName(m.getName()))
3036                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3037             return null;
3038         }
3039         private MethodHandle unreflectForVH(Method m) {
3040             // these names require special lookups because they throw UnsupportedOperationException
3041             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3042                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3043             return null;
3044         }
3045 
3046         /**
3047          * Produces a method handle for a reflected method.
3048          * It will bypass checks for overriding methods on the receiver,
3049          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3050          * instruction from within the explicitly specified {@code specialCaller}.
3051          * The type of the method handle will be that of the method,
3052          * with a suitably restricted receiver type prepended.
3053          * (The receiver type will be {@code specialCaller} or a subtype.)
3054          * If the method's {@code accessible} flag is not set,
3055          * access checking is performed immediately on behalf of the lookup class,
3056          * as if {@code invokespecial} instruction were being linked.
3057          * <p>
3058          * Before method resolution,
3059          * if the explicitly specified caller class is not identical with the
3060          * lookup class, or if this lookup object does not have
3061          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3062          * privileges, the access fails.
3063          * <p>
3064          * The returned method handle will have
3065          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3066          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3067          * @param m the reflected method
3068          * @param specialCaller the class nominally calling the method
3069          * @return a method handle which can invoke the reflected method
3070          * @throws IllegalAccessException if access checking fails,
3071          *                                or if the method is {@code static},
3072          *                                or if the method's variable arity modifier bit
3073          *                                is set and {@code asVarargsCollector} fails
3074          * @throws NullPointerException if any argument is null
3075          */
3076         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3077             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3078             Lookup specialLookup = this.in(specialCaller);
3079             MemberName method = new MemberName(m, true);
3080             assert(method.isMethod());
3081             // ignore m.isAccessible:  this is a new kind of access
3082             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3083         }
3084 
3085         /**
3086          * Produces a method handle for a reflected constructor.
3087          * The type of the method handle will be that of the constructor,
3088          * with the return type changed to the declaring class.
3089          * The method handle will perform a {@code newInstance} operation,
3090          * creating a new instance of the constructor's class on the
3091          * arguments passed to the method handle.
3092          * <p>
3093          * If the constructor's {@code accessible} flag is not set,
3094          * access checking is performed immediately on behalf of the lookup class.
3095          * <p>
3096          * The returned method handle will have
3097          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3098          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3099          * <p>
3100          * If the returned method handle is invoked, the constructor's class will
3101          * be initialized, if it has not already been initialized.
3102          * @param c the reflected constructor
3103          * @return a method handle which can invoke the reflected constructor
3104          * @throws IllegalAccessException if access checking fails
3105          *                                or if the method's variable arity modifier bit
3106          *                                is set and {@code asVarargsCollector} fails
3107          * @throws NullPointerException if the argument is null
3108          */
3109         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3110             MemberName ctor = new MemberName(c);
3111             assert(ctor.isConstructor());
3112             @SuppressWarnings("deprecation")
3113             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3114             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
3115         }
3116 
3117         /**
3118          * Produces a method handle giving read access to a reflected field.
3119          * The type of the method handle will have a return type of the field's
3120          * value type.
3121          * If the field is {@code static}, the method handle will take no arguments.
3122          * Otherwise, its single argument will be the instance containing
3123          * the field.
3124          * If the {@code Field} object's {@code accessible} flag is not set,
3125          * access checking is performed immediately on behalf of the lookup class.
3126          * <p>
3127          * If the field is static, and
3128          * if the returned method handle is invoked, the field's class will
3129          * be initialized, if it has not already been initialized.
3130          * @param f the reflected field
3131          * @return a method handle which can load values from the reflected field
3132          * @throws IllegalAccessException if access checking fails
3133          * @throws NullPointerException if the argument is null
3134          */
3135         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3136             return unreflectField(f, false);
3137         }
3138 
3139         /**
3140          * Produces a method handle giving write access to a reflected field.
3141          * The type of the method handle will have a void return type.
3142          * If the field is {@code static}, the method handle will take a single
3143          * argument, of the field's value type, the value to be stored.
3144          * Otherwise, the two arguments will be the instance containing
3145          * the field, and the value to be stored.
3146          * If the {@code Field} object's {@code accessible} flag is not set,
3147          * access checking is performed immediately on behalf of the lookup class.
3148          * <p>
3149          * If the field is {@code final}, write access will not be
3150          * allowed and access checking will fail, except under certain
3151          * narrow circumstances documented for {@link Field#set Field.set}.
3152          * A method handle is returned only if a corresponding call to
3153          * the {@code Field} object's {@code set} method could return
3154          * normally.  In particular, fields which are both {@code static}
3155          * and {@code final} may never be set.
3156          * <p>
3157          * If the field is {@code static}, and
3158          * if the returned method handle is invoked, the field's class will
3159          * be initialized, if it has not already been initialized.
3160          * @param f the reflected field
3161          * @return a method handle which can store values into the reflected field
3162          * @throws IllegalAccessException if access checking fails,
3163          *         or if the field is {@code final} and write access
3164          *         is not enabled on the {@code Field} object
3165          * @throws NullPointerException if the argument is null
3166          */
3167         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3168             return unreflectField(f, true);
3169         }
3170 
3171         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3172             MemberName field = new MemberName(f, isSetter);
3173             if (isSetter && field.isFinal()) {
3174                 if (field.isStatic()) {
3175                     throw field.makeAccessException("static final field has no write access", this);
3176                 } else if (field.getDeclaringClass().isHidden()){
3177                     throw field.makeAccessException("final field in a hidden class has no write access", this);
3178                 }
3179             }
3180             assert(isSetter
3181                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3182                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3183             @SuppressWarnings("deprecation")
3184             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3185             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3186         }
3187 
3188         /**
3189          * Produces a VarHandle giving access to a reflected field {@code f}
3190          * of type {@code T} declared in a class of type {@code R}.
3191          * The VarHandle's variable type is {@code T}.
3192          * If the field is non-static the VarHandle has one coordinate type,
3193          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3194          * coordinate types.
3195          * <p>
3196          * Access checking is performed immediately on behalf of the lookup
3197          * class, regardless of the value of the field's {@code accessible}
3198          * flag.
3199          * <p>
3200          * If the field is static, and if the returned VarHandle is operated
3201          * on, the field's declaring class will be initialized, if it has not
3202          * already been initialized.
3203          * <p>
3204          * Certain access modes of the returned VarHandle are unsupported under
3205          * the following conditions:
3206          * <ul>
3207          * <li>if the field is declared {@code final}, then the write, atomic
3208          *     update, numeric atomic update, and bitwise atomic update access
3209          *     modes are unsupported.
3210          * <li>if the field type is anything other than {@code byte},
3211          *     {@code short}, {@code char}, {@code int}, {@code long},
3212          *     {@code float}, or {@code double} then numeric atomic update
3213          *     access modes are unsupported.
3214          * <li>if the field type is anything other than {@code boolean},
3215          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3216          *     {@code long} then bitwise atomic update access modes are
3217          *     unsupported.
3218          * </ul>
3219          * <p>
3220          * If the field is declared {@code volatile} then the returned VarHandle
3221          * will override access to the field (effectively ignore the
3222          * {@code volatile} declaration) in accordance to its specified
3223          * access modes.
3224          * <p>
3225          * If the field type is {@code float} or {@code double} then numeric
3226          * and atomic update access modes compare values using their bitwise
3227          * representation (see {@link Float#floatToRawIntBits} and
3228          * {@link Double#doubleToRawLongBits}, respectively).
3229          * @apiNote
3230          * Bitwise comparison of {@code float} values or {@code double} values,
3231          * as performed by the numeric and atomic update access modes, differ
3232          * from the primitive {@code ==} operator and the {@link Float#equals}
3233          * and {@link Double#equals} methods, specifically with respect to
3234          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3235          * Care should be taken when performing a compare and set or a compare
3236          * and exchange operation with such values since the operation may
3237          * unexpectedly fail.
3238          * There are many possible NaN values that are considered to be
3239          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3240          * provided by Java can distinguish between them.  Operation failure can
3241          * occur if the expected or witness value is a NaN value and it is
3242          * transformed (perhaps in a platform specific manner) into another NaN
3243          * value, and thus has a different bitwise representation (see
3244          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3245          * details).
3246          * The values {@code -0.0} and {@code +0.0} have different bitwise
3247          * representations but are considered equal when using the primitive
3248          * {@code ==} operator.  Operation failure can occur if, for example, a
3249          * numeric algorithm computes an expected value to be say {@code -0.0}
3250          * and previously computed the witness value to be say {@code +0.0}.
3251          * @param f the reflected field, with a field of type {@code T}, and
3252          * a declaring class of type {@code R}
3253          * @return a VarHandle giving access to non-static fields or a static
3254          * field
3255          * @throws IllegalAccessException if access checking fails
3256          * @throws NullPointerException if the argument is null
3257          * @since 9
3258          */
3259         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3260             MemberName getField = new MemberName(f, false);
3261             MemberName putField = new MemberName(f, true);
3262             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
3263                                                       f.getDeclaringClass(), getField, putField);
3264         }
3265 
3266         /**
3267          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3268          * created by this lookup object or a similar one.
3269          * Security and access checks are performed to ensure that this lookup object
3270          * is capable of reproducing the target method handle.
3271          * This means that the cracking may fail if target is a direct method handle
3272          * but was created by an unrelated lookup object.
3273          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3274          * and was created by a lookup object for a different class.
3275          * @param target a direct method handle to crack into symbolic reference components
3276          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3277          * @throws    SecurityException if a security manager is present and it
3278          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3279          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3280          * @throws    NullPointerException if the target is {@code null}
3281          * @see MethodHandleInfo
3282          * @since 1.8
3283          */
3284         public MethodHandleInfo revealDirect(MethodHandle target) {
3285             MemberName member = target.internalMemberName();
3286             if (member == null || (!member.isResolved() &&
3287                                    !member.isMethodHandleInvoke() &&
3288                                    !member.isVarHandleMethodInvoke()))
3289                 throw newIllegalArgumentException("not a direct method handle");
3290             Class<?> defc = member.getDeclaringClass();
3291             byte refKind = member.getReferenceKind();
3292             assert(MethodHandleNatives.refKindIsValid(refKind));
3293             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3294                 // Devirtualized method invocation is usually formally virtual.
3295                 // To avoid creating extra MemberName objects for this common case,
3296                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3297                 refKind = REF_invokeVirtual;
3298             if (refKind == REF_invokeVirtual && defc.isInterface())
3299                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3300                 refKind = REF_invokeInterface;
3301             // Check SM permissions and member access before cracking.
3302             try {
3303                 checkAccess(refKind, defc, member);
3304                 checkSecurityManager(defc, member);
3305             } catch (IllegalAccessException ex) {
3306                 throw new IllegalArgumentException(ex);
3307             }
3308             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3309                 Class<?> callerClass = target.internalCallerClass();
3310                 if (!hasFullPrivilegeAccess() || callerClass != lookupClass())
3311                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3312             }
3313             // Produce the handle to the results.
3314             return new InfoFromMemberName(this, member, refKind);
3315         }
3316 
3317         /// Helper methods, all package-private.
3318 
3319         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3320             checkSymbolicClass(refc);  // do this before attempting to resolve
3321             Objects.requireNonNull(name);
3322             Objects.requireNonNull(type);
3323             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
3324                                             NoSuchFieldException.class);
3325         }
3326 
3327         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3328             checkSymbolicClass(refc);  // do this before attempting to resolve
3329             Objects.requireNonNull(name);
3330             Objects.requireNonNull(type);
3331             checkMethodName(refKind, name);  // NPE check on name
3332             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
3333                                             NoSuchMethodException.class);
3334         }
3335 
3336         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3337             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3338             Objects.requireNonNull(member.getName());
3339             Objects.requireNonNull(member.getType());
3340             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
3341                                             ReflectiveOperationException.class);
3342         }
3343 
3344         MemberName resolveOrNull(byte refKind, MemberName member) {
3345             // do this before attempting to resolve
3346             if (!isClassAccessible(member.getDeclaringClass())) {
3347                 return null;
3348             }
3349             Objects.requireNonNull(member.getName());
3350             Objects.requireNonNull(member.getType());
3351             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull());
3352         }
3353 
3354         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3355             if (!isClassAccessible(refc)) {
3356                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3357             }
3358         }
3359 
3360         boolean isClassAccessible(Class<?> refc) {
3361             Objects.requireNonNull(refc);
3362             Class<?> caller = lookupClassOrNull();
3363             return caller == null || VerifyAccess.isClassAccessible(refc, caller, prevLookupClass, allowedModes);
3364         }
3365 
3366         /** Check name for an illegal leading "&lt;" character. */
3367         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3368             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
3369                 throw new NoSuchMethodException("illegal method name: "+name);
3370         }
3371 
3372 
3373         /**
3374          * Find my trustable caller class if m is a caller sensitive method.
3375          * If this lookup object has full privilege access, then the caller class is the lookupClass.
3376          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3377          */
3378         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3379             if (MethodHandleNatives.isCallerSensitive(m) && !hasFullPrivilegeAccess()) {
3380                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3381                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3382             }
3383             return this;
3384         }
3385 
3386         /**
3387          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3388          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3389          *
3390          * @deprecated This method was originally designed to test {@code PRIVATE} access
3391          * that implies full privilege access but {@code MODULE} access has since become
3392          * independent of {@code PRIVATE} access.  It is recommended to call
3393          * {@link #hasFullPrivilegeAccess()} instead.
3394          * @since 9
3395          */
3396         @Deprecated(since="14")
3397         public boolean hasPrivateAccess() {
3398             return hasFullPrivilegeAccess();
3399         }
3400 
3401         /**
3402          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3403          * i.e. {@code PRIVATE} and {@code MODULE} access.
3404          * A {@code Lookup} object must have full privilege access in order to
3405          * access all members that are allowed to the {@linkplain #lookupClass() lookup class}.
3406          *
3407          * @return {@code true} if this lookup has full privilege access.
3408          * @since 14
3409          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3410          */
3411         public boolean hasFullPrivilegeAccess() {
3412             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3413         }
3414 
3415         /**
3416          * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
3417          * Determines a trustable caller class to compare with refc, the symbolic reference class.
3418          * If this lookup object has full privilege access, then the caller class is the lookupClass.
3419          */
3420         void checkSecurityManager(Class<?> refc, MemberName m) {
3421             if (allowedModes == TRUSTED)  return;
3422 
3423             SecurityManager smgr = System.getSecurityManager();
3424             if (smgr == null)  return;
3425 
3426             // Step 1:
3427             boolean fullPowerLookup = hasFullPrivilegeAccess();
3428             if (!fullPowerLookup ||
3429                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3430                 ReflectUtil.checkPackageAccess(refc);
3431             }
3432 
3433             if (m == null) {  // findClass or accessClass
3434                 // Step 2b:
3435                 if (!fullPowerLookup) {
3436                     smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
3437                 }
3438                 return;
3439             }
3440 
3441             // Step 2a:
3442             if (m.isPublic()) return;
3443             if (!fullPowerLookup) {
3444                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3445             }
3446 
3447             // Step 3:
3448             Class<?> defc = m.getDeclaringClass();
3449             if (!fullPowerLookup && defc != refc) {
3450                 ReflectUtil.checkPackageAccess(defc);
3451             }
3452         }
3453 
3454         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3455             boolean wantStatic = (refKind == REF_invokeStatic);
3456             String message;
3457             if (m.isConstructor())
3458                 message = "expected a method, not a constructor";
3459             else if (!m.isMethod())
3460                 message = "expected a method";
3461             else if (wantStatic != m.isStatic())
3462                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3463             else
3464                 { checkAccess(refKind, refc, m); return; }
3465             throw m.makeAccessException(message, this);
3466         }
3467 
3468         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3469             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3470             String message;
3471             if (wantStatic != m.isStatic())
3472                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3473             else
3474                 { checkAccess(refKind, refc, m); return; }
3475             throw m.makeAccessException(message, this);
3476         }
3477 
3478         /** Check public/protected/private bits on the symbolic reference class and its member. */
3479         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3480             assert(m.referenceKindIsConsistentWith(refKind) &&
3481                    MethodHandleNatives.refKindIsValid(refKind) &&
3482                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3483             int allowedModes = this.allowedModes;
3484             if (allowedModes == TRUSTED)  return;
3485             int mods = m.getModifiers();
3486             if (Modifier.isProtected(mods) &&
3487                     refKind == REF_invokeVirtual &&
3488                     m.getDeclaringClass() == Object.class &&
3489                     m.getName().equals("clone") &&
3490                     refc.isArray()) {
3491                 // The JVM does this hack also.
3492                 // (See ClassVerifier::verify_invoke_instructions
3493                 // and LinkResolver::check_method_accessability.)
3494                 // Because the JVM does not allow separate methods on array types,
3495                 // there is no separate method for int[].clone.
3496                 // All arrays simply inherit Object.clone.
3497                 // But for access checking logic, we make Object.clone
3498                 // (normally protected) appear to be public.
3499                 // Later on, when the DirectMethodHandle is created,
3500                 // its leading argument will be restricted to the
3501                 // requested array type.
3502                 // N.B. The return type is not adjusted, because
3503                 // that is *not* the bytecode behavior.
3504                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3505             }
3506             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3507                 // cannot "new" a protected ctor in a different package
3508                 mods ^= Modifier.PROTECTED;
3509             }
3510             if (Modifier.isFinal(mods) &&
3511                     MethodHandleNatives.refKindIsSetter(refKind))
3512                 throw m.makeAccessException("unexpected set of a final field", this);
3513             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3514             if ((requestedModes & allowedModes) != 0) {
3515                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3516                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3517                     return;
3518             } else {
3519                 // Protected members can also be checked as if they were package-private.
3520                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
3521                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
3522                     return;
3523             }
3524             throw m.makeAccessException(accessFailedMessage(refc, m), this);
3525         }
3526 
3527         String accessFailedMessage(Class<?> refc, MemberName m) {
3528             Class<?> defc = m.getDeclaringClass();
3529             int mods = m.getModifiers();
3530             // check the class first:
3531             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
3532                                (defc == refc ||
3533                                 Modifier.isPublic(refc.getModifiers())));
3534             if (!classOK && (allowedModes & PACKAGE) != 0) {
3535                 // ignore previous lookup class to check if default package access
3536                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
3537                            (defc == refc ||
3538                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
3539             }
3540             if (!classOK)
3541                 return "class is not public";
3542             if (Modifier.isPublic(mods))
3543                 return "access to public member failed";  // (how?, module not readable?)
3544             if (Modifier.isPrivate(mods))
3545                 return "member is private";
3546             if (Modifier.isProtected(mods))
3547                 return "member is protected";
3548             return "member is private to package";
3549         }
3550 
3551         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
3552             int allowedModes = this.allowedModes;
3553             if (allowedModes == TRUSTED)  return;
3554             if ((lookupModes() & PRIVATE) == 0
3555                 || (specialCaller != lookupClass()
3556                        // ensure non-abstract methods in superinterfaces can be special-invoked
3557                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
3558                 throw new MemberName(specialCaller).
3559                     makeAccessException("no private access for invokespecial", this);
3560         }
3561 
3562         private boolean restrictProtectedReceiver(MemberName method) {
3563             // The accessing class only has the right to use a protected member
3564             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
3565             if (!method.isProtected() || method.isStatic()
3566                 || allowedModes == TRUSTED
3567                 || method.getDeclaringClass() == lookupClass()
3568                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
3569                 return false;
3570             return true;
3571         }
3572         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
3573             assert(!method.isStatic());
3574             // receiver type of mh is too wide; narrow to caller
3575             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
3576                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
3577             }
3578             MethodType rawType = mh.type();
3579             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
3580             MethodType narrowType = rawType.changeParameterType(0, caller);
3581             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
3582             assert(mh.viewAsTypeChecks(narrowType, true));
3583             return mh.copyWith(narrowType, mh.form);
3584         }
3585 
3586         /** Check access and get the requested method. */
3587         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3588             final boolean doRestrict    = true;
3589             final boolean checkSecurity = true;
3590             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3591         }
3592         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
3593         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3594             final boolean doRestrict    = false;
3595             final boolean checkSecurity = true;
3596             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
3597         }
3598         /** Check access and get the requested method, eliding security manager checks. */
3599         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3600             final boolean doRestrict    = true;
3601             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
3602             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3603         }
3604         /** Common code for all methods; do not call directly except from immediately above. */
3605         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
3606                                                    boolean checkSecurity,
3607                                                    boolean doRestrict,
3608                                                    Lookup boundCaller) throws IllegalAccessException {
3609             checkMethod(refKind, refc, method);
3610             // Optionally check with the security manager; this isn't needed for unreflect* calls.
3611             if (checkSecurity)
3612                 checkSecurityManager(refc, method);
3613             assert(!method.isMethodHandleInvoke());
3614 
3615             if (refKind == REF_invokeSpecial &&
3616                 refc != lookupClass() &&
3617                 !refc.isInterface() &&
3618                 refc != lookupClass().getSuperclass() &&
3619                 refc.isAssignableFrom(lookupClass())) {
3620                 assert(!method.getName().equals("<init>"));  // not this code path
3621 
3622                 // Per JVMS 6.5, desc. of invokespecial instruction:
3623                 // If the method is in a superclass of the LC,
3624                 // and if our original search was above LC.super,
3625                 // repeat the search (symbolic lookup) from LC.super
3626                 // and continue with the direct superclass of that class,
3627                 // and so forth, until a match is found or no further superclasses exist.
3628                 // FIXME: MemberName.resolve should handle this instead.
3629                 Class<?> refcAsSuper = lookupClass();
3630                 MemberName m2;
3631                 do {
3632                     refcAsSuper = refcAsSuper.getSuperclass();
3633                     m2 = new MemberName(refcAsSuper,
3634                                         method.getName(),
3635                                         method.getMethodType(),
3636                                         REF_invokeSpecial);
3637                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
3638                 } while (m2 == null &&         // no method is found yet
3639                          refc != refcAsSuper); // search up to refc
3640                 if (m2 == null)  throw new InternalError(method.toString());
3641                 method = m2;
3642                 refc = refcAsSuper;
3643                 // redo basic checks
3644                 checkMethod(refKind, refc, method);
3645             }
3646             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
3647             MethodHandle mh = dmh;
3648             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
3649             if ((doRestrict && refKind == REF_invokeSpecial) ||
3650                     (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method))) {
3651                 mh = restrictReceiver(method, dmh, lookupClass());
3652             }
3653             mh = maybeBindCaller(method, mh, boundCaller);
3654             mh = mh.setVarargs(method);
3655             return mh;
3656         }
3657         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
3658                                              throws IllegalAccessException {
3659             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
3660                 return mh;
3661 
3662             // boundCaller must have full privilege access.
3663             // It should have been checked by findBoundCallerLookup. Safe to check this again.
3664             if (!boundCaller.hasFullPrivilegeAccess())
3665                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3666 
3667             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
3668             // Note: caller will apply varargs after this step happens.
3669             return cbmh;
3670         }
3671 
3672         /** Check access and get the requested field. */
3673         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
3674             final boolean checkSecurity = true;
3675             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
3676         }
3677         /** Check access and get the requested field, eliding security manager checks. */
3678         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
3679             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
3680             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
3681         }
3682         /** Common code for all fields; do not call directly except from immediately above. */
3683         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
3684                                                   boolean checkSecurity) throws IllegalAccessException {
3685             checkField(refKind, refc, field);
3686             // Optionally check with the security manager; this isn't needed for unreflect* calls.
3687             if (checkSecurity)
3688                 checkSecurityManager(refc, field);
3689             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
3690             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
3691                                     restrictProtectedReceiver(field));
3692             if (doRestrict)
3693                 return restrictReceiver(field, dmh, lookupClass());
3694             return dmh;
3695         }
3696         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
3697                                             Class<?> refc, MemberName getField, MemberName putField)
3698                 throws IllegalAccessException {
3699             final boolean checkSecurity = true;
3700             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
3701         }
3702         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
3703                                                              Class<?> refc, MemberName getField, MemberName putField)
3704                 throws IllegalAccessException {
3705             final boolean checkSecurity = false;
3706             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
3707         }
3708         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
3709                                                   Class<?> refc, MemberName getField, MemberName putField,
3710                                                   boolean checkSecurity) throws IllegalAccessException {
3711             assert getField.isStatic() == putField.isStatic();
3712             assert getField.isGetter() && putField.isSetter();
3713             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
3714             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
3715 
3716             checkField(getRefKind, refc, getField);
3717             if (checkSecurity)
3718                 checkSecurityManager(refc, getField);
3719 
3720             if (!putField.isFinal()) {
3721                 // A VarHandle does not support updates to final fields, any
3722                 // such VarHandle to a final field will be read-only and
3723                 // therefore the following write-based accessibility checks are
3724                 // only required for non-final fields
3725                 checkField(putRefKind, refc, putField);
3726                 if (checkSecurity)
3727                     checkSecurityManager(refc, putField);
3728             }
3729 
3730             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
3731                                   restrictProtectedReceiver(getField));
3732             if (doRestrict) {
3733                 assert !getField.isStatic();
3734                 // receiver type of VarHandle is too wide; narrow to caller
3735                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
3736                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
3737                 }
3738                 refc = lookupClass();
3739             }
3740             return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(),
3741                                              this.allowedModes == TRUSTED && !getField.getDeclaringClass().isHidden());
3742         }
3743         /** Check access and get the requested constructor. */
3744         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3745             final boolean checkSecurity = true;
3746             return getDirectConstructorCommon(refc, ctor, checkSecurity);
3747         }
3748         /** Check access and get the requested constructor, eliding security manager checks. */
3749         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3750             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
3751             return getDirectConstructorCommon(refc, ctor, checkSecurity);
3752         }
3753         /** Common code for all constructors; do not call directly except from immediately above. */
3754         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
3755                                                   boolean checkSecurity) throws IllegalAccessException {
3756             assert(ctor.isConstructor());
3757             checkAccess(REF_newInvokeSpecial, refc, ctor);
3758             // Optionally check with the security manager; this isn't needed for unreflect* calls.
3759             if (checkSecurity)
3760                 checkSecurityManager(refc, ctor);
3761             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
3762             return DirectMethodHandle.make(ctor).setVarargs(ctor);
3763         }
3764 
3765         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
3766          */
3767         /*non-public*/
3768         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
3769                 throws ReflectiveOperationException {
3770             if (!(type instanceof Class || type instanceof MethodType))
3771                 throw new InternalError("unresolved MemberName");
3772             MemberName member = new MemberName(refKind, defc, name, type);
3773             MethodHandle mh = LOOKASIDE_TABLE.get(member);
3774             if (mh != null) {
3775                 checkSymbolicClass(defc);
3776                 return mh;
3777             }
3778             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
3779                 // Treat MethodHandle.invoke and invokeExact specially.
3780                 mh = findVirtualForMH(member.getName(), member.getMethodType());
3781                 if (mh != null) {
3782                     return mh;
3783                 }
3784             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
3785                 // Treat signature-polymorphic methods on VarHandle specially.
3786                 mh = findVirtualForVH(member.getName(), member.getMethodType());
3787                 if (mh != null) {
3788                     return mh;
3789                 }
3790             }
3791             MemberName resolved = resolveOrFail(refKind, member);
3792             mh = getDirectMethodForConstant(refKind, defc, resolved);
3793             if (mh instanceof DirectMethodHandle
3794                     && canBeCached(refKind, defc, resolved)) {
3795                 MemberName key = mh.internalMemberName();
3796                 if (key != null) {
3797                     key = key.asNormalOriginal();
3798                 }
3799                 if (member.equals(key)) {  // better safe than sorry
3800                     LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
3801                 }
3802             }
3803             return mh;
3804         }
3805         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
3806             if (refKind == REF_invokeSpecial) {
3807                 return false;
3808             }
3809             if (!Modifier.isPublic(defc.getModifiers()) ||
3810                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
3811                     !member.isPublic() ||
3812                     member.isCallerSensitive()) {
3813                 return false;
3814             }
3815             ClassLoader loader = defc.getClassLoader();
3816             if (loader != null) {
3817                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
3818                 boolean found = false;
3819                 while (sysl != null) {
3820                     if (loader == sysl) { found = true; break; }
3821                     sysl = sysl.getParent();
3822                 }
3823                 if (!found) {
3824                     return false;
3825                 }
3826             }
3827             try {
3828                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
3829                     new MemberName(refKind, defc, member.getName(), member.getType()));
3830                 if (resolved2 == null) {
3831                     return false;
3832                 }
3833                 checkSecurityManager(defc, resolved2);
3834             } catch (SecurityException ex) {
3835                 return false;
3836             }
3837             return true;
3838         }
3839         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
3840                 throws ReflectiveOperationException {
3841             if (MethodHandleNatives.refKindIsField(refKind)) {
3842                 return getDirectFieldNoSecurityManager(refKind, defc, member);
3843             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
3844                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
3845             } else if (refKind == REF_newInvokeSpecial) {
3846                 return getDirectConstructorNoSecurityManager(defc, member);
3847             }
3848             // oops
3849             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
3850         }
3851 
3852         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
3853     }
3854 
3855     /**
3856      * Produces a method handle constructing arrays of a desired type,
3857      * as if by the {@code anewarray} bytecode.
3858      * The return type of the method handle will be the array type.
3859      * The type of its sole argument will be {@code int}, which specifies the size of the array.
3860      *
3861      * <p> If the returned method handle is invoked with a negative
3862      * array size, a {@code NegativeArraySizeException} will be thrown.
3863      *
3864      * @param arrayClass an array type
3865      * @return a method handle which can create arrays of the given type
3866      * @throws NullPointerException if the argument is {@code null}
3867      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
3868      * @see java.lang.reflect.Array#newInstance(Class, int)
3869      * @jvms 6.5 {@code anewarray} Instruction
3870      * @since 9
3871      */
3872     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
3873         if (!arrayClass.isArray()) {
3874             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
3875         }
3876         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
3877                 bindTo(arrayClass.getComponentType());
3878         return ani.asType(ani.type().changeReturnType(arrayClass));
3879     }
3880 
3881     /**
3882      * Produces a method handle returning the length of an array,
3883      * as if by the {@code arraylength} bytecode.
3884      * The type of the method handle will have {@code int} as return type,
3885      * and its sole argument will be the array type.
3886      *
3887      * <p> If the returned method handle is invoked with a {@code null}
3888      * array reference, a {@code NullPointerException} will be thrown.
3889      *
3890      * @param arrayClass an array type
3891      * @return a method handle which can retrieve the length of an array of the given array type
3892      * @throws NullPointerException if the argument is {@code null}
3893      * @throws IllegalArgumentException if arrayClass is not an array type
3894      * @jvms 6.5 {@code arraylength} Instruction
3895      * @since 9
3896      */
3897     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
3898         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
3899     }
3900 
3901     /**
3902      * Produces a method handle giving read access to elements of an array,
3903      * as if by the {@code aaload} bytecode.
3904      * The type of the method handle will have a return type of the array's
3905      * element type.  Its first argument will be the array type,
3906      * and the second will be {@code int}.
3907      *
3908      * <p> When the returned method handle is invoked,
3909      * the array reference and array index are checked.
3910      * A {@code NullPointerException} will be thrown if the array reference
3911      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
3912      * thrown if the index is negative or if it is greater than or equal to
3913      * the length of the array.
3914      *
3915      * @param arrayClass an array type
3916      * @return a method handle which can load values from the given array type
3917      * @throws NullPointerException if the argument is null
3918      * @throws  IllegalArgumentException if arrayClass is not an array type
3919      * @jvms 6.5 {@code aaload} Instruction
3920      */
3921     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
3922         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
3923     }
3924 
3925     /**
3926      * Produces a method handle giving write access to elements of an array,
3927      * as if by the {@code astore} bytecode.
3928      * The type of the method handle will have a void return type.
3929      * Its last argument will be the array's element type.
3930      * The first and second arguments will be the array type and int.
3931      *
3932      * <p> When the returned method handle is invoked,
3933      * the array reference and array index are checked.
3934      * A {@code NullPointerException} will be thrown if the array reference
3935      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
3936      * thrown if the index is negative or if it is greater than or equal to
3937      * the length of the array.
3938      *
3939      * @param arrayClass the class of an array
3940      * @return a method handle which can store values into the array type
3941      * @throws NullPointerException if the argument is null
3942      * @throws IllegalArgumentException if arrayClass is not an array type
3943      * @jvms 6.5 {@code aastore} Instruction
3944      */
3945     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
3946         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
3947     }
3948 
3949     /**
3950      * Produces a VarHandle giving access to elements of an array of type
3951      * {@code arrayClass}.  The VarHandle's variable type is the component type
3952      * of {@code arrayClass} and the list of coordinate types is
3953      * {@code (arrayClass, int)}, where the {@code int} coordinate type
3954      * corresponds to an argument that is an index into an array.
3955      * <p>
3956      * Certain access modes of the returned VarHandle are unsupported under
3957      * the following conditions:
3958      * <ul>
3959      * <li>if the component type is anything other than {@code byte},
3960      *     {@code short}, {@code char}, {@code int}, {@code long},
3961      *     {@code float}, or {@code double} then numeric atomic update access
3962      *     modes are unsupported.
3963      * <li>if the field type is anything other than {@code boolean},
3964      *     {@code byte}, {@code short}, {@code char}, {@code int} or
3965      *     {@code long} then bitwise atomic update access modes are
3966      *     unsupported.
3967      * </ul>
3968      * <p>
3969      * If the component type is {@code float} or {@code double} then numeric
3970      * and atomic update access modes compare values using their bitwise
3971      * representation (see {@link Float#floatToRawIntBits} and
3972      * {@link Double#doubleToRawLongBits}, respectively).
3973      *
3974      * <p> When the returned {@code VarHandle} is invoked,
3975      * the array reference and array index are checked.
3976      * A {@code NullPointerException} will be thrown if the array reference
3977      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
3978      * thrown if the index is negative or if it is greater than or equal to
3979      * the length of the array.
3980      *
3981      * @apiNote
3982      * Bitwise comparison of {@code float} values or {@code double} values,
3983      * as performed by the numeric and atomic update access modes, differ
3984      * from the primitive {@code ==} operator and the {@link Float#equals}
3985      * and {@link Double#equals} methods, specifically with respect to
3986      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3987      * Care should be taken when performing a compare and set or a compare
3988      * and exchange operation with such values since the operation may
3989      * unexpectedly fail.
3990      * There are many possible NaN values that are considered to be
3991      * {@code NaN} in Java, although no IEEE 754 floating-point operation
3992      * provided by Java can distinguish between them.  Operation failure can
3993      * occur if the expected or witness value is a NaN value and it is
3994      * transformed (perhaps in a platform specific manner) into another NaN
3995      * value, and thus has a different bitwise representation (see
3996      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3997      * details).
3998      * The values {@code -0.0} and {@code +0.0} have different bitwise
3999      * representations but are considered equal when using the primitive
4000      * {@code ==} operator.  Operation failure can occur if, for example, a
4001      * numeric algorithm computes an expected value to be say {@code -0.0}
4002      * and previously computed the witness value to be say {@code +0.0}.
4003      * @param arrayClass the class of an array, of type {@code T[]}
4004      * @return a VarHandle giving access to elements of an array
4005      * @throws NullPointerException if the arrayClass is null
4006      * @throws IllegalArgumentException if arrayClass is not an array type
4007      * @since 9
4008      */
4009     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4010         return VarHandles.makeArrayElementHandle(arrayClass);
4011     }
4012 
4013     /**
4014      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4015      * viewed as if it were a different primitive array type, such as
4016      * {@code int[]} or {@code long[]}.
4017      * The VarHandle's variable type is the component type of
4018      * {@code viewArrayClass} and the list of coordinate types is
4019      * {@code (byte[], int)}, where the {@code int} coordinate type
4020      * corresponds to an argument that is an index into a {@code byte[]} array.
4021      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4022      * array, composing bytes to or from a value of the component type of
4023      * {@code viewArrayClass} according to the given endianness.
4024      * <p>
4025      * The supported component types (variables types) are {@code short},
4026      * {@code char}, {@code int}, {@code long}, {@code float} and
4027      * {@code double}.
4028      * <p>
4029      * Access of bytes at a given index will result in an
4030      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4031      * or greater than the {@code byte[]} array length minus the size (in bytes)
4032      * of {@code T}.
4033      * <p>
4034      * Access of bytes at an index may be aligned or misaligned for {@code T},
4035      * with respect to the underlying memory address, {@code A} say, associated
4036      * with the array and index.
4037      * If access is misaligned then access for anything other than the
4038      * {@code get} and {@code set} access modes will result in an
4039      * {@code IllegalStateException}.  In such cases atomic access is only
4040      * guaranteed with respect to the largest power of two that divides the GCD
4041      * of {@code A} and the size (in bytes) of {@code T}.
4042      * If access is aligned then following access modes are supported and are
4043      * guaranteed to support atomic access:
4044      * <ul>
4045      * <li>read write access modes for all {@code T}, with the exception of
4046      *     access modes {@code get} and {@code set} for {@code long} and
4047      *     {@code double} on 32-bit platforms.
4048      * <li>atomic update access modes for {@code int}, {@code long},
4049      *     {@code float} or {@code double}.
4050      *     (Future major platform releases of the JDK may support additional
4051      *     types for certain currently unsupported access modes.)
4052      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4053      *     (Future major platform releases of the JDK may support additional
4054      *     numeric types for certain currently unsupported access modes.)
4055      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4056      *     (Future major platform releases of the JDK may support additional
4057      *     numeric types for certain currently unsupported access modes.)
4058      * </ul>
4059      * <p>
4060      * Misaligned access, and therefore atomicity guarantees, may be determined
4061      * for {@code byte[]} arrays without operating on a specific array.  Given
4062      * an {@code index}, {@code T} and it's corresponding boxed type,
4063      * {@code T_BOX}, misalignment may be determined as follows:
4064      * <pre>{@code
4065      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4066      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
4067      *     alignmentOffset(0, sizeOfT);
4068      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
4069      * boolean isMisaligned = misalignedAtIndex != 0;
4070      * }</pre>
4071      * <p>
4072      * If the variable type is {@code float} or {@code double} then atomic
4073      * update access modes compare values using their bitwise representation
4074      * (see {@link Float#floatToRawIntBits} and
4075      * {@link Double#doubleToRawLongBits}, respectively).
4076      * @param viewArrayClass the view array class, with a component type of
4077      * type {@code T}
4078      * @param byteOrder the endianness of the view array elements, as
4079      * stored in the underlying {@code byte} array
4080      * @return a VarHandle giving access to elements of a {@code byte[]} array
4081      * viewed as if elements corresponding to the components type of the view
4082      * array class
4083      * @throws NullPointerException if viewArrayClass or byteOrder is null
4084      * @throws IllegalArgumentException if viewArrayClass is not an array type
4085      * @throws UnsupportedOperationException if the component type of
4086      * viewArrayClass is not supported as a variable type
4087      * @since 9
4088      */
4089     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4090                                      ByteOrder byteOrder) throws IllegalArgumentException {
4091         Objects.requireNonNull(byteOrder);
4092         return VarHandles.byteArrayViewHandle(viewArrayClass,
4093                                               byteOrder == ByteOrder.BIG_ENDIAN);
4094     }
4095 
4096     /**
4097      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4098      * viewed as if it were an array of elements of a different primitive
4099      * component type to that of {@code byte}, such as {@code int[]} or
4100      * {@code long[]}.
4101      * The VarHandle's variable type is the component type of
4102      * {@code viewArrayClass} and the list of coordinate types is
4103      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4104      * corresponds to an argument that is an index into a {@code byte[]} array.
4105      * The returned VarHandle accesses bytes at an index in a
4106      * {@code ByteBuffer}, composing bytes to or from a value of the component
4107      * type of {@code viewArrayClass} according to the given endianness.
4108      * <p>
4109      * The supported component types (variables types) are {@code short},
4110      * {@code char}, {@code int}, {@code long}, {@code float} and
4111      * {@code double}.
4112      * <p>
4113      * Access will result in a {@code ReadOnlyBufferException} for anything
4114      * other than the read access modes if the {@code ByteBuffer} is read-only.
4115      * <p>
4116      * Access of bytes at a given index will result in an
4117      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4118      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4119      * {@code T}.
4120      * <p>
4121      * Access of bytes at an index may be aligned or misaligned for {@code T},
4122      * with respect to the underlying memory address, {@code A} say, associated
4123      * with the {@code ByteBuffer} and index.
4124      * If access is misaligned then access for anything other than the
4125      * {@code get} and {@code set} access modes will result in an
4126      * {@code IllegalStateException}.  In such cases atomic access is only
4127      * guaranteed with respect to the largest power of two that divides the GCD
4128      * of {@code A} and the size (in bytes) of {@code T}.
4129      * If access is aligned then following access modes are supported and are
4130      * guaranteed to support atomic access:
4131      * <ul>
4132      * <li>read write access modes for all {@code T}, with the exception of
4133      *     access modes {@code get} and {@code set} for {@code long} and
4134      *     {@code double} on 32-bit platforms.
4135      * <li>atomic update access modes for {@code int}, {@code long},
4136      *     {@code float} or {@code double}.
4137      *     (Future major platform releases of the JDK may support additional
4138      *     types for certain currently unsupported access modes.)
4139      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4140      *     (Future major platform releases of the JDK may support additional
4141      *     numeric types for certain currently unsupported access modes.)
4142      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4143      *     (Future major platform releases of the JDK may support additional
4144      *     numeric types for certain currently unsupported access modes.)
4145      * </ul>
4146      * <p>
4147      * Misaligned access, and therefore atomicity guarantees, may be determined
4148      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4149      * {@code index}, {@code T} and it's corresponding boxed type,
4150      * {@code T_BOX}, as follows:
4151      * <pre>{@code
4152      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4153      * ByteBuffer bb = ...
4154      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4155      * boolean isMisaligned = misalignedAtIndex != 0;
4156      * }</pre>
4157      * <p>
4158      * If the variable type is {@code float} or {@code double} then atomic
4159      * update access modes compare values using their bitwise representation
4160      * (see {@link Float#floatToRawIntBits} and
4161      * {@link Double#doubleToRawLongBits}, respectively).
4162      * @param viewArrayClass the view array class, with a component type of
4163      * type {@code T}
4164      * @param byteOrder the endianness of the view array elements, as
4165      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4166      * endianness of a {@code ByteBuffer})
4167      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4168      * viewed as if elements corresponding to the components type of the view
4169      * array class
4170      * @throws NullPointerException if viewArrayClass or byteOrder is null
4171      * @throws IllegalArgumentException if viewArrayClass is not an array type
4172      * @throws UnsupportedOperationException if the component type of
4173      * viewArrayClass is not supported as a variable type
4174      * @since 9
4175      */
4176     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4177                                       ByteOrder byteOrder) throws IllegalArgumentException {
4178         Objects.requireNonNull(byteOrder);
4179         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4180                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4181     }
4182 
4183 
4184     /// method handle invocation (reflective style)
4185 
4186     /**
4187      * Produces a method handle which will invoke any method handle of the
4188      * given {@code type}, with a given number of trailing arguments replaced by
4189      * a single trailing {@code Object[]} array.
4190      * The resulting invoker will be a method handle with the following
4191      * arguments:
4192      * <ul>
4193      * <li>a single {@code MethodHandle} target
4194      * <li>zero or more leading values (counted by {@code leadingArgCount})
4195      * <li>an {@code Object[]} array containing trailing arguments
4196      * </ul>
4197      * <p>
4198      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4199      * the indicated {@code type}.
4200      * That is, if the target is exactly of the given {@code type}, it will behave
4201      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4202      * is used to convert the target to the required {@code type}.
4203      * <p>
4204      * The type of the returned invoker will not be the given {@code type}, but rather
4205      * will have all parameters except the first {@code leadingArgCount}
4206      * replaced by a single array of type {@code Object[]}, which will be
4207      * the final parameter.
4208      * <p>
4209      * Before invoking its target, the invoker will spread the final array, apply
4210      * reference casts as necessary, and unbox and widen primitive arguments.
4211      * If, when the invoker is called, the supplied array argument does
4212      * not have the correct number of elements, the invoker will throw
4213      * an {@link IllegalArgumentException} instead of invoking the target.
4214      * <p>
4215      * This method is equivalent to the following code (though it may be more efficient):
4216      * <blockquote><pre>{@code
4217 MethodHandle invoker = MethodHandles.invoker(type);
4218 int spreadArgCount = type.parameterCount() - leadingArgCount;
4219 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4220 return invoker;
4221      * }</pre></blockquote>
4222      * This method throws no reflective or security exceptions.
4223      * @param type the desired target type
4224      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4225      * @return a method handle suitable for invoking any method handle of the given type
4226      * @throws NullPointerException if {@code type} is null
4227      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4228      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4229      *                  or if the resulting method handle's type would have
4230      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4231      */
4232     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4233         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4234             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4235         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4236         return type.invokers().spreadInvoker(leadingArgCount);
4237     }
4238 
4239     /**
4240      * Produces a special <em>invoker method handle</em> which can be used to
4241      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4242      * The resulting invoker will have a type which is
4243      * exactly equal to the desired type, except that it will accept
4244      * an additional leading argument of type {@code MethodHandle}.
4245      * <p>
4246      * This method is equivalent to the following code (though it may be more efficient):
4247      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4248      *
4249      * <p style="font-size:smaller;">
4250      * <em>Discussion:</em>
4251      * Invoker method handles can be useful when working with variable method handles
4252      * of unknown types.
4253      * For example, to emulate an {@code invokeExact} call to a variable method
4254      * handle {@code M}, extract its type {@code T},
4255      * look up the invoker method {@code X} for {@code T},
4256      * and call the invoker method, as {@code X.invoke(T, A...)}.
4257      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4258      * is unknown.)
4259      * If spreading, collecting, or other argument transformations are required,
4260      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4261      * method handle values, as long as they are compatible with the type of {@code X}.
4262      * <p style="font-size:smaller;">
4263      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4264      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4265      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4266      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4267      * <p>
4268      * This method throws no reflective or security exceptions.
4269      * @param type the desired target type
4270      * @return a method handle suitable for invoking any method handle of the given type
4271      * @throws IllegalArgumentException if the resulting method handle's type would have
4272      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4273      */
4274     public static MethodHandle exactInvoker(MethodType type) {
4275         return type.invokers().exactInvoker();
4276     }
4277 
4278     /**
4279      * Produces a special <em>invoker method handle</em> which can be used to
4280      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4281      * The resulting invoker will have a type which is
4282      * exactly equal to the desired type, except that it will accept
4283      * an additional leading argument of type {@code MethodHandle}.
4284      * <p>
4285      * Before invoking its target, if the target differs from the expected type,
4286      * the invoker will apply reference casts as
4287      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4288      * Similarly, the return value will be converted as necessary.
4289      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4290      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4291      * <p>
4292      * This method is equivalent to the following code (though it may be more efficient):
4293      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4294      * <p style="font-size:smaller;">
4295      * <em>Discussion:</em>
4296      * A {@linkplain MethodType#genericMethodType general method type} is one which
4297      * mentions only {@code Object} arguments and return values.
4298      * An invoker for such a type is capable of calling any method handle
4299      * of the same arity as the general type.
4300      * <p style="font-size:smaller;">
4301      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4302      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4303      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4304      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4305      * <p>
4306      * This method throws no reflective or security exceptions.
4307      * @param type the desired target type
4308      * @return a method handle suitable for invoking any method handle convertible to the given type
4309      * @throws IllegalArgumentException if the resulting method handle's type would have
4310      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4311      */
4312     public static MethodHandle invoker(MethodType type) {
4313         return type.invokers().genericInvoker();
4314     }
4315 
4316     /**
4317      * Produces a special <em>invoker method handle</em> which can be used to
4318      * invoke a signature-polymorphic access mode method on any VarHandle whose
4319      * associated access mode type is compatible with the given type.
4320      * The resulting invoker will have a type which is exactly equal to the
4321      * desired given type, except that it will accept an additional leading
4322      * argument of type {@code VarHandle}.
4323      *
4324      * @param accessMode the VarHandle access mode
4325      * @param type the desired target type
4326      * @return a method handle suitable for invoking an access mode method of
4327      *         any VarHandle whose access mode type is of the given type.
4328      * @since 9
4329      */
4330     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4331         return type.invokers().varHandleMethodExactInvoker(accessMode);
4332     }
4333 
4334     /**
4335      * Produces a special <em>invoker method handle</em> which can be used to
4336      * invoke a signature-polymorphic access mode method on any VarHandle whose
4337      * associated access mode type is compatible with the given type.
4338      * The resulting invoker will have a type which is exactly equal to the
4339      * desired given type, except that it will accept an additional leading
4340      * argument of type {@code VarHandle}.
4341      * <p>
4342      * Before invoking its target, if the access mode type differs from the
4343      * desired given type, the invoker will apply reference casts as necessary
4344      * and box, unbox, or widen primitive values, as if by
4345      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4346      * converted as necessary.
4347      * <p>
4348      * This method is equivalent to the following code (though it may be more
4349      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4350      *
4351      * @param accessMode the VarHandle access mode
4352      * @param type the desired target type
4353      * @return a method handle suitable for invoking an access mode method of
4354      *         any VarHandle whose access mode type is convertible to the given
4355      *         type.
4356      * @since 9
4357      */
4358     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4359         return type.invokers().varHandleMethodInvoker(accessMode);
4360     }
4361 
4362     /*non-public*/
4363     static MethodHandle basicInvoker(MethodType type) {
4364         return type.invokers().basicInvoker();
4365     }
4366 
4367      /// method handle modification (creation from other method handles)
4368 
4369     /**
4370      * Produces a method handle which adapts the type of the
4371      * given method handle to a new type by pairwise argument and return type conversion.
4372      * The original type and new type must have the same number of arguments.
4373      * The resulting method handle is guaranteed to report a type
4374      * which is equal to the desired new type.
4375      * <p>
4376      * If the original type and new type are equal, returns target.
4377      * <p>
4378      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4379      * and some additional conversions are also applied if those conversions fail.
4380      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4381      * if possible, before or instead of any conversions done by {@code asType}:
4382      * <ul>
4383      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4384      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4385      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4386      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4387      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4388      *     (This treatment follows the usage of the bytecode verifier.)
4389      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4390      *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
4391      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4392      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4393      *     then a Java casting conversion (JLS 5.5) is applied.
4394      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4395      *     widening and/or narrowing.)
4396      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4397      *     conversion will be applied at runtime, possibly followed
4398      *     by a Java casting conversion (JLS 5.5) on the primitive value,
4399      *     possibly followed by a conversion from byte to boolean by testing
4400      *     the low-order bit.
4401      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4402      *     and if the reference is null at runtime, a zero value is introduced.
4403      * </ul>
4404      * @param target the method handle to invoke after arguments are retyped
4405      * @param newType the expected type of the new method handle
4406      * @return a method handle which delegates to the target after performing
4407      *           any necessary argument conversions, and arranges for any
4408      *           necessary return value conversions
4409      * @throws NullPointerException if either argument is null
4410      * @throws WrongMethodTypeException if the conversion cannot be made
4411      * @see MethodHandle#asType
4412      */
4413     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4414         explicitCastArgumentsChecks(target, newType);
4415         // use the asTypeCache when possible:
4416         MethodType oldType = target.type();
4417         if (oldType == newType)  return target;
4418         if (oldType.explicitCastEquivalentToAsType(newType)) {
4419             return target.asFixedArity().asType(newType);
4420         }
4421         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4422     }
4423 
4424     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4425         if (target.type().parameterCount() != newType.parameterCount()) {
4426             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4427         }
4428     }
4429 
4430     /**
4431      * Produces a method handle which adapts the calling sequence of the
4432      * given method handle to a new type, by reordering the arguments.
4433      * The resulting method handle is guaranteed to report a type
4434      * which is equal to the desired new type.
4435      * <p>
4436      * The given array controls the reordering.
4437      * Call {@code #I} the number of incoming parameters (the value
4438      * {@code newType.parameterCount()}, and call {@code #O} the number
4439      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4440      * Then the length of the reordering array must be {@code #O},
4441      * and each element must be a non-negative number less than {@code #I}.
4442      * For every {@code N} less than {@code #O}, the {@code N}-th
4443      * outgoing argument will be taken from the {@code I}-th incoming
4444      * argument, where {@code I} is {@code reorder[N]}.
4445      * <p>
4446      * No argument or return value conversions are applied.
4447      * The type of each incoming argument, as determined by {@code newType},
4448      * must be identical to the type of the corresponding outgoing parameter
4449      * or parameters in the target method handle.
4450      * The return type of {@code newType} must be identical to the return
4451      * type of the original target.
4452      * <p>
4453      * The reordering array need not specify an actual permutation.
4454      * An incoming argument will be duplicated if its index appears
4455      * more than once in the array, and an incoming argument will be dropped
4456      * if its index does not appear in the array.
4457      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4458      * incoming arguments which are not mentioned in the reordering array
4459      * may be of any type, as determined only by {@code newType}.
4460      * <blockquote><pre>{@code
4461 import static java.lang.invoke.MethodHandles.*;
4462 import static java.lang.invoke.MethodType.*;
4463 ...
4464 MethodType intfn1 = methodType(int.class, int.class);
4465 MethodType intfn2 = methodType(int.class, int.class, int.class);
4466 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4467 assert(sub.type().equals(intfn2));
4468 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4469 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4470 assert((int)rsub.invokeExact(1, 100) == 99);
4471 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4472 assert(add.type().equals(intfn2));
4473 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4474 assert(twice.type().equals(intfn1));
4475 assert((int)twice.invokeExact(21) == 42);
4476      * }</pre></blockquote>
4477      * <p>
4478      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4479      * variable-arity method handle}, even if the original target method handle was.
4480      * @param target the method handle to invoke after arguments are reordered
4481      * @param newType the expected type of the new method handle
4482      * @param reorder an index array which controls the reordering
4483      * @return a method handle which delegates to the target after it
4484      *           drops unused arguments and moves and/or duplicates the other arguments
4485      * @throws NullPointerException if any argument is null
4486      * @throws IllegalArgumentException if the index array length is not equal to
4487      *                  the arity of the target, or if any index array element
4488      *                  not a valid index for a parameter of {@code newType},
4489      *                  or if two corresponding parameter types in
4490      *                  {@code target.type()} and {@code newType} are not identical,
4491      */
4492     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4493         reorder = reorder.clone();  // get a private copy
4494         MethodType oldType = target.type();
4495         permuteArgumentChecks(reorder, newType, oldType);
4496         // first detect dropped arguments and handle them separately
4497         int[] originalReorder = reorder;
4498         BoundMethodHandle result = target.rebind();
4499         LambdaForm form = result.form;
4500         int newArity = newType.parameterCount();
4501         // Normalize the reordering into a real permutation,
4502         // by removing duplicates and adding dropped elements.
4503         // This somewhat improves lambda form caching, as well
4504         // as simplifying the transform by breaking it up into steps.
4505         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4506             if (ddIdx > 0) {
4507                 // We found a duplicated entry at reorder[ddIdx].
4508                 // Example:  (x,y,z)->asList(x,y,z)
4509                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4510                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4511                 // The starred element corresponds to the argument
4512                 // deleted by the dupArgumentForm transform.
4513                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
4514                 boolean killFirst = false;
4515                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
4516                     // Set killFirst if the dup is larger than an intervening position.
4517                     // This will remove at least one inversion from the permutation.
4518                     if (dupVal > val) killFirst = true;
4519                 }
4520                 if (!killFirst) {
4521                     srcPos = dstPos;
4522                     dstPos = ddIdx;
4523                 }
4524                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
4525                 assert (reorder[srcPos] == reorder[dstPos]);
4526                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
4527                 // contract the reordering by removing the element at dstPos
4528                 int tailPos = dstPos + 1;
4529                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
4530                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
4531             } else {
4532                 int dropVal = ~ddIdx, insPos = 0;
4533                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
4534                     // Find first element of reorder larger than dropVal.
4535                     // This is where we will insert the dropVal.
4536                     insPos += 1;
4537                 }
4538                 Class<?> ptype = newType.parameterType(dropVal);
4539                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
4540                 oldType = oldType.insertParameterTypes(insPos, ptype);
4541                 // expand the reordering by inserting an element at insPos
4542                 int tailPos = insPos + 1;
4543                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
4544                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
4545                 reorder[insPos] = dropVal;
4546             }
4547             assert (permuteArgumentChecks(reorder, newType, oldType));
4548         }
4549         assert (reorder.length == newArity);  // a perfect permutation
4550         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
4551         form = form.editor().permuteArgumentsForm(1, reorder);
4552         if (newType == result.type() && form == result.internalForm())
4553             return result;
4554         return result.copyWith(newType, form);
4555     }
4556 
4557     /**
4558      * Return an indication of any duplicate or omission in reorder.
4559      * If the reorder contains a duplicate entry, return the index of the second occurrence.
4560      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
4561      * Otherwise, return zero.
4562      * If an element not in [0..newArity-1] is encountered, return reorder.length.
4563      */
4564     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
4565         final int BIT_LIMIT = 63;  // max number of bits in bit mask
4566         if (newArity < BIT_LIMIT) {
4567             long mask = 0;
4568             for (int i = 0; i < reorder.length; i++) {
4569                 int arg = reorder[i];
4570                 if (arg >= newArity) {
4571                     return reorder.length;
4572                 }
4573                 long bit = 1L << arg;
4574                 if ((mask & bit) != 0) {
4575                     return i;  // >0 indicates a dup
4576                 }
4577                 mask |= bit;
4578             }
4579             if (mask == (1L << newArity) - 1) {
4580                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
4581                 return 0;
4582             }
4583             // find first zero
4584             long zeroBit = Long.lowestOneBit(~mask);
4585             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
4586             assert(zeroPos <= newArity);
4587             if (zeroPos == newArity) {
4588                 return 0;
4589             }
4590             return ~zeroPos;
4591         } else {
4592             // same algorithm, different bit set
4593             BitSet mask = new BitSet(newArity);
4594             for (int i = 0; i < reorder.length; i++) {
4595                 int arg = reorder[i];
4596                 if (arg >= newArity) {
4597                     return reorder.length;
4598                 }
4599                 if (mask.get(arg)) {
4600                     return i;  // >0 indicates a dup
4601                 }
4602                 mask.set(arg);
4603             }
4604             int zeroPos = mask.nextClearBit(0);
4605             assert(zeroPos <= newArity);
4606             if (zeroPos == newArity) {
4607                 return 0;
4608             }
4609             return ~zeroPos;
4610         }
4611     }
4612 
4613     private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
4614         if (newType.returnType() != oldType.returnType())
4615             throw newIllegalArgumentException("return types do not match",
4616                     oldType, newType);
4617         if (reorder.length == oldType.parameterCount()) {
4618             int limit = newType.parameterCount();
4619             boolean bad = false;
4620             for (int j = 0; j < reorder.length; j++) {
4621                 int i = reorder[j];
4622                 if (i < 0 || i >= limit) {
4623                     bad = true; break;
4624                 }
4625                 Class<?> src = newType.parameterType(i);
4626                 Class<?> dst = oldType.parameterType(j);
4627                 if (src != dst)
4628                     throw newIllegalArgumentException("parameter types do not match after reorder",
4629                             oldType, newType);
4630             }
4631             if (!bad)  return true;
4632         }
4633         throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
4634     }
4635 
4636     /**
4637      * Produces a method handle of the requested return type which returns the given
4638      * constant value every time it is invoked.
4639      * <p>
4640      * Before the method handle is returned, the passed-in value is converted to the requested type.
4641      * If the requested type is primitive, widening primitive conversions are attempted,
4642      * else reference conversions are attempted.
4643      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
4644      * @param type the return type of the desired method handle
4645      * @param value the value to return
4646      * @return a method handle of the given return type and no arguments, which always returns the given value
4647      * @throws NullPointerException if the {@code type} argument is null
4648      * @throws ClassCastException if the value cannot be converted to the required return type
4649      * @throws IllegalArgumentException if the given type is {@code void.class}
4650      */
4651     public static MethodHandle constant(Class<?> type, Object value) {
4652         if (type.isPrimitive()) {
4653             if (type == void.class)
4654                 throw newIllegalArgumentException("void type");
4655             Wrapper w = Wrapper.forPrimitiveType(type);
4656             value = w.convert(value, type);
4657             if (w.zero().equals(value))
4658                 return zero(w, type);
4659             return insertArguments(identity(type), 0, value);
4660         } else {
4661             if (value == null)
4662                 return zero(Wrapper.OBJECT, type);
4663             return identity(type).bindTo(value);
4664         }
4665     }
4666 
4667     /**
4668      * Produces a method handle which returns its sole argument when invoked.
4669      * @param type the type of the sole parameter and return value of the desired method handle
4670      * @return a unary method handle which accepts and returns the given type
4671      * @throws NullPointerException if the argument is null
4672      * @throws IllegalArgumentException if the given type is {@code void.class}
4673      */
4674     public static MethodHandle identity(Class<?> type) {
4675         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
4676         int pos = btw.ordinal();
4677         MethodHandle ident = IDENTITY_MHS[pos];
4678         if (ident == null) {
4679             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
4680         }
4681         if (ident.type().returnType() == type)
4682             return ident;
4683         // something like identity(Foo.class); do not bother to intern these
4684         assert (btw == Wrapper.OBJECT);
4685         return makeIdentity(type);
4686     }
4687 
4688     /**
4689      * Produces a constant method handle of the requested return type which
4690      * returns the default value for that type every time it is invoked.
4691      * The resulting constant method handle will have no side effects.
4692      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
4693      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
4694      * since {@code explicitCastArguments} converts {@code null} to default values.
4695      * @param type the expected return type of the desired method handle
4696      * @return a constant method handle that takes no arguments
4697      *         and returns the default value of the given type (or void, if the type is void)
4698      * @throws NullPointerException if the argument is null
4699      * @see MethodHandles#constant
4700      * @see MethodHandles#empty
4701      * @see MethodHandles#explicitCastArguments
4702      * @since 9
4703      */
4704     public static MethodHandle zero(Class<?> type) {
4705         Objects.requireNonNull(type);
4706         return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
4707     }
4708 
4709     private static MethodHandle identityOrVoid(Class<?> type) {
4710         return type == void.class ? zero(type) : identity(type);
4711     }
4712 
4713     /**
4714      * Produces a method handle of the requested type which ignores any arguments, does nothing,
4715      * and returns a suitable default depending on the return type.
4716      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
4717      * <p>The returned method handle is equivalent to
4718      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
4719      *
4720      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
4721      * {@code guardWithTest(pred, target, empty(target.type())}.
4722      * @param type the type of the desired method handle
4723      * @return a constant method handle of the given type, which returns a default value of the given return type
4724      * @throws NullPointerException if the argument is null
4725      * @see MethodHandles#zero
4726      * @see MethodHandles#constant
4727      * @since 9
4728      */
4729     public static  MethodHandle empty(MethodType type) {
4730         Objects.requireNonNull(type);
4731         return dropArguments(zero(type.returnType()), 0, type.parameterList());
4732     }
4733 
4734     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
4735     private static MethodHandle makeIdentity(Class<?> ptype) {
4736         MethodType mtype = methodType(ptype, ptype);
4737         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
4738         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
4739     }
4740 
4741     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
4742         int pos = btw.ordinal();
4743         MethodHandle zero = ZERO_MHS[pos];
4744         if (zero == null) {
4745             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
4746         }
4747         if (zero.type().returnType() == rtype)
4748             return zero;
4749         assert(btw == Wrapper.OBJECT);
4750         return makeZero(rtype);
4751     }
4752     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
4753     private static MethodHandle makeZero(Class<?> rtype) {
4754         MethodType mtype = methodType(rtype);
4755         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
4756         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
4757     }
4758 
4759     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
4760         // Simulate a CAS, to avoid racy duplication of results.
4761         MethodHandle prev = cache[pos];
4762         if (prev != null) return prev;
4763         return cache[pos] = value;
4764     }
4765 
4766     /**
4767      * Provides a target method handle with one or more <em>bound arguments</em>
4768      * in advance of the method handle's invocation.
4769      * The formal parameters to the target corresponding to the bound
4770      * arguments are called <em>bound parameters</em>.
4771      * Returns a new method handle which saves away the bound arguments.
4772      * When it is invoked, it receives arguments for any non-bound parameters,
4773      * binds the saved arguments to their corresponding parameters,
4774      * and calls the original target.
4775      * <p>
4776      * The type of the new method handle will drop the types for the bound
4777      * parameters from the original target type, since the new method handle
4778      * will no longer require those arguments to be supplied by its callers.
4779      * <p>
4780      * Each given argument object must match the corresponding bound parameter type.
4781      * If a bound parameter type is a primitive, the argument object
4782      * must be a wrapper, and will be unboxed to produce the primitive value.
4783      * <p>
4784      * The {@code pos} argument selects which parameters are to be bound.
4785      * It may range between zero and <i>N-L</i> (inclusively),
4786      * where <i>N</i> is the arity of the target method handle
4787      * and <i>L</i> is the length of the values array.
4788      * <p>
4789      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4790      * variable-arity method handle}, even if the original target method handle was.
4791      * @param target the method handle to invoke after the argument is inserted
4792      * @param pos where to insert the argument (zero for the first)
4793      * @param values the series of arguments to insert
4794      * @return a method handle which inserts an additional argument,
4795      *         before calling the original method handle
4796      * @throws NullPointerException if the target or the {@code values} array is null
4797      * @throws IllegalArgumentException if (@code pos) is less than {@code 0} or greater than
4798      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
4799      *         is the length of the values array.
4800      * @throws ClassCastException if an argument does not match the corresponding bound parameter
4801      *         type.
4802      * @see MethodHandle#bindTo
4803      */
4804     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
4805         int insCount = values.length;
4806         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
4807         if (insCount == 0)  return target;
4808         BoundMethodHandle result = target.rebind();
4809         for (int i = 0; i < insCount; i++) {
4810             Object value = values[i];
4811             Class<?> ptype = ptypes[pos+i];
4812             if (ptype.isPrimitive()) {
4813                 result = insertArgumentPrimitive(result, pos, ptype, value);
4814             } else {
4815                 value = ptype.cast(value);  // throw CCE if needed
4816                 result = result.bindArgumentL(pos, value);
4817             }
4818         }
4819         return result;
4820     }
4821 
4822     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
4823                                                              Class<?> ptype, Object value) {
4824         Wrapper w = Wrapper.forPrimitiveType(ptype);
4825         // perform unboxing and/or primitive conversion
4826         value = w.convert(value, ptype);
4827         switch (w) {
4828         case INT:     return result.bindArgumentI(pos, (int)value);
4829         case LONG:    return result.bindArgumentJ(pos, (long)value);
4830         case FLOAT:   return result.bindArgumentF(pos, (float)value);
4831         case DOUBLE:  return result.bindArgumentD(pos, (double)value);
4832         default:      return result.bindArgumentI(pos, ValueConversions.widenSubword(value));
4833         }
4834     }
4835 
4836     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
4837         MethodType oldType = target.type();
4838         int outargs = oldType.parameterCount();
4839         int inargs  = outargs - insCount;
4840         if (inargs < 0)
4841             throw newIllegalArgumentException("too many values to insert");
4842         if (pos < 0 || pos > inargs)
4843             throw newIllegalArgumentException("no argument type to append");
4844         return oldType.ptypes();
4845     }
4846 
4847     /**
4848      * Produces a method handle which will discard some dummy arguments
4849      * before calling some other specified <i>target</i> method handle.
4850      * The type of the new method handle will be the same as the target's type,
4851      * except it will also include the dummy argument types,
4852      * at some given position.
4853      * <p>
4854      * The {@code pos} argument may range between zero and <i>N</i>,
4855      * where <i>N</i> is the arity of the target.
4856      * If {@code pos} is zero, the dummy arguments will precede
4857      * the target's real arguments; if {@code pos} is <i>N</i>
4858      * they will come after.
4859      * <p>
4860      * <b>Example:</b>
4861      * <blockquote><pre>{@code
4862 import static java.lang.invoke.MethodHandles.*;
4863 import static java.lang.invoke.MethodType.*;
4864 ...
4865 MethodHandle cat = lookup().findVirtual(String.class,
4866   "concat", methodType(String.class, String.class));
4867 assertEquals("xy", (String) cat.invokeExact("x", "y"));
4868 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
4869 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
4870 assertEquals(bigType, d0.type());
4871 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
4872      * }</pre></blockquote>
4873      * <p>
4874      * This method is also equivalent to the following code:
4875      * <blockquote><pre>
4876      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
4877      * </pre></blockquote>
4878      * @param target the method handle to invoke after the arguments are dropped
4879      * @param pos position of first argument to drop (zero for the leftmost)
4880      * @param valueTypes the type(s) of the argument(s) to drop
4881      * @return a method handle which drops arguments of the given types,
4882      *         before calling the original method handle
4883      * @throws NullPointerException if the target is null,
4884      *                              or if the {@code valueTypes} list or any of its elements is null
4885      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
4886      *                  or if {@code pos} is negative or greater than the arity of the target,
4887      *                  or if the new method handle's type would have too many parameters
4888      */
4889     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
4890         return dropArguments0(target, pos, copyTypes(valueTypes.toArray()));
4891     }
4892 
4893     private static List<Class<?>> copyTypes(Object[] array) {
4894         return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class));
4895     }
4896 
4897     private static MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) {
4898         MethodType oldType = target.type();  // get NPE
4899         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
4900         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
4901         if (dropped == 0)  return target;
4902         BoundMethodHandle result = target.rebind();
4903         LambdaForm lform = result.form;
4904         int insertFormArg = 1 + pos;
4905         for (Class<?> ptype : valueTypes) {
4906             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
4907         }
4908         result = result.copyWith(newType, lform);
4909         return result;
4910     }
4911 
4912     private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
4913         int dropped = valueTypes.size();
4914         MethodType.checkSlotCount(dropped);
4915         int outargs = oldType.parameterCount();
4916         int inargs  = outargs + dropped;
4917         if (pos < 0 || pos > outargs)
4918             throw newIllegalArgumentException("no argument type to remove"
4919                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
4920                     );
4921         return dropped;
4922     }
4923 
4924     /**
4925      * Produces a method handle which will discard some dummy arguments
4926      * before calling some other specified <i>target</i> method handle.
4927      * The type of the new method handle will be the same as the target's type,
4928      * except it will also include the dummy argument types,
4929      * at some given position.
4930      * <p>
4931      * The {@code pos} argument may range between zero and <i>N</i>,
4932      * where <i>N</i> is the arity of the target.
4933      * If {@code pos} is zero, the dummy arguments will precede
4934      * the target's real arguments; if {@code pos} is <i>N</i>
4935      * they will come after.
4936      * @apiNote
4937      * <blockquote><pre>{@code
4938 import static java.lang.invoke.MethodHandles.*;
4939 import static java.lang.invoke.MethodType.*;
4940 ...
4941 MethodHandle cat = lookup().findVirtual(String.class,
4942   "concat", methodType(String.class, String.class));
4943 assertEquals("xy", (String) cat.invokeExact("x", "y"));
4944 MethodHandle d0 = dropArguments(cat, 0, String.class);
4945 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
4946 MethodHandle d1 = dropArguments(cat, 1, String.class);
4947 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
4948 MethodHandle d2 = dropArguments(cat, 2, String.class);
4949 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
4950 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
4951 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
4952      * }</pre></blockquote>
4953      * <p>
4954      * This method is also equivalent to the following code:
4955      * <blockquote><pre>
4956      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
4957      * </pre></blockquote>
4958      * @param target the method handle to invoke after the arguments are dropped
4959      * @param pos position of first argument to drop (zero for the leftmost)
4960      * @param valueTypes the type(s) of the argument(s) to drop
4961      * @return a method handle which drops arguments of the given types,
4962      *         before calling the original method handle
4963      * @throws NullPointerException if the target is null,
4964      *                              or if the {@code valueTypes} array or any of its elements is null
4965      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
4966      *                  or if {@code pos} is negative or greater than the arity of the target,
4967      *                  or if the new method handle's type would have
4968      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
4969      */
4970     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
4971         return dropArguments0(target, pos, copyTypes(valueTypes));
4972     }
4973 
4974     // private version which allows caller some freedom with error handling
4975     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
4976                                       boolean nullOnFailure) {
4977         newTypes = copyTypes(newTypes.toArray());
4978         List<Class<?>> oldTypes = target.type().parameterList();
4979         int match = oldTypes.size();
4980         if (skip != 0) {
4981             if (skip < 0 || skip > match) {
4982                 throw newIllegalArgumentException("illegal skip", skip, target);
4983             }
4984             oldTypes = oldTypes.subList(skip, match);
4985             match -= skip;
4986         }
4987         List<Class<?>> addTypes = newTypes;
4988         int add = addTypes.size();
4989         if (pos != 0) {
4990             if (pos < 0 || pos > add) {
4991                 throw newIllegalArgumentException("illegal pos", pos, newTypes);
4992             }
4993             addTypes = addTypes.subList(pos, add);
4994             add -= pos;
4995             assert(addTypes.size() == add);
4996         }
4997         // Do not add types which already match the existing arguments.
4998         if (match > add || !oldTypes.equals(addTypes.subList(0, match))) {
4999             if (nullOnFailure) {
5000                 return null;
5001             }
5002             throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes);
5003         }
5004         addTypes = addTypes.subList(match, add);
5005         add -= match;
5006         assert(addTypes.size() == add);
5007         // newTypes:     (   P*[pos], M*[match], A*[add] )
5008         // target: ( S*[skip],        M*[match]  )
5009         MethodHandle adapter = target;
5010         if (add > 0) {
5011             adapter = dropArguments0(adapter, skip+ match, addTypes);
5012         }
5013         // adapter: (S*[skip],        M*[match], A*[add] )
5014         if (pos > 0) {
5015             adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos));
5016         }
5017         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5018         return adapter;
5019     }
5020 
5021     /**
5022      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5023      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5024      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5025      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5026      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5027      * {@link #dropArguments(MethodHandle, int, Class[])}.
5028      * <p>
5029      * The resulting handle will have the same return type as the target handle.
5030      * <p>
5031      * In more formal terms, assume these two type lists:<ul>
5032      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5033      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5034      * {@code newTypes}.
5035      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5036      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5037      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5038      * sub-list.
5039      * </ul>
5040      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5041      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5042      * {@link #dropArguments(MethodHandle, int, Class[])}.
5043      *
5044      * @apiNote
5045      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5046      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5047      * <blockquote><pre>{@code
5048 import static java.lang.invoke.MethodHandles.*;
5049 import static java.lang.invoke.MethodType.*;
5050 ...
5051 ...
5052 MethodHandle h0 = constant(boolean.class, true);
5053 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5054 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5055 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5056 if (h1.type().parameterCount() < h2.type().parameterCount())
5057     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5058 else
5059     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5060 MethodHandle h3 = guardWithTest(h0, h1, h2);
5061 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5062      * }</pre></blockquote>
5063      * @param target the method handle to adapt
5064      * @param skip number of targets parameters to disregard (they will be unchanged)
5065      * @param newTypes the list of types to match {@code target}'s parameter type list to
5066      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5067      * @return a possibly adapted method handle
5068      * @throws NullPointerException if either argument is null
5069      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5070      *         or if {@code skip} is negative or greater than the arity of the target,
5071      *         or if {@code pos} is negative or greater than the newTypes list size,
5072      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5073      *         {@code pos}.
5074      * @since 9
5075      */
5076     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5077         Objects.requireNonNull(target);
5078         Objects.requireNonNull(newTypes);
5079         return dropArgumentsToMatch(target, skip, newTypes, pos, false);
5080     }
5081 
5082     /**
5083      * Adapts a target method handle by pre-processing
5084      * one or more of its arguments, each with its own unary filter function,
5085      * and then calling the target with each pre-processed argument
5086      * replaced by the result of its corresponding filter function.
5087      * <p>
5088      * The pre-processing is performed by one or more method handles,
5089      * specified in the elements of the {@code filters} array.
5090      * The first element of the filter array corresponds to the {@code pos}
5091      * argument of the target, and so on in sequence.
5092      * The filter functions are invoked in left to right order.
5093      * <p>
5094      * Null arguments in the array are treated as identity functions,
5095      * and the corresponding arguments left unchanged.
5096      * (If there are no non-null elements in the array, the original target is returned.)
5097      * Each filter is applied to the corresponding argument of the adapter.
5098      * <p>
5099      * If a filter {@code F} applies to the {@code N}th argument of
5100      * the target, then {@code F} must be a method handle which
5101      * takes exactly one argument.  The type of {@code F}'s sole argument
5102      * replaces the corresponding argument type of the target
5103      * in the resulting adapted method handle.
5104      * The return type of {@code F} must be identical to the corresponding
5105      * parameter type of the target.
5106      * <p>
5107      * It is an error if there are elements of {@code filters}
5108      * (null or not)
5109      * which do not correspond to argument positions in the target.
5110      * <p><b>Example:</b>
5111      * <blockquote><pre>{@code
5112 import static java.lang.invoke.MethodHandles.*;
5113 import static java.lang.invoke.MethodType.*;
5114 ...
5115 MethodHandle cat = lookup().findVirtual(String.class,
5116   "concat", methodType(String.class, String.class));
5117 MethodHandle upcase = lookup().findVirtual(String.class,
5118   "toUpperCase", methodType(String.class));
5119 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5120 MethodHandle f0 = filterArguments(cat, 0, upcase);
5121 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5122 MethodHandle f1 = filterArguments(cat, 1, upcase);
5123 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5124 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5125 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5126      * }</pre></blockquote>
5127      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5128      * denotes the return type of both the {@code target} and resulting adapter.
5129      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5130      * of the parameters and arguments that precede and follow the filter position
5131      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5132      * values of the filtered parameters and arguments; they also represent the
5133      * return types of the {@code filter[i]} handles. The latter accept arguments
5134      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5135      * the resulting adapter.
5136      * <blockquote><pre>{@code
5137      * T target(P... p, A[i]... a[i], B... b);
5138      * A[i] filter[i](V[i]);
5139      * T adapter(P... p, V[i]... v[i], B... b) {
5140      *   return target(p..., filter[i](v[i])..., b...);
5141      * }
5142      * }</pre></blockquote>
5143      * <p>
5144      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5145      * variable-arity method handle}, even if the original target method handle was.
5146      *
5147      * @param target the method handle to invoke after arguments are filtered
5148      * @param pos the position of the first argument to filter
5149      * @param filters method handles to call initially on filtered arguments
5150      * @return method handle which incorporates the specified argument filtering logic
5151      * @throws NullPointerException if the target is null
5152      *                              or if the {@code filters} array is null
5153      * @throws IllegalArgumentException if a non-null element of {@code filters}
5154      *          does not match a corresponding argument type of target as described above,
5155      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5156      *          or if the resulting method handle's type would have
5157      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5158      */
5159     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5160         // In method types arguments start at index 0, while the LF
5161         // editor have the MH receiver at position 0 - adjust appropriately.
5162         final int MH_RECEIVER_OFFSET = 1;
5163         filterArgumentsCheckArity(target, pos, filters);
5164         MethodHandle adapter = target;
5165 
5166         // keep track of currently matched filters, as to optimize repeated filters
5167         int index = 0;
5168         int[] positions = new int[filters.length];
5169         MethodHandle filter = null;
5170 
5171         // process filters in reverse order so that the invocation of
5172         // the resulting adapter will invoke the filters in left-to-right order
5173         for (int i = filters.length - 1; i >= 0; --i) {
5174             MethodHandle newFilter = filters[i];
5175             if (newFilter == null) continue;  // ignore null elements of filters
5176 
5177             // flush changes on update
5178             if (filter != newFilter) {
5179                 if (filter != null) {
5180                     if (index > 1) {
5181                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5182                     } else {
5183                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5184                     }
5185                 }
5186                 filter = newFilter;
5187                 index = 0;
5188             }
5189 
5190             filterArgumentChecks(target, pos + i, newFilter);
5191             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5192         }
5193         if (index > 1) {
5194             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5195         } else if (index == 1) {
5196             adapter = filterArgument(adapter, positions[0] - 1, filter);
5197         }
5198         return adapter;
5199     }
5200 
5201     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5202         MethodType targetType = adapter.type();
5203         MethodType filterType = filter.type();
5204         BoundMethodHandle result = adapter.rebind();
5205         Class<?> newParamType = filterType.parameterType(0);
5206 
5207         Class<?>[] ptypes = targetType.ptypes().clone();
5208         for (int pos : positions) {
5209             ptypes[pos - 1] = newParamType;
5210         }
5211         MethodType newType = MethodType.makeImpl(targetType.rtype(), ptypes, true);
5212 
5213         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5214         return result.copyWithExtendL(newType, lform, filter);
5215     }
5216 
5217     /*non-public*/
5218     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5219         filterArgumentChecks(target, pos, filter);
5220         MethodType targetType = target.type();
5221         MethodType filterType = filter.type();
5222         BoundMethodHandle result = target.rebind();
5223         Class<?> newParamType = filterType.parameterType(0);
5224         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5225         MethodType newType = targetType.changeParameterType(pos, newParamType);
5226         result = result.copyWithExtendL(newType, lform, filter);
5227         return result;
5228     }
5229 
5230     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5231         MethodType targetType = target.type();
5232         int maxPos = targetType.parameterCount();
5233         if (pos + filters.length > maxPos)
5234             throw newIllegalArgumentException("too many filters");
5235     }
5236 
5237     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5238         MethodType targetType = target.type();
5239         MethodType filterType = filter.type();
5240         if (filterType.parameterCount() != 1
5241             || filterType.returnType() != targetType.parameterType(pos))
5242             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5243     }
5244 
5245     /**
5246      * Adapts a target method handle by pre-processing
5247      * a sub-sequence of its arguments with a filter (another method handle).
5248      * The pre-processed arguments are replaced by the result (if any) of the
5249      * filter function.
5250      * The target is then called on the modified (usually shortened) argument list.
5251      * <p>
5252      * If the filter returns a value, the target must accept that value as
5253      * its argument in position {@code pos}, preceded and/or followed by
5254      * any arguments not passed to the filter.
5255      * If the filter returns void, the target must accept all arguments
5256      * not passed to the filter.
5257      * No arguments are reordered, and a result returned from the filter
5258      * replaces (in order) the whole subsequence of arguments originally
5259      * passed to the adapter.
5260      * <p>
5261      * The argument types (if any) of the filter
5262      * replace zero or one argument types of the target, at position {@code pos},
5263      * in the resulting adapted method handle.
5264      * The return type of the filter (if any) must be identical to the
5265      * argument type of the target at position {@code pos}, and that target argument
5266      * is supplied by the return value of the filter.
5267      * <p>
5268      * In all cases, {@code pos} must be greater than or equal to zero, and
5269      * {@code pos} must also be less than or equal to the target's arity.
5270      * <p><b>Example:</b>
5271      * <blockquote><pre>{@code
5272 import static java.lang.invoke.MethodHandles.*;
5273 import static java.lang.invoke.MethodType.*;
5274 ...
5275 MethodHandle deepToString = publicLookup()
5276   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5277 
5278 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5279 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5280 
5281 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5282 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5283 
5284 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5285 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5286 assertEquals("[top, [up, down], strange]",
5287              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5288 
5289 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5290 assertEquals("[top, [up, down], [strange]]",
5291              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5292 
5293 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5294 assertEquals("[top, [[up, down, strange], charm], bottom]",
5295              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5296      * }</pre></blockquote>
5297      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5298      * represents the return type of the {@code target} and resulting adapter.
5299      * {@code V}/{@code v} stand for the return type and value of the
5300      * {@code filter}, which are also found in the signature and arguments of
5301      * the {@code target}, respectively, unless {@code V} is {@code void}.
5302      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5303      * and values preceding and following the collection position, {@code pos},
5304      * in the {@code target}'s signature. They also turn up in the resulting
5305      * adapter's signature and arguments, where they surround
5306      * {@code B}/{@code b}, which represent the parameter types and arguments
5307      * to the {@code filter} (if any).
5308      * <blockquote><pre>{@code
5309      * T target(A...,V,C...);
5310      * V filter(B...);
5311      * T adapter(A... a,B... b,C... c) {
5312      *   V v = filter(b...);
5313      *   return target(a...,v,c...);
5314      * }
5315      * // and if the filter has no arguments:
5316      * T target2(A...,V,C...);
5317      * V filter2();
5318      * T adapter2(A... a,C... c) {
5319      *   V v = filter2();
5320      *   return target2(a...,v,c...);
5321      * }
5322      * // and if the filter has a void return:
5323      * T target3(A...,C...);
5324      * void filter3(B...);
5325      * T adapter3(A... a,B... b,C... c) {
5326      *   filter3(b...);
5327      *   return target3(a...,c...);
5328      * }
5329      * }</pre></blockquote>
5330      * <p>
5331      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5332      * one which first "folds" the affected arguments, and then drops them, in separate
5333      * steps as follows:
5334      * <blockquote><pre>{@code
5335      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5336      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5337      * }</pre></blockquote>
5338      * If the target method handle consumes no arguments besides than the result
5339      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5340      * is equivalent to {@code filterReturnValue(coll, mh)}.
5341      * If the filter method handle {@code coll} consumes one argument and produces
5342      * a non-void result, then {@code collectArguments(mh, N, coll)}
5343      * is equivalent to {@code filterArguments(mh, N, coll)}.
5344      * Other equivalences are possible but would require argument permutation.
5345      * <p>
5346      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5347      * variable-arity method handle}, even if the original target method handle was.
5348      *
5349      * @param target the method handle to invoke after filtering the subsequence of arguments
5350      * @param pos the position of the first adapter argument to pass to the filter,
5351      *            and/or the target argument which receives the result of the filter
5352      * @param filter method handle to call on the subsequence of arguments
5353      * @return method handle which incorporates the specified argument subsequence filtering logic
5354      * @throws NullPointerException if either argument is null
5355      * @throws IllegalArgumentException if the return type of {@code filter}
5356      *          is non-void and is not the same as the {@code pos} argument of the target,
5357      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5358      *          or if the resulting method handle's type would have
5359      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5360      * @see MethodHandles#foldArguments
5361      * @see MethodHandles#filterArguments
5362      * @see MethodHandles#filterReturnValue
5363      */
5364     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5365         MethodType newType = collectArgumentsChecks(target, pos, filter);
5366         MethodType collectorType = filter.type();
5367         BoundMethodHandle result = target.rebind();
5368         LambdaForm lform;
5369         if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) {
5370             lform = result.editor().collectArgumentArrayForm(1 + pos, filter);
5371             if (lform != null) {
5372                 return result.copyWith(newType, lform);
5373             }
5374         }
5375         lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5376         return result.copyWithExtendL(newType, lform, filter);
5377     }
5378 
5379     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5380         MethodType targetType = target.type();
5381         MethodType filterType = filter.type();
5382         Class<?> rtype = filterType.returnType();
5383         List<Class<?>> filterArgs = filterType.parameterList();
5384         if (rtype == void.class) {
5385             return targetType.insertParameterTypes(pos, filterArgs);
5386         }
5387         if (rtype != targetType.parameterType(pos)) {
5388             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5389         }
5390         return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
5391     }
5392 
5393     /**
5394      * Adapts a target method handle by post-processing
5395      * its return value (if any) with a filter (another method handle).
5396      * The result of the filter is returned from the adapter.
5397      * <p>
5398      * If the target returns a value, the filter must accept that value as
5399      * its only argument.
5400      * If the target returns void, the filter must accept no arguments.
5401      * <p>
5402      * The return type of the filter
5403      * replaces the return type of the target
5404      * in the resulting adapted method handle.
5405      * The argument type of the filter (if any) must be identical to the
5406      * return type of the target.
5407      * <p><b>Example:</b>
5408      * <blockquote><pre>{@code
5409 import static java.lang.invoke.MethodHandles.*;
5410 import static java.lang.invoke.MethodType.*;
5411 ...
5412 MethodHandle cat = lookup().findVirtual(String.class,
5413   "concat", methodType(String.class, String.class));
5414 MethodHandle length = lookup().findVirtual(String.class,
5415   "length", methodType(int.class));
5416 System.out.println((String) cat.invokeExact("x", "y")); // xy
5417 MethodHandle f0 = filterReturnValue(cat, length);
5418 System.out.println((int) f0.invokeExact("x", "y")); // 2
5419      * }</pre></blockquote>
5420      * <p>Here is pseudocode for the resulting adapter. In the code,
5421      * {@code T}/{@code t} represent the result type and value of the
5422      * {@code target}; {@code V}, the result type of the {@code filter}; and
5423      * {@code A}/{@code a}, the types and values of the parameters and arguments
5424      * of the {@code target} as well as the resulting adapter.
5425      * <blockquote><pre>{@code
5426      * T target(A...);
5427      * V filter(T);
5428      * V adapter(A... a) {
5429      *   T t = target(a...);
5430      *   return filter(t);
5431      * }
5432      * // and if the target has a void return:
5433      * void target2(A...);
5434      * V filter2();
5435      * V adapter2(A... a) {
5436      *   target2(a...);
5437      *   return filter2();
5438      * }
5439      * // and if the filter has a void return:
5440      * T target3(A...);
5441      * void filter3(V);
5442      * void adapter3(A... a) {
5443      *   T t = target3(a...);
5444      *   filter3(t);
5445      * }
5446      * }</pre></blockquote>
5447      * <p>
5448      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5449      * variable-arity method handle}, even if the original target method handle was.
5450      * @param target the method handle to invoke before filtering the return value
5451      * @param filter method handle to call on the return value
5452      * @return method handle which incorporates the specified return value filtering logic
5453      * @throws NullPointerException if either argument is null
5454      * @throws IllegalArgumentException if the argument list of {@code filter}
5455      *          does not match the return type of target as described above
5456      */
5457     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5458         MethodType targetType = target.type();
5459         MethodType filterType = filter.type();
5460         filterReturnValueChecks(targetType, filterType);
5461         BoundMethodHandle result = target.rebind();
5462         BasicType rtype = BasicType.basicType(filterType.returnType());
5463         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5464         MethodType newType = targetType.changeReturnType(filterType.returnType());
5465         result = result.copyWithExtendL(newType, lform, filter);
5466         return result;
5467     }
5468 
5469     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5470         Class<?> rtype = targetType.returnType();
5471         int filterValues = filterType.parameterCount();
5472         if (filterValues == 0
5473                 ? (rtype != void.class)
5474                 : (rtype != filterType.parameterType(0) || filterValues != 1))
5475             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5476     }
5477 
5478     /**
5479      * Adapts a target method handle by pre-processing
5480      * some of its arguments, and then calling the target with
5481      * the result of the pre-processing, inserted into the original
5482      * sequence of arguments.
5483      * <p>
5484      * The pre-processing is performed by {@code combiner}, a second method handle.
5485      * Of the arguments passed to the adapter, the first {@code N} arguments
5486      * are copied to the combiner, which is then called.
5487      * (Here, {@code N} is defined as the parameter count of the combiner.)
5488      * After this, control passes to the target, with any result
5489      * from the combiner inserted before the original {@code N} incoming
5490      * arguments.
5491      * <p>
5492      * If the combiner returns a value, the first parameter type of the target
5493      * must be identical with the return type of the combiner, and the next
5494      * {@code N} parameter types of the target must exactly match the parameters
5495      * of the combiner.
5496      * <p>
5497      * If the combiner has a void return, no result will be inserted,
5498      * and the first {@code N} parameter types of the target
5499      * must exactly match the parameters of the combiner.
5500      * <p>
5501      * The resulting adapter is the same type as the target, except that the
5502      * first parameter type is dropped,
5503      * if it corresponds to the result of the combiner.
5504      * <p>
5505      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
5506      * that either the combiner or the target does not wish to receive.
5507      * If some of the incoming arguments are destined only for the combiner,
5508      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
5509      * arguments will not need to be live on the stack on entry to the
5510      * target.)
5511      * <p><b>Example:</b>
5512      * <blockquote><pre>{@code
5513 import static java.lang.invoke.MethodHandles.*;
5514 import static java.lang.invoke.MethodType.*;
5515 ...
5516 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5517   "println", methodType(void.class, String.class))
5518     .bindTo(System.out);
5519 MethodHandle cat = lookup().findVirtual(String.class,
5520   "concat", methodType(String.class, String.class));
5521 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5522 MethodHandle catTrace = foldArguments(cat, trace);
5523 // also prints "boo":
5524 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5525      * }</pre></blockquote>
5526      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5527      * represents the result type of the {@code target} and resulting adapter.
5528      * {@code V}/{@code v} represent the type and value of the parameter and argument
5529      * of {@code target} that precedes the folding position; {@code V} also is
5530      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
5531      * types and values of the {@code N} parameters and arguments at the folding
5532      * position. {@code B}/{@code b} represent the types and values of the
5533      * {@code target} parameters and arguments that follow the folded parameters
5534      * and arguments.
5535      * <blockquote><pre>{@code
5536      * // there are N arguments in A...
5537      * T target(V, A[N]..., B...);
5538      * V combiner(A...);
5539      * T adapter(A... a, B... b) {
5540      *   V v = combiner(a...);
5541      *   return target(v, a..., b...);
5542      * }
5543      * // and if the combiner has a void return:
5544      * T target2(A[N]..., B...);
5545      * void combiner2(A...);
5546      * T adapter2(A... a, B... b) {
5547      *   combiner2(a...);
5548      *   return target2(a..., b...);
5549      * }
5550      * }</pre></blockquote>
5551      * <p>
5552      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5553      * variable-arity method handle}, even if the original target method handle was.
5554      * @param target the method handle to invoke after arguments are combined
5555      * @param combiner method handle to call initially on the incoming arguments
5556      * @return method handle which incorporates the specified argument folding logic
5557      * @throws NullPointerException if either argument is null
5558      * @throws IllegalArgumentException if {@code combiner}'s return type
5559      *          is non-void and not the same as the first argument type of
5560      *          the target, or if the initial {@code N} argument types
5561      *          of the target
5562      *          (skipping one matching the {@code combiner}'s return type)
5563      *          are not identical with the argument types of {@code combiner}
5564      */
5565     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
5566         return foldArguments(target, 0, combiner);
5567     }
5568 
5569     /**
5570      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
5571      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
5572      * before the folded arguments.
5573      * <p>
5574      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
5575      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
5576      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
5577      * 0.
5578      *
5579      * @apiNote Example:
5580      * <blockquote><pre>{@code
5581     import static java.lang.invoke.MethodHandles.*;
5582     import static java.lang.invoke.MethodType.*;
5583     ...
5584     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5585     "println", methodType(void.class, String.class))
5586     .bindTo(System.out);
5587     MethodHandle cat = lookup().findVirtual(String.class,
5588     "concat", methodType(String.class, String.class));
5589     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5590     MethodHandle catTrace = foldArguments(cat, 1, trace);
5591     // also prints "jum":
5592     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5593      * }</pre></blockquote>
5594      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5595      * represents the result type of the {@code target} and resulting adapter.
5596      * {@code V}/{@code v} represent the type and value of the parameter and argument
5597      * of {@code target} that precedes the folding position; {@code V} also is
5598      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
5599      * types and values of the {@code N} parameters and arguments at the folding
5600      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
5601      * and values of the {@code target} parameters and arguments that precede and
5602      * follow the folded parameters and arguments starting at {@code pos},
5603      * respectively.
5604      * <blockquote><pre>{@code
5605      * // there are N arguments in A...
5606      * T target(Z..., V, A[N]..., B...);
5607      * V combiner(A...);
5608      * T adapter(Z... z, A... a, B... b) {
5609      *   V v = combiner(a...);
5610      *   return target(z..., v, a..., b...);
5611      * }
5612      * // and if the combiner has a void return:
5613      * T target2(Z..., A[N]..., B...);
5614      * void combiner2(A...);
5615      * T adapter2(Z... z, A... a, B... b) {
5616      *   combiner2(a...);
5617      *   return target2(z..., a..., b...);
5618      * }
5619      * }</pre></blockquote>
5620      * <p>
5621      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5622      * variable-arity method handle}, even if the original target method handle was.
5623      *
5624      * @param target the method handle to invoke after arguments are combined
5625      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
5626      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
5627      * @param combiner method handle to call initially on the incoming arguments
5628      * @return method handle which incorporates the specified argument folding logic
5629      * @throws NullPointerException if either argument is null
5630      * @throws IllegalArgumentException if either of the following two conditions holds:
5631      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
5632      *              {@code pos} of the target signature;
5633      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
5634      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
5635      *
5636      * @see #foldArguments(MethodHandle, MethodHandle)
5637      * @since 9
5638      */
5639     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
5640         MethodType targetType = target.type();
5641         MethodType combinerType = combiner.type();
5642         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
5643         BoundMethodHandle result = target.rebind();
5644         boolean dropResult = rtype == void.class;
5645         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
5646         MethodType newType = targetType;
5647         if (!dropResult) {
5648             newType = newType.dropParameterTypes(pos, pos + 1);
5649         }
5650         result = result.copyWithExtendL(newType, lform, combiner);
5651         return result;
5652     }
5653 
5654     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
5655         int foldArgs   = combinerType.parameterCount();
5656         Class<?> rtype = combinerType.returnType();
5657         int foldVals = rtype == void.class ? 0 : 1;
5658         int afterInsertPos = foldPos + foldVals;
5659         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
5660         if (ok) {
5661             for (int i = 0; i < foldArgs; i++) {
5662                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
5663                     ok = false;
5664                     break;
5665                 }
5666             }
5667         }
5668         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
5669             ok = false;
5670         if (!ok)
5671             throw misMatchedTypes("target and combiner types", targetType, combinerType);
5672         return rtype;
5673     }
5674 
5675     /**
5676      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
5677      * of the pre-processing replacing the argument at the given position.
5678      *
5679      * @param target the method handle to invoke after arguments are combined
5680      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
5681      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
5682      * @param combiner method handle to call initially on the incoming arguments
5683      * @param argPositions indexes of the target to pick arguments sent to the combiner from
5684      * @return method handle which incorporates the specified argument folding logic
5685      * @throws NullPointerException if either argument is null
5686      * @throws IllegalArgumentException if either of the following two conditions holds:
5687      *          (1) {@code combiner}'s return type is not the same as the argument type at position
5688      *              {@code pos} of the target signature;
5689      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
5690      *              not identical with the argument types of {@code combiner}.
5691      */
5692     /*non-public*/
5693     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
5694         return argumentsWithCombiner(true, target, position, combiner, argPositions);
5695     }
5696 
5697     /**
5698      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
5699      * the pre-processing inserted into the original sequence of arguments at the given position.
5700      *
5701      * @param target the method handle to invoke after arguments are combined
5702      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
5703      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
5704      * @param combiner method handle to call initially on the incoming arguments
5705      * @param argPositions indexes of the target to pick arguments sent to the combiner from
5706      * @return method handle which incorporates the specified argument folding logic
5707      * @throws NullPointerException if either argument is null
5708      * @throws IllegalArgumentException if either of the following two conditions holds:
5709      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
5710      *              {@code pos} of the target signature;
5711      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
5712      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
5713      *              with the argument types of {@code combiner}.
5714      */
5715     /*non-public*/
5716     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
5717         return argumentsWithCombiner(false, target, position, combiner, argPositions);
5718     }
5719 
5720     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
5721         MethodType targetType = target.type();
5722         MethodType combinerType = combiner.type();
5723         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
5724         BoundMethodHandle result = target.rebind();
5725 
5726         MethodType newType = targetType;
5727         LambdaForm lform;
5728         if (filter) {
5729             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
5730         } else {
5731             boolean dropResult = rtype == void.class;
5732             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
5733             if (!dropResult) {
5734                 newType = newType.dropParameterTypes(position, position + 1);
5735             }
5736         }
5737         result = result.copyWithExtendL(newType, lform, combiner);
5738         return result;
5739     }
5740 
5741     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
5742         int combinerArgs = combinerType.parameterCount();
5743         if (argPos.length != combinerArgs) {
5744             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
5745         }
5746         Class<?> rtype = combinerType.returnType();
5747 
5748         for (int i = 0; i < combinerArgs; i++) {
5749             int arg = argPos[i];
5750             if (arg < 0 || arg > targetType.parameterCount()) {
5751                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
5752             }
5753             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
5754                 throw newIllegalArgumentException("target argument type at position " + arg
5755                         + " must match combiner argument type at index " + i + ": " + targetType
5756                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
5757             }
5758         }
5759         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
5760             throw misMatchedTypes("target and combiner types", targetType, combinerType);
5761         }
5762         return rtype;
5763     }
5764 
5765     /**
5766      * Makes a method handle which adapts a target method handle,
5767      * by guarding it with a test, a boolean-valued method handle.
5768      * If the guard fails, a fallback handle is called instead.
5769      * All three method handles must have the same corresponding
5770      * argument and return types, except that the return type
5771      * of the test must be boolean, and the test is allowed
5772      * to have fewer arguments than the other two method handles.
5773      * <p>
5774      * Here is pseudocode for the resulting adapter. In the code, {@code T}
5775      * represents the uniform result type of the three involved handles;
5776      * {@code A}/{@code a}, the types and values of the {@code target}
5777      * parameters and arguments that are consumed by the {@code test}; and
5778      * {@code B}/{@code b}, those types and values of the {@code target}
5779      * parameters and arguments that are not consumed by the {@code test}.
5780      * <blockquote><pre>{@code
5781      * boolean test(A...);
5782      * T target(A...,B...);
5783      * T fallback(A...,B...);
5784      * T adapter(A... a,B... b) {
5785      *   if (test(a...))
5786      *     return target(a..., b...);
5787      *   else
5788      *     return fallback(a..., b...);
5789      * }
5790      * }</pre></blockquote>
5791      * Note that the test arguments ({@code a...} in the pseudocode) cannot
5792      * be modified by execution of the test, and so are passed unchanged
5793      * from the caller to the target or fallback as appropriate.
5794      * @param test method handle used for test, must return boolean
5795      * @param target method handle to call if test passes
5796      * @param fallback method handle to call if test fails
5797      * @return method handle which incorporates the specified if/then/else logic
5798      * @throws NullPointerException if any argument is null
5799      * @throws IllegalArgumentException if {@code test} does not return boolean,
5800      *          or if all three method types do not match (with the return
5801      *          type of {@code test} changed to match that of the target).
5802      */
5803     public static MethodHandle guardWithTest(MethodHandle test,
5804                                MethodHandle target,
5805                                MethodHandle fallback) {
5806         MethodType gtype = test.type();
5807         MethodType ttype = target.type();
5808         MethodType ftype = fallback.type();
5809         if (!ttype.equals(ftype))
5810             throw misMatchedTypes("target and fallback types", ttype, ftype);
5811         if (gtype.returnType() != boolean.class)
5812             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
5813         List<Class<?>> targs = ttype.parameterList();
5814         test = dropArgumentsToMatch(test, 0, targs, 0, true);
5815         if (test == null) {
5816             throw misMatchedTypes("target and test types", ttype, gtype);
5817         }
5818         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
5819     }
5820 
5821     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
5822         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
5823     }
5824 
5825     /**
5826      * Makes a method handle which adapts a target method handle,
5827      * by running it inside an exception handler.
5828      * If the target returns normally, the adapter returns that value.
5829      * If an exception matching the specified type is thrown, the fallback
5830      * handle is called instead on the exception, plus the original arguments.
5831      * <p>
5832      * The target and handler must have the same corresponding
5833      * argument and return types, except that handler may omit trailing arguments
5834      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
5835      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
5836      * <p>
5837      * Here is pseudocode for the resulting adapter. In the code, {@code T}
5838      * represents the return type of the {@code target} and {@code handler},
5839      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
5840      * the types and values of arguments to the resulting handle consumed by
5841      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
5842      * resulting handle discarded by {@code handler}.
5843      * <blockquote><pre>{@code
5844      * T target(A..., B...);
5845      * T handler(ExType, A...);
5846      * T adapter(A... a, B... b) {
5847      *   try {
5848      *     return target(a..., b...);
5849      *   } catch (ExType ex) {
5850      *     return handler(ex, a...);
5851      *   }
5852      * }
5853      * }</pre></blockquote>
5854      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
5855      * be modified by execution of the target, and so are passed unchanged
5856      * from the caller to the handler, if the handler is invoked.
5857      * <p>
5858      * The target and handler must return the same type, even if the handler
5859      * always throws.  (This might happen, for instance, because the handler
5860      * is simulating a {@code finally} clause).
5861      * To create such a throwing handler, compose the handler creation logic
5862      * with {@link #throwException throwException},
5863      * in order to create a method handle of the correct return type.
5864      * @param target method handle to call
5865      * @param exType the type of exception which the handler will catch
5866      * @param handler method handle to call if a matching exception is thrown
5867      * @return method handle which incorporates the specified try/catch logic
5868      * @throws NullPointerException if any argument is null
5869      * @throws IllegalArgumentException if {@code handler} does not accept
5870      *          the given exception type, or if the method handle types do
5871      *          not match in their return types and their
5872      *          corresponding parameters
5873      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
5874      */
5875     public static MethodHandle catchException(MethodHandle target,
5876                                 Class<? extends Throwable> exType,
5877                                 MethodHandle handler) {
5878         MethodType ttype = target.type();
5879         MethodType htype = handler.type();
5880         if (!Throwable.class.isAssignableFrom(exType))
5881             throw new ClassCastException(exType.getName());
5882         if (htype.parameterCount() < 1 ||
5883             !htype.parameterType(0).isAssignableFrom(exType))
5884             throw newIllegalArgumentException("handler does not accept exception type "+exType);
5885         if (htype.returnType() != ttype.returnType())
5886             throw misMatchedTypes("target and handler return types", ttype, htype);
5887         handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
5888         if (handler == null) {
5889             throw misMatchedTypes("target and handler types", ttype, htype);
5890         }
5891         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
5892     }
5893 
5894     /**
5895      * Produces a method handle which will throw exceptions of the given {@code exType}.
5896      * The method handle will accept a single argument of {@code exType},
5897      * and immediately throw it as an exception.
5898      * The method type will nominally specify a return of {@code returnType}.
5899      * The return type may be anything convenient:  It doesn't matter to the
5900      * method handle's behavior, since it will never return normally.
5901      * @param returnType the return type of the desired method handle
5902      * @param exType the parameter type of the desired method handle
5903      * @return method handle which can throw the given exceptions
5904      * @throws NullPointerException if either argument is null
5905      */
5906     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
5907         if (!Throwable.class.isAssignableFrom(exType))
5908             throw new ClassCastException(exType.getName());
5909         return MethodHandleImpl.throwException(methodType(returnType, exType));
5910     }
5911 
5912     /**
5913      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
5914      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
5915      * delivers the loop's result, which is the return value of the resulting handle.
5916      * <p>
5917      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
5918      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
5919      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
5920      * terms of method handles, each clause will specify up to four independent actions:<ul>
5921      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
5922      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
5923      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
5924      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
5925      * </ul>
5926      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
5927      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
5928      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
5929      * <p>
5930      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
5931      * this case. See below for a detailed description.
5932      * <p>
5933      * <em>Parameters optional everywhere:</em>
5934      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
5935      * As an exception, the init functions cannot take any {@code v} parameters,
5936      * because those values are not yet computed when the init functions are executed.
5937      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
5938      * In fact, any clause function may take no arguments at all.
5939      * <p>
5940      * <em>Loop parameters:</em>
5941      * A clause function may take all the iteration variable values it is entitled to, in which case
5942      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
5943      * with their types and values notated as {@code (A...)} and {@code (a...)}.
5944      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
5945      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
5946      * init function is automatically a loop parameter {@code a}.)
5947      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
5948      * These loop parameters act as loop-invariant values visible across the whole loop.
5949      * <p>
5950      * <em>Parameters visible everywhere:</em>
5951      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
5952      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
5953      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
5954      * Most clause functions will not need all of this information, but they will be formally connected to it
5955      * as if by {@link #dropArguments}.
5956      * <a id="astar"></a>
5957      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
5958      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
5959      * In that notation, the general form of an init function parameter list
5960      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
5961      * <p>
5962      * <em>Checking clause structure:</em>
5963      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
5964      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
5965      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
5966      * met by the inputs to the loop combinator.
5967      * <p>
5968      * <em>Effectively identical sequences:</em>
5969      * <a id="effid"></a>
5970      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
5971      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
5972      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
5973      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
5974      * that longest list.
5975      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
5976      * and the same is true if more sequences of the form {@code (V... A*)} are added.
5977      * <p>
5978      * <em>Step 0: Determine clause structure.</em><ol type="a">
5979      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
5980      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
5981      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
5982      * four. Padding takes place by appending elements to the array.
5983      * <li>Clauses with all {@code null}s are disregarded.
5984      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
5985      * </ol>
5986      * <p>
5987      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
5988      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
5989      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
5990      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
5991      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
5992      * iteration variable type.
5993      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
5994      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
5995      * </ol>
5996      * <p>
5997      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
5998      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
5999      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6000      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6001      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6002      * (These types will be checked in step 2, along with all the clause function types.)
6003      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6004      * <li>All of the collected parameter lists must be effectively identical.
6005      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6006      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6007      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6008      * the "internal parameter list".
6009      * </ul>
6010      * <p>
6011      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6012      * <li>Examine fini function return types, disregarding omitted fini functions.
6013      * <li>If there are no fini functions, the loop return type is {@code void}.
6014      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6015      * type.
6016      * </ol>
6017      * <p>
6018      * <em>Step 1D: Check other types.</em><ol type="a">
6019      * <li>There must be at least one non-omitted pred function.
6020      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6021      * </ol>
6022      * <p>
6023      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6024      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6025      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6026      * (Note that their parameter lists are already effectively identical to this list.)
6027      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6028      * effectively identical to the internal parameter list {@code (V... A...)}.
6029      * </ol>
6030      * <p>
6031      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6032      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6033      * type.
6034      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6035      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6036      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6037      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6038      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6039      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6040      * loop return type.
6041      * </ol>
6042      * <p>
6043      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6044      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6045      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6046      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6047      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6048      * pad out the end of the list.
6049      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6050      * </ol>
6051      * <p>
6052      * <em>Final observations.</em><ol type="a">
6053      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6054      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6055      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6056      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6057      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6058      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6059      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6060      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6061      * </ol>
6062      * <p>
6063      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6064      * <ul>
6065      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6066      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6067      * (Only one {@code Pn} has to be non-{@code null}.)
6068      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6069      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6070      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6071      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6072      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6073      * the resulting loop handle's parameter types {@code (A...)}.
6074      * </ul>
6075      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6076      * which is natural if most of the loop computation happens in the steps.  For some loops,
6077      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6078      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6079      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6080      * where the init functions will need the extra parameters.  For such reasons, the rules for
6081      * determining these parameters are as symmetric as possible, across all clause parts.
6082      * In general, the loop parameters function as common invariant values across the whole
6083      * loop, while the iteration variables function as common variant values, or (if there is
6084      * no step function) as internal loop invariant temporaries.
6085      * <p>
6086      * <em>Loop execution.</em><ol type="a">
6087      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6088      * every clause function. These locals are loop invariant.
6089      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6090      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6091      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6092      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6093      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6094      * (in argument order).
6095      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6096      * returns {@code false}.
6097      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6098      * sequence {@code (v...)} of loop variables.
6099      * The updated value is immediately visible to all subsequent function calls.
6100      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6101      * (of type {@code R}) is returned from the loop as a whole.
6102      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6103      * except by throwing an exception.
6104      * </ol>
6105      * <p>
6106      * <em>Usage tips.</em>
6107      * <ul>
6108      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6109      * sometimes a step function only needs to observe the current value of its own variable.
6110      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6111      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6112      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6113      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6114      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6115      * <li>If some of the clause functions are virtual methods on an instance, the instance
6116      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6117      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6118      * will be the first iteration variable value, and it will be easy to use virtual
6119      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6120      * </ul>
6121      * <p>
6122      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6123      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6124      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6125      * <blockquote><pre>{@code
6126      * V... init...(A...);
6127      * boolean pred...(V..., A...);
6128      * V... step...(V..., A...);
6129      * R fini...(V..., A...);
6130      * R loop(A... a) {
6131      *   V... v... = init...(a...);
6132      *   for (;;) {
6133      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6134      *       v = s(v..., a...);
6135      *       if (!p(v..., a...)) {
6136      *         return f(v..., a...);
6137      *       }
6138      *     }
6139      *   }
6140      * }
6141      * }</pre></blockquote>
6142      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6143      * to their full length, even though individual clause functions may neglect to take them all.
6144      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6145      *
6146      * @apiNote Example:
6147      * <blockquote><pre>{@code
6148      * // iterative implementation of the factorial function as a loop handle
6149      * static int one(int k) { return 1; }
6150      * static int inc(int i, int acc, int k) { return i + 1; }
6151      * static int mult(int i, int acc, int k) { return i * acc; }
6152      * static boolean pred(int i, int acc, int k) { return i < k; }
6153      * static int fin(int i, int acc, int k) { return acc; }
6154      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6155      * // null initializer for counter, should initialize to 0
6156      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6157      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6158      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6159      * assertEquals(120, loop.invoke(5));
6160      * }</pre></blockquote>
6161      * The same example, dropping arguments and using combinators:
6162      * <blockquote><pre>{@code
6163      * // simplified implementation of the factorial function as a loop handle
6164      * static int inc(int i) { return i + 1; } // drop acc, k
6165      * static int mult(int i, int acc) { return i * acc; } //drop k
6166      * static boolean cmp(int i, int k) { return i < k; }
6167      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6168      * // null initializer for counter, should initialize to 0
6169      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6170      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6171      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6172      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6173      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6174      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6175      * assertEquals(720, loop.invoke(6));
6176      * }</pre></blockquote>
6177      * A similar example, using a helper object to hold a loop parameter:
6178      * <blockquote><pre>{@code
6179      * // instance-based implementation of the factorial function as a loop handle
6180      * static class FacLoop {
6181      *   final int k;
6182      *   FacLoop(int k) { this.k = k; }
6183      *   int inc(int i) { return i + 1; }
6184      *   int mult(int i, int acc) { return i * acc; }
6185      *   boolean pred(int i) { return i < k; }
6186      *   int fin(int i, int acc) { return acc; }
6187      * }
6188      * // assume MH_FacLoop is a handle to the constructor
6189      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6190      * // null initializer for counter, should initialize to 0
6191      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6192      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6193      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6194      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6195      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6196      * assertEquals(5040, loop.invoke(7));
6197      * }</pre></blockquote>
6198      *
6199      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6200      *
6201      * @return a method handle embodying the looping behavior as defined by the arguments.
6202      *
6203      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6204      *
6205      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6206      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6207      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6208      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6209      * @since 9
6210      */
6211     public static MethodHandle loop(MethodHandle[]... clauses) {
6212         // Step 0: determine clause structure.
6213         loopChecks0(clauses);
6214 
6215         List<MethodHandle> init = new ArrayList<>();
6216         List<MethodHandle> step = new ArrayList<>();
6217         List<MethodHandle> pred = new ArrayList<>();
6218         List<MethodHandle> fini = new ArrayList<>();
6219 
6220         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6221             init.add(clause[0]); // all clauses have at least length 1
6222             step.add(clause.length <= 1 ? null : clause[1]);
6223             pred.add(clause.length <= 2 ? null : clause[2]);
6224             fini.add(clause.length <= 3 ? null : clause[3]);
6225         });
6226 
6227         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6228         final int nclauses = init.size();
6229 
6230         // Step 1A: determine iteration variables (V...).
6231         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6232         for (int i = 0; i < nclauses; ++i) {
6233             MethodHandle in = init.get(i);
6234             MethodHandle st = step.get(i);
6235             if (in == null && st == null) {
6236                 iterationVariableTypes.add(void.class);
6237             } else if (in != null && st != null) {
6238                 loopChecks1a(i, in, st);
6239                 iterationVariableTypes.add(in.type().returnType());
6240             } else {
6241                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6242             }
6243         }
6244         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).
6245                 collect(Collectors.toList());
6246 
6247         // Step 1B: determine loop parameters (A...).
6248         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6249         loopChecks1b(init, commonSuffix);
6250 
6251         // Step 1C: determine loop return type.
6252         // Step 1D: check other types.
6253         // local variable required here; see JDK-8223553
6254         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6255                 .map(MethodType::returnType);
6256         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6257         loopChecks1cd(pred, fini, loopReturnType);
6258 
6259         // Step 2: determine parameter lists.
6260         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6261         commonParameterSequence.addAll(commonSuffix);
6262         loopChecks2(step, pred, fini, commonParameterSequence);
6263 
6264         // Step 3: fill in omitted functions.
6265         for (int i = 0; i < nclauses; ++i) {
6266             Class<?> t = iterationVariableTypes.get(i);
6267             if (init.get(i) == null) {
6268                 init.set(i, empty(methodType(t, commonSuffix)));
6269             }
6270             if (step.get(i) == null) {
6271                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6272             }
6273             if (pred.get(i) == null) {
6274                 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence));
6275             }
6276             if (fini.get(i) == null) {
6277                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6278             }
6279         }
6280 
6281         // Step 4: fill in missing parameter types.
6282         // Also convert all handles to fixed-arity handles.
6283         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6284         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6285         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6286         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6287 
6288         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6289                 allMatch(pl -> pl.equals(commonSuffix));
6290         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6291                 allMatch(pl -> pl.equals(commonParameterSequence));
6292 
6293         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6294     }
6295 
6296     private static void loopChecks0(MethodHandle[][] clauses) {
6297         if (clauses == null || clauses.length == 0) {
6298             throw newIllegalArgumentException("null or no clauses passed");
6299         }
6300         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6301             throw newIllegalArgumentException("null clauses are not allowed");
6302         }
6303         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6304             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6305         }
6306     }
6307 
6308     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6309         if (in.type().returnType() != st.type().returnType()) {
6310             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6311                     st.type().returnType());
6312         }
6313     }
6314 
6315     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6316         final List<Class<?>> empty = List.of();
6317         final List<Class<?>> longest = mhs.filter(Objects::nonNull).
6318                 // take only those that can contribute to a common suffix because they are longer than the prefix
6319                         map(MethodHandle::type).
6320                         filter(t -> t.parameterCount() > skipSize).
6321                         map(MethodType::parameterList).
6322                         reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6323         return longest.size() == 0 ? empty : longest.subList(skipSize, longest.size());
6324     }
6325 
6326     private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) {
6327         final List<Class<?>> empty = List.of();
6328         return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6329     }
6330 
6331     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6332         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6333         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6334         return longestParameterList(Arrays.asList(longest1, longest2));
6335     }
6336 
6337     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6338         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6339                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6340             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6341                     " (common suffix: " + commonSuffix + ")");
6342         }
6343     }
6344 
6345     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6346         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6347                 anyMatch(t -> t != loopReturnType)) {
6348             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6349                     loopReturnType + ")");
6350         }
6351 
6352         if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
6353             throw newIllegalArgumentException("no predicate found", pred);
6354         }
6355         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6356                 anyMatch(t -> t != boolean.class)) {
6357             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6358         }
6359     }
6360 
6361     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6362         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6363                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6364             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6365                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6366         }
6367     }
6368 
6369     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6370         return hs.stream().map(h -> {
6371             int pc = h.type().parameterCount();
6372             int tpsize = targetParams.size();
6373             return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h;
6374         }).collect(Collectors.toList());
6375     }
6376 
6377     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6378         return hs.stream().map(MethodHandle::asFixedArity).collect(Collectors.toList());
6379     }
6380 
6381     /**
6382      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6383      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6384      * <p>
6385      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6386      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6387      * evaluates to {@code true}).
6388      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6389      * <p>
6390      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6391      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6392      * and updated with the value returned from its invocation. The result of loop execution will be
6393      * the final value of the additional loop-local variable (if present).
6394      * <p>
6395      * The following rules hold for these argument handles:<ul>
6396      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6397      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6398      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6399      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6400      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6401      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6402      * It will constrain the parameter lists of the other loop parts.
6403      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6404      * list {@code (A...)} is called the <em>external parameter list</em>.
6405      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6406      * additional state variable of the loop.
6407      * The body must both accept and return a value of this type {@code V}.
6408      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6409      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6410      * <a href="MethodHandles.html#effid">effectively identical</a>
6411      * to the external parameter list {@code (A...)}.
6412      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6413      * {@linkplain #empty default value}.
6414      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6415      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6416      * effectively identical to the internal parameter list.
6417      * </ul>
6418      * <p>
6419      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6420      * <li>The loop handle's result type is the result type {@code V} of the body.
6421      * <li>The loop handle's parameter types are the types {@code (A...)},
6422      * from the external parameter list.
6423      * </ul>
6424      * <p>
6425      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6426      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6427      * passed to the loop.
6428      * <blockquote><pre>{@code
6429      * V init(A...);
6430      * boolean pred(V, A...);
6431      * V body(V, A...);
6432      * V whileLoop(A... a...) {
6433      *   V v = init(a...);
6434      *   while (pred(v, a...)) {
6435      *     v = body(v, a...);
6436      *   }
6437      *   return v;
6438      * }
6439      * }</pre></blockquote>
6440      *
6441      * @apiNote Example:
6442      * <blockquote><pre>{@code
6443      * // implement the zip function for lists as a loop handle
6444      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6445      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6446      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6447      *   zip.add(a.next());
6448      *   zip.add(b.next());
6449      *   return zip;
6450      * }
6451      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6452      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6453      * List<String> a = Arrays.asList("a", "b", "c", "d");
6454      * List<String> b = Arrays.asList("e", "f", "g", "h");
6455      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6456      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6457      * }</pre></blockquote>
6458      *
6459      *
6460      * @apiNote The implementation of this method can be expressed as follows:
6461      * <blockquote><pre>{@code
6462      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6463      *     MethodHandle fini = (body.type().returnType() == void.class
6464      *                         ? null : identity(body.type().returnType()));
6465      *     MethodHandle[]
6466      *         checkExit = { null, null, pred, fini },
6467      *         varBody   = { init, body };
6468      *     return loop(checkExit, varBody);
6469      * }
6470      * }</pre></blockquote>
6471      *
6472      * @param init optional initializer, providing the initial value of the loop variable.
6473      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6474      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6475      *             above for other constraints.
6476      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6477      *             See above for other constraints.
6478      *
6479      * @return a method handle implementing the {@code while} loop as described by the arguments.
6480      * @throws IllegalArgumentException if the rules for the arguments are violated.
6481      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6482      *
6483      * @see #loop(MethodHandle[][])
6484      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6485      * @since 9
6486      */
6487     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6488         whileLoopChecks(init, pred, body);
6489         MethodHandle fini = identityOrVoid(body.type().returnType());
6490         MethodHandle[] checkExit = { null, null, pred, fini };
6491         MethodHandle[] varBody = { init, body };
6492         return loop(checkExit, varBody);
6493     }
6494 
6495     /**
6496      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
6497      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6498      * <p>
6499      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6500      * method will, in each iteration, first execute its body and then evaluate the predicate.
6501      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
6502      * <p>
6503      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6504      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6505      * and updated with the value returned from its invocation. The result of loop execution will be
6506      * the final value of the additional loop-local variable (if present).
6507      * <p>
6508      * The following rules hold for these argument handles:<ul>
6509      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6510      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6511      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6512      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6513      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6514      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6515      * It will constrain the parameter lists of the other loop parts.
6516      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6517      * list {@code (A...)} is called the <em>external parameter list</em>.
6518      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6519      * additional state variable of the loop.
6520      * The body must both accept and return a value of this type {@code V}.
6521      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6522      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6523      * <a href="MethodHandles.html#effid">effectively identical</a>
6524      * to the external parameter list {@code (A...)}.
6525      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6526      * {@linkplain #empty default value}.
6527      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6528      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6529      * effectively identical to the internal parameter list.
6530      * </ul>
6531      * <p>
6532      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6533      * <li>The loop handle's result type is the result type {@code V} of the body.
6534      * <li>The loop handle's parameter types are the types {@code (A...)},
6535      * from the external parameter list.
6536      * </ul>
6537      * <p>
6538      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6539      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6540      * passed to the loop.
6541      * <blockquote><pre>{@code
6542      * V init(A...);
6543      * boolean pred(V, A...);
6544      * V body(V, A...);
6545      * V doWhileLoop(A... a...) {
6546      *   V v = init(a...);
6547      *   do {
6548      *     v = body(v, a...);
6549      *   } while (pred(v, a...));
6550      *   return v;
6551      * }
6552      * }</pre></blockquote>
6553      *
6554      * @apiNote Example:
6555      * <blockquote><pre>{@code
6556      * // int i = 0; while (i < limit) { ++i; } return i; => limit
6557      * static int zero(int limit) { return 0; }
6558      * static int step(int i, int limit) { return i + 1; }
6559      * static boolean pred(int i, int limit) { return i < limit; }
6560      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
6561      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
6562      * assertEquals(23, loop.invoke(23));
6563      * }</pre></blockquote>
6564      *
6565      *
6566      * @apiNote The implementation of this method can be expressed as follows:
6567      * <blockquote><pre>{@code
6568      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
6569      *     MethodHandle fini = (body.type().returnType() == void.class
6570      *                         ? null : identity(body.type().returnType()));
6571      *     MethodHandle[] clause = { init, body, pred, fini };
6572      *     return loop(clause);
6573      * }
6574      * }</pre></blockquote>
6575      *
6576      * @param init optional initializer, providing the initial value of the loop variable.
6577      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6578      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6579      *             See above for other constraints.
6580      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6581      *             above for other constraints.
6582      *
6583      * @return a method handle implementing the {@code while} loop as described by the arguments.
6584      * @throws IllegalArgumentException if the rules for the arguments are violated.
6585      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6586      *
6587      * @see #loop(MethodHandle[][])
6588      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
6589      * @since 9
6590      */
6591     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
6592         whileLoopChecks(init, pred, body);
6593         MethodHandle fini = identityOrVoid(body.type().returnType());
6594         MethodHandle[] clause = {init, body, pred, fini };
6595         return loop(clause);
6596     }
6597 
6598     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
6599         Objects.requireNonNull(pred);
6600         Objects.requireNonNull(body);
6601         MethodType bodyType = body.type();
6602         Class<?> returnType = bodyType.returnType();
6603         List<Class<?>> innerList = bodyType.parameterList();
6604         List<Class<?>> outerList = innerList;
6605         if (returnType == void.class) {
6606             // OK
6607         } else if (innerList.size() == 0 || innerList.get(0) != returnType) {
6608             // leading V argument missing => error
6609             MethodType expected = bodyType.insertParameterTypes(0, returnType);
6610             throw misMatchedTypes("body function", bodyType, expected);
6611         } else {
6612             outerList = innerList.subList(1, innerList.size());
6613         }
6614         MethodType predType = pred.type();
6615         if (predType.returnType() != boolean.class ||
6616                 !predType.effectivelyIdenticalParameters(0, innerList)) {
6617             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
6618         }
6619         if (init != null) {
6620             MethodType initType = init.type();
6621             if (initType.returnType() != returnType ||
6622                     !initType.effectivelyIdenticalParameters(0, outerList)) {
6623                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
6624             }
6625         }
6626     }
6627 
6628     /**
6629      * Constructs a loop that runs a given number of iterations.
6630      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6631      * <p>
6632      * The number of iterations is determined by the {@code iterations} handle evaluation result.
6633      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
6634      * It will be initialized to 0 and incremented by 1 in each iteration.
6635      * <p>
6636      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
6637      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
6638      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
6639      * <p>
6640      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
6641      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
6642      * iteration variable.
6643      * The result of the loop handle execution will be the final {@code V} value of that variable
6644      * (or {@code void} if there is no {@code V} variable).
6645      * <p>
6646      * The following rules hold for the argument handles:<ul>
6647      * <li>The {@code iterations} handle must not be {@code null}, and must return
6648      * the type {@code int}, referred to here as {@code I} in parameter type lists.
6649      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6650      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
6651      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6652      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
6653      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
6654      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
6655      * of types called the <em>internal parameter list</em>.
6656      * It will constrain the parameter lists of the other loop parts.
6657      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
6658      * with no additional {@code A} types, then the internal parameter list is extended by
6659      * the argument types {@code A...} of the {@code iterations} handle.
6660      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
6661      * list {@code (A...)} is called the <em>external parameter list</em>.
6662      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6663      * additional state variable of the loop.
6664      * The body must both accept a leading parameter and return a value of this type {@code V}.
6665      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6666      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6667      * <a href="MethodHandles.html#effid">effectively identical</a>
6668      * to the external parameter list {@code (A...)}.
6669      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6670      * {@linkplain #empty default value}.
6671      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
6672      * effectively identical to the external parameter list {@code (A...)}.
6673      * </ul>
6674      * <p>
6675      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6676      * <li>The loop handle's result type is the result type {@code V} of the body.
6677      * <li>The loop handle's parameter types are the types {@code (A...)},
6678      * from the external parameter list.
6679      * </ul>
6680      * <p>
6681      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6682      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
6683      * arguments passed to the loop.
6684      * <blockquote><pre>{@code
6685      * int iterations(A...);
6686      * V init(A...);
6687      * V body(V, int, A...);
6688      * V countedLoop(A... a...) {
6689      *   int end = iterations(a...);
6690      *   V v = init(a...);
6691      *   for (int i = 0; i < end; ++i) {
6692      *     v = body(v, i, a...);
6693      *   }
6694      *   return v;
6695      * }
6696      * }</pre></blockquote>
6697      *
6698      * @apiNote Example with a fully conformant body method:
6699      * <blockquote><pre>{@code
6700      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
6701      * // => a variation on a well known theme
6702      * static String step(String v, int counter, String init) { return "na " + v; }
6703      * // assume MH_step is a handle to the method above
6704      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
6705      * MethodHandle start = MethodHandles.identity(String.class);
6706      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
6707      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
6708      * }</pre></blockquote>
6709      *
6710      * @apiNote Example with the simplest possible body method type,
6711      * and passing the number of iterations to the loop invocation:
6712      * <blockquote><pre>{@code
6713      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
6714      * // => a variation on a well known theme
6715      * static String step(String v, int counter ) { return "na " + v; }
6716      * // assume MH_step is a handle to the method above
6717      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
6718      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
6719      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
6720      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
6721      * }</pre></blockquote>
6722      *
6723      * @apiNote Example that treats the number of iterations, string to append to, and string to append
6724      * as loop parameters:
6725      * <blockquote><pre>{@code
6726      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
6727      * // => a variation on a well known theme
6728      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
6729      * // assume MH_step is a handle to the method above
6730      * MethodHandle count = MethodHandles.identity(int.class);
6731      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
6732      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
6733      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
6734      * }</pre></blockquote>
6735      *
6736      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
6737      * to enforce a loop type:
6738      * <blockquote><pre>{@code
6739      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
6740      * // => a variation on a well known theme
6741      * static String step(String v, int counter, String pre) { return pre + " " + v; }
6742      * // assume MH_step is a handle to the method above
6743      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
6744      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
6745      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
6746      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
6747      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
6748      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
6749      * }</pre></blockquote>
6750      *
6751      * @apiNote The implementation of this method can be expressed as follows:
6752      * <blockquote><pre>{@code
6753      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
6754      *     return countedLoop(empty(iterations.type()), iterations, init, body);
6755      * }
6756      * }</pre></blockquote>
6757      *
6758      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
6759      *                   result type must be {@code int}. See above for other constraints.
6760      * @param init optional initializer, providing the initial value of the loop variable.
6761      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6762      * @param body body of the loop, which may not be {@code null}.
6763      *             It controls the loop parameters and result type in the standard case (see above for details).
6764      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
6765      *             and may accept any number of additional types.
6766      *             See above for other constraints.
6767      *
6768      * @return a method handle representing the loop.
6769      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
6770      * @throws IllegalArgumentException if any argument violates the rules formulated above.
6771      *
6772      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
6773      * @since 9
6774      */
6775     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
6776         return countedLoop(empty(iterations.type()), iterations, init, body);
6777     }
6778 
6779     /**
6780      * Constructs a loop that counts over a range of numbers.
6781      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6782      * <p>
6783      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
6784      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
6785      * values of the loop counter.
6786      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
6787      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
6788      * <p>
6789      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
6790      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
6791      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
6792      * <p>
6793      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
6794      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
6795      * iteration variable.
6796      * The result of the loop handle execution will be the final {@code V} value of that variable
6797      * (or {@code void} if there is no {@code V} variable).
6798      * <p>
6799      * The following rules hold for the argument handles:<ul>
6800      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
6801      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
6802      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6803      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
6804      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6805      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
6806      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
6807      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
6808      * of types called the <em>internal parameter list</em>.
6809      * It will constrain the parameter lists of the other loop parts.
6810      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
6811      * with no additional {@code A} types, then the internal parameter list is extended by
6812      * the argument types {@code A...} of the {@code end} handle.
6813      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
6814      * list {@code (A...)} is called the <em>external parameter list</em>.
6815      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6816      * additional state variable of the loop.
6817      * The body must both accept a leading parameter and return a value of this type {@code V}.
6818      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6819      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6820      * <a href="MethodHandles.html#effid">effectively identical</a>
6821      * to the external parameter list {@code (A...)}.
6822      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6823      * {@linkplain #empty default value}.
6824      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
6825      * effectively identical to the external parameter list {@code (A...)}.
6826      * <li>Likewise, the parameter list of {@code end} must be effectively identical
6827      * to the external parameter list.
6828      * </ul>
6829      * <p>
6830      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6831      * <li>The loop handle's result type is the result type {@code V} of the body.
6832      * <li>The loop handle's parameter types are the types {@code (A...)},
6833      * from the external parameter list.
6834      * </ul>
6835      * <p>
6836      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6837      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
6838      * arguments passed to the loop.
6839      * <blockquote><pre>{@code
6840      * int start(A...);
6841      * int end(A...);
6842      * V init(A...);
6843      * V body(V, int, A...);
6844      * V countedLoop(A... a...) {
6845      *   int e = end(a...);
6846      *   int s = start(a...);
6847      *   V v = init(a...);
6848      *   for (int i = s; i < e; ++i) {
6849      *     v = body(v, i, a...);
6850      *   }
6851      *   return v;
6852      * }
6853      * }</pre></blockquote>
6854      *
6855      * @apiNote The implementation of this method can be expressed as follows:
6856      * <blockquote><pre>{@code
6857      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
6858      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
6859      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
6860      *     // the following semantics:
6861      *     // MH_increment: (int limit, int counter) -> counter + 1
6862      *     // MH_predicate: (int limit, int counter) -> counter < limit
6863      *     Class<?> counterType = start.type().returnType();  // int
6864      *     Class<?> returnType = body.type().returnType();
6865      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
6866      *     if (returnType != void.class) {  // ignore the V variable
6867      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
6868      *         pred = dropArguments(pred, 1, returnType);  // ditto
6869      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
6870      *     }
6871      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
6872      *     MethodHandle[]
6873      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
6874      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
6875      *         indexVar   = { start, incr };           // i = start(); i = i + 1
6876      *     return loop(loopLimit, bodyClause, indexVar);
6877      * }
6878      * }</pre></blockquote>
6879      *
6880      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
6881      *              See above for other constraints.
6882      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
6883      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
6884      * @param init optional initializer, providing the initial value of the loop variable.
6885      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6886      * @param body body of the loop, which may not be {@code null}.
6887      *             It controls the loop parameters and result type in the standard case (see above for details).
6888      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
6889      *             and may accept any number of additional types.
6890      *             See above for other constraints.
6891      *
6892      * @return a method handle representing the loop.
6893      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
6894      * @throws IllegalArgumentException if any argument violates the rules formulated above.
6895      *
6896      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
6897      * @since 9
6898      */
6899     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
6900         countedLoopChecks(start, end, init, body);
6901         Class<?> counterType = start.type().returnType();  // int, but who's counting?
6902         Class<?> limitType   = end.type().returnType();    // yes, int again
6903         Class<?> returnType  = body.type().returnType();
6904         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
6905         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
6906         MethodHandle retv = null;
6907         if (returnType != void.class) {
6908             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
6909             pred = dropArguments(pred, 1, returnType);  // ditto
6910             retv = dropArguments(identity(returnType), 0, counterType);
6911         }
6912         body = dropArguments(body, 0, counterType);  // ignore the limit variable
6913         MethodHandle[]
6914             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
6915             bodyClause = { init, body },            // v = init(); v = body(v, i)
6916             indexVar   = { start, incr };           // i = start(); i = i + 1
6917         return loop(loopLimit, bodyClause, indexVar);
6918     }
6919 
6920     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
6921         Objects.requireNonNull(start);
6922         Objects.requireNonNull(end);
6923         Objects.requireNonNull(body);
6924         Class<?> counterType = start.type().returnType();
6925         if (counterType != int.class) {
6926             MethodType expected = start.type().changeReturnType(int.class);
6927             throw misMatchedTypes("start function", start.type(), expected);
6928         } else if (end.type().returnType() != counterType) {
6929             MethodType expected = end.type().changeReturnType(counterType);
6930             throw misMatchedTypes("end function", end.type(), expected);
6931         }
6932         MethodType bodyType = body.type();
6933         Class<?> returnType = bodyType.returnType();
6934         List<Class<?>> innerList = bodyType.parameterList();
6935         // strip leading V value if present
6936         int vsize = (returnType == void.class ? 0 : 1);
6937         if (vsize != 0 && (innerList.size() == 0 || innerList.get(0) != returnType)) {
6938             // argument list has no "V" => error
6939             MethodType expected = bodyType.insertParameterTypes(0, returnType);
6940             throw misMatchedTypes("body function", bodyType, expected);
6941         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
6942             // missing I type => error
6943             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
6944             throw misMatchedTypes("body function", bodyType, expected);
6945         }
6946         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
6947         if (outerList.isEmpty()) {
6948             // special case; take lists from end handle
6949             outerList = end.type().parameterList();
6950             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
6951         }
6952         MethodType expected = methodType(counterType, outerList);
6953         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
6954             throw misMatchedTypes("start parameter types", start.type(), expected);
6955         }
6956         if (end.type() != start.type() &&
6957             !end.type().effectivelyIdenticalParameters(0, outerList)) {
6958             throw misMatchedTypes("end parameter types", end.type(), expected);
6959         }
6960         if (init != null) {
6961             MethodType initType = init.type();
6962             if (initType.returnType() != returnType ||
6963                 !initType.effectivelyIdenticalParameters(0, outerList)) {
6964                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
6965             }
6966         }
6967     }
6968 
6969     /**
6970      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
6971      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6972      * <p>
6973      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
6974      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
6975      * <p>
6976      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
6977      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
6978      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
6979      * <p>
6980      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
6981      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
6982      * iteration variable.
6983      * The result of the loop handle execution will be the final {@code V} value of that variable
6984      * (or {@code void} if there is no {@code V} variable).
6985      * <p>
6986      * The following rules hold for the argument handles:<ul>
6987      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6988      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
6989      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6990      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
6991      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
6992      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
6993      * of types called the <em>internal parameter list</em>.
6994      * It will constrain the parameter lists of the other loop parts.
6995      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
6996      * with no additional {@code A} types, then the internal parameter list is extended by
6997      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
6998      * single type {@code Iterable} is added and constitutes the {@code A...} list.
6999      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7000      * list {@code (A...)} is called the <em>external parameter list</em>.
7001      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7002      * additional state variable of the loop.
7003      * The body must both accept a leading parameter and return a value of this type {@code V}.
7004      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7005      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7006      * <a href="MethodHandles.html#effid">effectively identical</a>
7007      * to the external parameter list {@code (A...)}.
7008      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7009      * {@linkplain #empty default value}.
7010      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7011      * type {@code java.util.Iterator} or a subtype thereof.
7012      * The iterator it produces when the loop is executed will be assumed
7013      * to yield values which can be converted to type {@code T}.
7014      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7015      * effectively identical to the external parameter list {@code (A...)}.
7016      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7017      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7018      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7019      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7020      * the {@link MethodHandle#asType asType} conversion method.
7021      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7022      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7023      * </ul>
7024      * <p>
7025      * The type {@code T} may be either a primitive or reference.
7026      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7027      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7028      * as if by the {@link MethodHandle#asType asType} conversion method.
7029      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7030      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7031      * <p>
7032      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7033      * <li>The loop handle's result type is the result type {@code V} of the body.
7034      * <li>The loop handle's parameter types are the types {@code (A...)},
7035      * from the external parameter list.
7036      * </ul>
7037      * <p>
7038      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7039      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7040      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7041      * <blockquote><pre>{@code
7042      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7043      * V init(A...);
7044      * V body(V,T,A...);
7045      * V iteratedLoop(A... a...) {
7046      *   Iterator<T> it = iterator(a...);
7047      *   V v = init(a...);
7048      *   while (it.hasNext()) {
7049      *     T t = it.next();
7050      *     v = body(v, t, a...);
7051      *   }
7052      *   return v;
7053      * }
7054      * }</pre></blockquote>
7055      *
7056      * @apiNote Example:
7057      * <blockquote><pre>{@code
7058      * // get an iterator from a list
7059      * static List<String> reverseStep(List<String> r, String e) {
7060      *   r.add(0, e);
7061      *   return r;
7062      * }
7063      * static List<String> newArrayList() { return new ArrayList<>(); }
7064      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7065      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7066      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7067      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7068      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7069      * }</pre></blockquote>
7070      *
7071      * @apiNote The implementation of this method can be expressed approximately as follows:
7072      * <blockquote><pre>{@code
7073      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7074      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7075      *     Class<?> returnType = body.type().returnType();
7076      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7077      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7078      *     MethodHandle retv = null, step = body, startIter = iterator;
7079      *     if (returnType != void.class) {
7080      *         // the simple thing first:  in (I V A...), drop the I to get V
7081      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7082      *         // body type signature (V T A...), internal loop types (I V A...)
7083      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7084      *     }
7085      *     if (startIter == null)  startIter = MH_getIter;
7086      *     MethodHandle[]
7087      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7088      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7089      *     return loop(iterVar, bodyClause);
7090      * }
7091      * }</pre></blockquote>
7092      *
7093      * @param iterator an optional handle to return the iterator to start the loop.
7094      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7095      *                 See above for other constraints.
7096      * @param init optional initializer, providing the initial value of the loop variable.
7097      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7098      * @param body body of the loop, which may not be {@code null}.
7099      *             It controls the loop parameters and result type in the standard case (see above for details).
7100      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7101      *             and may accept any number of additional types.
7102      *             See above for other constraints.
7103      *
7104      * @return a method handle embodying the iteration loop functionality.
7105      * @throws NullPointerException if the {@code body} handle is {@code null}.
7106      * @throws IllegalArgumentException if any argument violates the above requirements.
7107      *
7108      * @since 9
7109      */
7110     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7111         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7112         Class<?> returnType = body.type().returnType();
7113         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7114         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7115         MethodHandle startIter;
7116         MethodHandle nextVal;
7117         {
7118             MethodType iteratorType;
7119             if (iterator == null) {
7120                 // derive argument type from body, if available, else use Iterable
7121                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7122                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7123             } else {
7124                 // force return type to the internal iterator class
7125                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7126                 startIter = iterator;
7127             }
7128             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7129             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7130 
7131             // perform the asType transforms under an exception transformer, as per spec.:
7132             try {
7133                 startIter = startIter.asType(iteratorType);
7134                 nextVal = nextRaw.asType(nextValType);
7135             } catch (WrongMethodTypeException ex) {
7136                 throw new IllegalArgumentException(ex);
7137             }
7138         }
7139 
7140         MethodHandle retv = null, step = body;
7141         if (returnType != void.class) {
7142             // the simple thing first:  in (I V A...), drop the I to get V
7143             retv = dropArguments(identity(returnType), 0, Iterator.class);
7144             // body type signature (V T A...), internal loop types (I V A...)
7145             step = swapArguments(body, 0, 1);  // swap V <-> T
7146         }
7147 
7148         MethodHandle[]
7149             iterVar    = { startIter, null, hasNext, retv },
7150             bodyClause = { init, filterArgument(step, 0, nextVal) };
7151         return loop(iterVar, bodyClause);
7152     }
7153 
7154     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7155         Objects.requireNonNull(body);
7156         MethodType bodyType = body.type();
7157         Class<?> returnType = bodyType.returnType();
7158         List<Class<?>> internalParamList = bodyType.parameterList();
7159         // strip leading V value if present
7160         int vsize = (returnType == void.class ? 0 : 1);
7161         if (vsize != 0 && (internalParamList.size() == 0 || internalParamList.get(0) != returnType)) {
7162             // argument list has no "V" => error
7163             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7164             throw misMatchedTypes("body function", bodyType, expected);
7165         } else if (internalParamList.size() <= vsize) {
7166             // missing T type => error
7167             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7168             throw misMatchedTypes("body function", bodyType, expected);
7169         }
7170         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7171         Class<?> iterableType = null;
7172         if (iterator != null) {
7173             // special case; if the body handle only declares V and T then
7174             // the external parameter list is obtained from iterator handle
7175             if (externalParamList.isEmpty()) {
7176                 externalParamList = iterator.type().parameterList();
7177             }
7178             MethodType itype = iterator.type();
7179             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7180                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7181             }
7182             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7183                 MethodType expected = methodType(itype.returnType(), externalParamList);
7184                 throw misMatchedTypes("iterator parameters", itype, expected);
7185             }
7186         } else {
7187             if (externalParamList.isEmpty()) {
7188                 // special case; if the iterator handle is null and the body handle
7189                 // only declares V and T then the external parameter list consists
7190                 // of Iterable
7191                 externalParamList = Arrays.asList(Iterable.class);
7192                 iterableType = Iterable.class;
7193             } else {
7194                 // special case; if the iterator handle is null and the external
7195                 // parameter list is not empty then the first parameter must be
7196                 // assignable to Iterable
7197                 iterableType = externalParamList.get(0);
7198                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7199                     throw newIllegalArgumentException(
7200                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7201                 }
7202             }
7203         }
7204         if (init != null) {
7205             MethodType initType = init.type();
7206             if (initType.returnType() != returnType ||
7207                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7208                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7209             }
7210         }
7211         return iterableType;  // help the caller a bit
7212     }
7213 
7214     /*non-public*/
7215     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7216         // there should be a better way to uncross my wires
7217         int arity = mh.type().parameterCount();
7218         int[] order = new int[arity];
7219         for (int k = 0; k < arity; k++)  order[k] = k;
7220         order[i] = j; order[j] = i;
7221         Class<?>[] types = mh.type().parameterArray();
7222         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7223         MethodType swapType = methodType(mh.type().returnType(), types);
7224         return permuteArguments(mh, swapType, order);
7225     }
7226 
7227     /**
7228      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7229      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7230      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7231      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7232      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7233      * {@code try-finally} handle.
7234      * <p>
7235      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7236      * The first is the exception thrown during the
7237      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7238      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7239      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7240      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7241      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7242      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7243      * <p>
7244      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7245      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7246      * two extra leading parameters:<ul>
7247      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7248      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7249      * the result from the execution of the {@code target} handle.
7250      * This parameter is not present if the {@code target} returns {@code void}.
7251      * </ul>
7252      * <p>
7253      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7254      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7255      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7256      * the cleanup.
7257      * <blockquote><pre>{@code
7258      * V target(A..., B...);
7259      * V cleanup(Throwable, V, A...);
7260      * V adapter(A... a, B... b) {
7261      *   V result = (zero value for V);
7262      *   Throwable throwable = null;
7263      *   try {
7264      *     result = target(a..., b...);
7265      *   } catch (Throwable t) {
7266      *     throwable = t;
7267      *     throw t;
7268      *   } finally {
7269      *     result = cleanup(throwable, result, a...);
7270      *   }
7271      *   return result;
7272      * }
7273      * }</pre></blockquote>
7274      * <p>
7275      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7276      * be modified by execution of the target, and so are passed unchanged
7277      * from the caller to the cleanup, if it is invoked.
7278      * <p>
7279      * The target and cleanup must return the same type, even if the cleanup
7280      * always throws.
7281      * To create such a throwing cleanup, compose the cleanup logic
7282      * with {@link #throwException throwException},
7283      * in order to create a method handle of the correct return type.
7284      * <p>
7285      * Note that {@code tryFinally} never converts exceptions into normal returns.
7286      * In rare cases where exceptions must be converted in that way, first wrap
7287      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7288      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7289      * <p>
7290      * It is recommended that the first parameter type of {@code cleanup} be
7291      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7292      * {@code cleanup} will always be invoked with whatever exception that
7293      * {@code target} throws.  Declaring a narrower type may result in a
7294      * {@code ClassCastException} being thrown by the {@code try-finally}
7295      * handle if the type of the exception thrown by {@code target} is not
7296      * assignable to the first parameter type of {@code cleanup}.  Note that
7297      * various exception types of {@code VirtualMachineError},
7298      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7299      * thrown by almost any kind of Java code, and a finally clause that
7300      * catches (say) only {@code IOException} would mask any of the others
7301      * behind a {@code ClassCastException}.
7302      *
7303      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7304      * @param cleanup the handle that is invoked in the finally block.
7305      *
7306      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7307      * @throws NullPointerException if any argument is null
7308      * @throws IllegalArgumentException if {@code cleanup} does not accept
7309      *          the required leading arguments, or if the method handle types do
7310      *          not match in their return types and their
7311      *          corresponding trailing parameters
7312      *
7313      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7314      * @since 9
7315      */
7316     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7317         List<Class<?>> targetParamTypes = target.type().parameterList();
7318         Class<?> rtype = target.type().returnType();
7319 
7320         tryFinallyChecks(target, cleanup);
7321 
7322         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7323         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7324         // target parameter list.
7325         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
7326 
7327         // Ensure that the intrinsic type checks the instance thrown by the
7328         // target against the first parameter of cleanup
7329         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7330 
7331         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7332         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7333     }
7334 
7335     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7336         Class<?> rtype = target.type().returnType();
7337         if (rtype != cleanup.type().returnType()) {
7338             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7339         }
7340         MethodType cleanupType = cleanup.type();
7341         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7342             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7343         }
7344         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7345             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7346         }
7347         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7348         // target parameter list.
7349         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7350         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7351             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7352                     cleanup.type(), target.type());
7353         }
7354     }
7355 
7356 }
--- EOF ---