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