rev 13458 : 8147078: MethodHandles.catchException does not enforce Throwable subtype

   1 /*
   2  * Copyright (c) 2008, 2016, 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 java.lang.reflect.*;
  29 import java.util.*;
  30 
  31 import sun.invoke.util.ValueConversions;
  32 import sun.invoke.util.VerifyAccess;
  33 import sun.invoke.util.Wrapper;
  34 import sun.reflect.CallerSensitive;
  35 import sun.reflect.Reflection;
  36 import sun.reflect.misc.ReflectUtil;
  37 import sun.security.util.SecurityConstants;
  38 import java.lang.invoke.LambdaForm.BasicType;
  39 
  40 import static java.lang.invoke.MethodHandleStatics.*;
  41 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  42 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  43 import java.util.concurrent.ConcurrentHashMap;
  44 import java.util.stream.Collectors;
  45 import java.util.stream.Stream;
  46 
  47 /**
  48  * This class consists exclusively of static methods that operate on or return
  49  * method handles. They fall into several categories:
  50  * <ul>
  51  * <li>Lookup methods which help create method handles for methods and fields.
  52  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  53  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  54  * </ul>
  55  *
  56  * @author John Rose, JSR 292 EG
  57  * @since 1.7
  58  */
  59 public class MethodHandles {
  60 
  61     private MethodHandles() { }  // do not instantiate
  62 
  63     private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  64 
  65     // See IMPL_LOOKUP below.
  66 
  67     //// Method handle creation from ordinary methods.
  68 
  69     /**
  70      * Returns a {@link Lookup lookup object} with
  71      * full capabilities to emulate all supported bytecode behaviors of the caller.
  72      * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller.
  73      * Factory methods on the lookup object can create
  74      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
  75      * for any member that the caller has access to via bytecodes,
  76      * including protected and private fields and methods.
  77      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
  78      * Do not store it in place where untrusted code can access it.
  79      * <p>
  80      * This method is caller sensitive, which means that it may return different
  81      * values to different callers.
  82      * <p>
  83      * For any given caller class {@code C}, the lookup object returned by this call
  84      * has equivalent capabilities to any lookup object
  85      * supplied by the JVM to the bootstrap method of an
  86      * <a href="package-summary.html#indyinsn">invokedynamic instruction</a>
  87      * executing in the same caller class {@code C}.
  88      * @return a lookup object for the caller of this method, with private access
  89      */
  90     @CallerSensitive
  91     public static Lookup lookup() {
  92         return new Lookup(Reflection.getCallerClass());
  93     }
  94 
  95     /**
  96      * Returns a {@link Lookup lookup object} which is trusted minimally.
  97      * It can only be used to create method handles to
  98      * publicly accessible fields and methods.
  99      * <p>
 100      * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class}
 101      * of this lookup object will be {@link java.lang.Object}.
 102      *
 103      * <p style="font-size:smaller;">
 104      * <em>Discussion:</em>
 105      * The lookup class can be changed to any other class {@code C} using an expression of the form
 106      * {@link Lookup#in publicLookup().in(C.class)}.
 107      * Since all classes have equal access to public names,
 108      * such a change would confer no new access rights.
 109      * A public lookup object is always subject to
 110      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 111      * Also, it cannot access
 112      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 113      * @return a lookup object which is trusted minimally
 114      */
 115     public static Lookup publicLookup() {
 116         return Lookup.PUBLIC_LOOKUP;
 117     }
 118 
 119     /**
 120      * Performs an unchecked "crack" of a
 121      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 122      * The result is as if the user had obtained a lookup object capable enough
 123      * to crack the target method handle, called
 124      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 125      * on the target to obtain its symbolic reference, and then called
 126      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 127      * to resolve the symbolic reference to a member.
 128      * <p>
 129      * If there is a security manager, its {@code checkPermission} method
 130      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 131      * @param <T> the desired type of the result, either {@link Member} or a subtype
 132      * @param target a direct method handle to crack into symbolic reference components
 133      * @param expected a class object representing the desired result type {@code T}
 134      * @return a reference to the method, constructor, or field object
 135      * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
 136      * @exception NullPointerException if either argument is {@code null}
 137      * @exception IllegalArgumentException if the target is not a direct method handle
 138      * @exception ClassCastException if the member is not of the expected type
 139      * @since 1.8
 140      */
 141     public static <T extends Member> T
 142     reflectAs(Class<T> expected, MethodHandle target) {
 143         SecurityManager smgr = System.getSecurityManager();
 144         if (smgr != null)  smgr.checkPermission(ACCESS_PERMISSION);
 145         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 146         return lookup.revealDirect(target).reflectAs(expected, lookup);
 147     }
 148     // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
 149     private static final java.security.Permission ACCESS_PERMISSION =
 150         new ReflectPermission("suppressAccessChecks");
 151 
 152     /**
 153      * A <em>lookup object</em> is a factory for creating method handles,
 154      * when the creation requires access checking.
 155      * Method handles do not perform
 156      * access checks when they are called, but rather when they are created.
 157      * Therefore, method handle access
 158      * restrictions must be enforced when a method handle is created.
 159      * The caller class against which those restrictions are enforced
 160      * is known as the {@linkplain #lookupClass lookup class}.
 161      * <p>
 162      * A lookup class which needs to create method handles will call
 163      * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself.
 164      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 165      * determined, and securely stored in the {@code Lookup} object.
 166      * The lookup class (or its delegates) may then use factory methods
 167      * on the {@code Lookup} object to create method handles for access-checked members.
 168      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 169      * even private ones.
 170      *
 171      * <h1><a name="lookups"></a>Lookup Factory Methods</h1>
 172      * The factory methods on a {@code Lookup} object correspond to all major
 173      * use cases for methods, constructors, and fields.
 174      * Each method handle created by a factory method is the functional
 175      * equivalent of a particular <em>bytecode behavior</em>.
 176      * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
 177      * Here is a summary of the correspondence between these factory methods and
 178      * the behavior of the resulting method handles:
 179      * <table border=1 cellpadding=5 summary="lookup method behaviors">
 180      * <tr>
 181      *     <th><a name="equiv"></a>lookup expression</th>
 182      *     <th>member</th>
 183      *     <th>bytecode behavior</th>
 184      * </tr>
 185      * <tr>
 186      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td>
 187      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 188      * </tr>
 189      * <tr>
 190      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td>
 191      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
 192      * </tr>
 193      * <tr>
 194      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td>
 195      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 196      * </tr>
 197      * <tr>
 198      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td>
 199      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 200      * </tr>
 201      * <tr>
 202      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td>
 203      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 204      * </tr>
 205      * <tr>
 206      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td>
 207      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 208      * </tr>
 209      * <tr>
 210      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td>
 211      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 212      * </tr>
 213      * <tr>
 214      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td>
 215      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 216      * </tr>
 217      * <tr>
 218      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td>
 219      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 220      * </tr>
 221      * <tr>
 222      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td>
 223      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 224      * </tr>
 225      * <tr>
 226      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
 227      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 228      * </tr>
 229      * <tr>
 230      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td>
 231      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 232      * </tr>
 233      * <tr>
 234      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
 235      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 236      * </tr>
 237      * <tr>
 238      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</td>
 239      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 240      * </tr>
 241      * </table>
 242      *
 243      * Here, the type {@code C} is the class or interface being searched for a member,
 244      * documented as a parameter named {@code refc} in the lookup methods.
 245      * The method type {@code MT} is composed from the return type {@code T}
 246      * and the sequence of argument types {@code A*}.
 247      * The constructor also has a sequence of argument types {@code A*} and
 248      * is deemed to return the newly-created object of type {@code C}.
 249      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 250      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 251      * if it is present, it is always the leading argument to the method handle invocation.
 252      * (In the case of some {@code protected} members, {@code this} may be
 253      * restricted in type to the lookup class; see below.)
 254      * The name {@code arg} stands for all the other method handle arguments.
 255      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 256      * stands for a null reference if the accessed method or field is static,
 257      * and {@code this} otherwise.
 258      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 259      * for reflective objects corresponding to the given members.
 260      * <p>
 261      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 262      * as if by {@code ldc CONSTANT_Class}.
 263      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 264      * <p>
 265      * In cases where the given member is of variable arity (i.e., a method or constructor)
 266      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 267      * In all other cases, the returned method handle will be of fixed arity.
 268      * <p style="font-size:smaller;">
 269      * <em>Discussion:</em>
 270      * The equivalence between looked-up method handles and underlying
 271      * class members and bytecode behaviors
 272      * can break down in a few ways:
 273      * <ul style="font-size:smaller;">
 274      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 275      * the lookup can still succeed, even when there is no equivalent
 276      * Java expression or bytecoded constant.
 277      * <li>Likewise, if {@code T} or {@code MT}
 278      * is not symbolically accessible from the lookup class's loader,
 279      * the lookup can still succeed.
 280      * For example, lookups for {@code MethodHandle.invokeExact} and
 281      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 282      * <li>If there is a security manager installed, it can forbid the lookup
 283      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 284      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 285      * constant is not subject to security manager checks.
 286      * <li>If the looked-up method has a
 287      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 288      * the method handle creation may fail, due to the method handle
 289      * type having too many parameters.
 290      * </ul>
 291      *
 292      * <h1><a name="access"></a>Access checking</h1>
 293      * Access checks are applied in the factory methods of {@code Lookup},
 294      * when a method handle is created.
 295      * This is a key difference from the Core Reflection API, since
 296      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 297      * performs access checking against every caller, on every call.
 298      * <p>
 299      * All access checks start from a {@code Lookup} object, which
 300      * compares its recorded lookup class against all requests to
 301      * create method handles.
 302      * A single {@code Lookup} object can be used to create any number
 303      * of access-checked method handles, all checked against a single
 304      * lookup class.
 305      * <p>
 306      * A {@code Lookup} object can be shared with other trusted code,
 307      * such as a metaobject protocol.
 308      * A shared {@code Lookup} object delegates the capability
 309      * to create method handles on private members of the lookup class.
 310      * Even if privileged code uses the {@code Lookup} object,
 311      * the access checking is confined to the privileges of the
 312      * original lookup class.
 313      * <p>
 314      * A lookup can fail, because
 315      * the containing class is not accessible to the lookup class, or
 316      * because the desired class member is missing, or because the
 317      * desired class member is not accessible to the lookup class, or
 318      * because the lookup object is not trusted enough to access the member.
 319      * In any of these cases, a {@code ReflectiveOperationException} will be
 320      * thrown from the attempted lookup.  The exact class will be one of
 321      * the following:
 322      * <ul>
 323      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 324      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 325      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 326      * </ul>
 327      * <p>
 328      * In general, the conditions under which a method handle may be
 329      * looked up for a method {@code M} are no more restrictive than the conditions
 330      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 331      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 332      * a method handle lookup will generally raise a corresponding
 333      * checked exception, such as {@code NoSuchMethodException}.
 334      * And the effect of invoking the method handle resulting from the lookup
 335      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 336      * to executing the compiled, verified, and resolved call to {@code M}.
 337      * The same point is true of fields and constructors.
 338      * <p style="font-size:smaller;">
 339      * <em>Discussion:</em>
 340      * Access checks only apply to named and reflected methods,
 341      * constructors, and fields.
 342      * Other method handle creation methods, such as
 343      * {@link MethodHandle#asType MethodHandle.asType},
 344      * do not require any access checks, and are used
 345      * independently of any {@code Lookup} object.
 346      * <p>
 347      * If the desired member is {@code protected}, the usual JVM rules apply,
 348      * including the requirement that the lookup class must be either be in the
 349      * same package as the desired member, or must inherit that member.
 350      * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.)
 351      * In addition, if the desired member is a non-static field or method
 352      * in a different package, the resulting method handle may only be applied
 353      * to objects of the lookup class or one of its subclasses.
 354      * This requirement is enforced by narrowing the type of the leading
 355      * {@code this} parameter from {@code C}
 356      * (which will necessarily be a superclass of the lookup class)
 357      * to the lookup class itself.
 358      * <p>
 359      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 360      * that the receiver argument must match both the resolved method <em>and</em>
 361      * the current class.  Again, this requirement is enforced by narrowing the
 362      * type of the leading parameter to the resulting method handle.
 363      * (See the Java Virtual Machine Specification, section 4.10.1.9.)
 364      * <p>
 365      * The JVM represents constructors and static initializer blocks as internal methods
 366      * with special names ({@code "<init>"} and {@code "<clinit>"}).
 367      * The internal syntax of invocation instructions allows them to refer to such internal
 368      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 369      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 370      * <p>
 371      * In some cases, access between nested classes is obtained by the Java compiler by creating
 372      * an wrapper method to access a private method of another class
 373      * in the same top-level declaration.
 374      * For example, a nested class {@code C.D}
 375      * can access private members within other related classes such as
 376      * {@code C}, {@code C.D.E}, or {@code C.B},
 377      * but the Java compiler may need to generate wrapper methods in
 378      * those related classes.  In such cases, a {@code Lookup} object on
 379      * {@code C.E} would be unable to those private members.
 380      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 381      * which can transform a lookup on {@code C.E} into one on any of those other
 382      * classes, without special elevation of privilege.
 383      * <p>
 384      * The accesses permitted to a given lookup object may be limited,
 385      * according to its set of {@link #lookupModes lookupModes},
 386      * to a subset of members normally accessible to the lookup class.
 387      * For example, the {@link MethodHandles#publicLookup publicLookup}
 388      * method produces a lookup object which is only allowed to access
 389      * public members in public classes.
 390      * The caller sensitive method {@link MethodHandles#lookup lookup}
 391      * produces a lookup object with full capabilities relative to
 392      * its caller class, to emulate all supported bytecode behaviors.
 393      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 394      * with fewer access modes than the original lookup object.
 395      *
 396      * <p style="font-size:smaller;">
 397      * <a name="privacc"></a>
 398      * <em>Discussion of private access:</em>
 399      * We say that a lookup has <em>private access</em>
 400      * if its {@linkplain #lookupModes lookup modes}
 401      * include the possibility of accessing {@code private} members.
 402      * As documented in the relevant methods elsewhere,
 403      * only lookups with private access possess the following capabilities:
 404      * <ul style="font-size:smaller;">
 405      * <li>access private fields, methods, and constructors of the lookup class
 406      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 407      *     such as {@code Class.forName}
 408      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 409      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 410      *     for classes accessible to the lookup class
 411      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 412      *     within the same package member
 413      * </ul>
 414      * <p style="font-size:smaller;">
 415      * Each of these permissions is a consequence of the fact that a lookup object
 416      * with private access can be securely traced back to an originating class,
 417      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 418      * can be reliably determined and emulated by method handles.
 419      *
 420      * <h1><a name="secmgr"></a>Security manager interactions</h1>
 421      * Although bytecode instructions can only refer to classes in
 422      * a related class loader, this API can search for methods in any
 423      * class, as long as a reference to its {@code Class} object is
 424      * available.  Such cross-loader references are also possible with the
 425      * Core Reflection API, and are impossible to bytecode instructions
 426      * such as {@code invokestatic} or {@code getfield}.
 427      * There is a {@linkplain java.lang.SecurityManager security manager API}
 428      * to allow applications to check such cross-loader references.
 429      * These checks apply to both the {@code MethodHandles.Lookup} API
 430      * and the Core Reflection API
 431      * (as found on {@link java.lang.Class Class}).
 432      * <p>
 433      * If a security manager is present, member and class lookups are subject to
 434      * additional checks.
 435      * From one to three calls are made to the security manager.
 436      * Any of these calls can refuse access by throwing a
 437      * {@link java.lang.SecurityException SecurityException}.
 438      * Define {@code smgr} as the security manager,
 439      * {@code lookc} as the lookup class of the current lookup object,
 440      * {@code refc} as the containing class in which the member
 441      * is being sought, and {@code defc} as the class in which the
 442      * member is actually defined.
 443      * (If a class or other type is being accessed,
 444      * the {@code refc} and {@code defc} values are the class itself.)
 445      * The value {@code lookc} is defined as <em>not present</em>
 446      * if the current lookup object does not have
 447      * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 448      * The calls are made according to the following rules:
 449      * <ul>
 450      * <li><b>Step 1:</b>
 451      *     If {@code lookc} is not present, or if its class loader is not
 452      *     the same as or an ancestor of the class loader of {@code refc},
 453      *     then {@link SecurityManager#checkPackageAccess
 454      *     smgr.checkPackageAccess(refcPkg)} is called,
 455      *     where {@code refcPkg} is the package of {@code refc}.
 456      * <li><b>Step 2a:</b>
 457      *     If the retrieved member is not public and
 458      *     {@code lookc} is not present, then
 459      *     {@link SecurityManager#checkPermission smgr.checkPermission}
 460      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
 461      * <li><b>Step 2b:</b>
 462      *     If the retrieved class has a {@code null} class loader,
 463      *     and {@code lookc} is not present, then
 464      *     {@link SecurityManager#checkPermission smgr.checkPermission}
 465      *     with {@code RuntimePermission("getClassLoader")} is called.
 466      * <li><b>Step 3:</b>
 467      *     If the retrieved member is not public,
 468      *     and if {@code lookc} is not present,
 469      *     and if {@code defc} and {@code refc} are different,
 470      *     then {@link SecurityManager#checkPackageAccess
 471      *     smgr.checkPackageAccess(defcPkg)} is called,
 472      *     where {@code defcPkg} is the package of {@code defc}.
 473      * </ul>
 474      * Security checks are performed after other access checks have passed.
 475      * Therefore, the above rules presuppose a member or class that is public,
 476      * or else that is being accessed from a lookup class that has
 477      * rights to access the member or class.
 478      *
 479      * <h1><a name="callsens"></a>Caller sensitive methods</h1>
 480      * A small number of Java methods have a special property called caller sensitivity.
 481      * A <em>caller-sensitive</em> method can behave differently depending on the
 482      * identity of its immediate caller.
 483      * <p>
 484      * If a method handle for a caller-sensitive method is requested,
 485      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
 486      * but they take account of the lookup class in a special way.
 487      * The resulting method handle behaves as if it were called
 488      * from an instruction contained in the lookup class,
 489      * so that the caller-sensitive method detects the lookup class.
 490      * (By contrast, the invoker of the method handle is disregarded.)
 491      * Thus, in the case of caller-sensitive methods,
 492      * different lookup classes may give rise to
 493      * differently behaving method handles.
 494      * <p>
 495      * In cases where the lookup object is
 496      * {@link MethodHandles#publicLookup() publicLookup()},
 497      * or some other lookup object without
 498      * <a href="MethodHandles.Lookup.html#privacc">private access</a>,
 499      * the lookup class is disregarded.
 500      * In such cases, no caller-sensitive method handle can be created,
 501      * access is forbidden, and the lookup fails with an
 502      * {@code IllegalAccessException}.
 503      * <p style="font-size:smaller;">
 504      * <em>Discussion:</em>
 505      * For example, the caller-sensitive method
 506      * {@link java.lang.Class#forName(String) Class.forName(x)}
 507      * can return varying classes or throw varying exceptions,
 508      * depending on the class loader of the class that calls it.
 509      * A public lookup of {@code Class.forName} will fail, because
 510      * there is no reasonable way to determine its bytecode behavior.
 511      * <p style="font-size:smaller;">
 512      * If an application caches method handles for broad sharing,
 513      * it should use {@code publicLookup()} to create them.
 514      * If there is a lookup of {@code Class.forName}, it will fail,
 515      * and the application must take appropriate action in that case.
 516      * It may be that a later lookup, perhaps during the invocation of a
 517      * bootstrap method, can incorporate the specific identity
 518      * of the caller, making the method accessible.
 519      * <p style="font-size:smaller;">
 520      * The function {@code MethodHandles.lookup} is caller sensitive
 521      * so that there can be a secure foundation for lookups.
 522      * Nearly all other methods in the JSR 292 API rely on lookup
 523      * objects to check access requests.
 524      */
 525     public static final
 526     class Lookup {
 527         /** The class on behalf of whom the lookup is being performed. */
 528         private final Class<?> lookupClass;
 529 
 530         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
 531         private final int allowedModes;
 532 
 533         /** A single-bit mask representing {@code public} access,
 534          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 535          *  The value, {@code 0x01}, happens to be the same as the value of the
 536          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
 537          */
 538         public static final int PUBLIC = Modifier.PUBLIC;
 539 
 540         /** A single-bit mask representing {@code private} access,
 541          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 542          *  The value, {@code 0x02}, happens to be the same as the value of the
 543          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
 544          */
 545         public static final int PRIVATE = Modifier.PRIVATE;
 546 
 547         /** A single-bit mask representing {@code protected} access,
 548          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 549          *  The value, {@code 0x04}, happens to be the same as the value of the
 550          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
 551          */
 552         public static final int PROTECTED = Modifier.PROTECTED;
 553 
 554         /** A single-bit mask representing {@code package} access (default access),
 555          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 556          *  The value is {@code 0x08}, which does not correspond meaningfully to
 557          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
 558          */
 559         public static final int PACKAGE = Modifier.STATIC;
 560 
 561         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE);
 562         private static final int TRUSTED   = -1;
 563 
 564         private static int fixmods(int mods) {
 565             mods &= (ALL_MODES - PACKAGE);
 566             return (mods != 0) ? mods : PACKAGE;
 567         }
 568 
 569         /** Tells which class is performing the lookup.  It is this class against
 570          *  which checks are performed for visibility and access permissions.
 571          *  <p>
 572          *  The class implies a maximum level of access permission,
 573          *  but the permissions may be additionally limited by the bitmask
 574          *  {@link #lookupModes lookupModes}, which controls whether non-public members
 575          *  can be accessed.
 576          *  @return the lookup class, on behalf of which this lookup object finds members
 577          */
 578         public Class<?> lookupClass() {
 579             return lookupClass;
 580         }
 581 
 582         // This is just for calling out to MethodHandleImpl.
 583         private Class<?> lookupClassOrNull() {
 584             return (allowedModes == TRUSTED) ? null : lookupClass;
 585         }
 586 
 587         /** Tells which access-protection classes of members this lookup object can produce.
 588          *  The result is a bit-mask of the bits
 589          *  {@linkplain #PUBLIC PUBLIC (0x01)},
 590          *  {@linkplain #PRIVATE PRIVATE (0x02)},
 591          *  {@linkplain #PROTECTED PROTECTED (0x04)},
 592          *  and {@linkplain #PACKAGE PACKAGE (0x08)}.
 593          *  <p>
 594          *  A freshly-created lookup object
 595          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
 596          *  has all possible bits set, since the caller class can access all its own members.
 597          *  A lookup object on a new lookup class
 598          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
 599          *  may have some mode bits set to zero.
 600          *  The purpose of this is to restrict access via the new lookup object,
 601          *  so that it can access only names which can be reached by the original
 602          *  lookup object, and also by the new lookup class.
 603          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
 604          */
 605         public int lookupModes() {
 606             return allowedModes & ALL_MODES;
 607         }
 608 
 609         /** Embody the current class (the lookupClass) as a lookup class
 610          * for method handle creation.
 611          * Must be called by from a method in this package,
 612          * which in turn is called by a method not in this package.
 613          */
 614         Lookup(Class<?> lookupClass) {
 615             this(lookupClass, ALL_MODES);
 616             // make sure we haven't accidentally picked up a privileged class:
 617             checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
 618         }
 619 
 620         private Lookup(Class<?> lookupClass, int allowedModes) {
 621             this.lookupClass = lookupClass;
 622             this.allowedModes = allowedModes;
 623         }
 624 
 625         /**
 626          * Creates a lookup on the specified new lookup class.
 627          * The resulting object will report the specified
 628          * class as its own {@link #lookupClass lookupClass}.
 629          * <p>
 630          * However, the resulting {@code Lookup} object is guaranteed
 631          * to have no more access capabilities than the original.
 632          * In particular, access capabilities can be lost as follows:<ul>
 633          * <li>If the new lookup class differs from the old one,
 634          * protected members will not be accessible by virtue of inheritance.
 635          * (Protected members may continue to be accessible because of package sharing.)
 636          * <li>If the new lookup class is in a different package
 637          * than the old one, protected and default (package) members will not be accessible.
 638          * <li>If the new lookup class is not within the same package member
 639          * as the old one, private members will not be accessible.
 640          * <li>If the new lookup class is not accessible to the old lookup class,
 641          * then no members, not even public members, will be accessible.
 642          * (In all other cases, public members will continue to be accessible.)
 643          * </ul>
 644          *
 645          * @param requestedLookupClass the desired lookup class for the new lookup object
 646          * @return a lookup object which reports the desired lookup class
 647          * @throws NullPointerException if the argument is null
 648          */
 649         public Lookup in(Class<?> requestedLookupClass) {
 650             Objects.requireNonNull(requestedLookupClass);
 651             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
 652                 return new Lookup(requestedLookupClass, ALL_MODES);
 653             if (requestedLookupClass == this.lookupClass)
 654                 return this;  // keep same capabilities
 655             int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
 656             if ((newModes & PACKAGE) != 0
 657                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
 658                 newModes &= ~(PACKAGE|PRIVATE);
 659             }
 660             // Allow nestmate lookups to be created without special privilege:
 661             if ((newModes & PRIVATE) != 0
 662                 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
 663                 newModes &= ~PRIVATE;
 664             }
 665             if ((newModes & PUBLIC) != 0
 666                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
 667                 // The requested class it not accessible from the lookup class.
 668                 // No permissions.
 669                 newModes = 0;
 670             }
 671             checkUnprivilegedlookupClass(requestedLookupClass, newModes);
 672             return new Lookup(requestedLookupClass, newModes);
 673         }
 674 
 675         // Make sure outer class is initialized first.
 676         static { IMPL_NAMES.getClass(); }
 677 
 678         /** Version of lookup which is trusted minimally.
 679          *  It can only be used to create method handles to
 680          *  publicly accessible members.
 681          */
 682         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, PUBLIC);
 683 
 684         /** Package-private version of lookup which is trusted. */
 685         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
 686 
 687         private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) {
 688             String name = lookupClass.getName();
 689             if (name.startsWith("java.lang.invoke."))
 690                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
 691 
 692             // For caller-sensitive MethodHandles.lookup()
 693             // disallow lookup more restricted packages
 694             if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) {
 695                 if (name.startsWith("java.") ||
 696                         (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) {
 697                     throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
 698                 }
 699             }
 700         }
 701 
 702         /**
 703          * Displays the name of the class from which lookups are to be made.
 704          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
 705          * If there are restrictions on the access permitted to this lookup,
 706          * this is indicated by adding a suffix to the class name, consisting
 707          * of a slash and a keyword.  The keyword represents the strongest
 708          * allowed access, and is chosen as follows:
 709          * <ul>
 710          * <li>If no access is allowed, the suffix is "/noaccess".
 711          * <li>If only public access is allowed, the suffix is "/public".
 712          * <li>If only public and package access are allowed, the suffix is "/package".
 713          * <li>If only public, package, and private access are allowed, the suffix is "/private".
 714          * </ul>
 715          * If none of the above cases apply, it is the case that full
 716          * access (public, package, private, and protected) is allowed.
 717          * In this case, no suffix is added.
 718          * This is true only of an object obtained originally from
 719          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
 720          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
 721          * always have restricted access, and will display a suffix.
 722          * <p>
 723          * (It may seem strange that protected access should be
 724          * stronger than private access.  Viewed independently from
 725          * package access, protected access is the first to be lost,
 726          * because it requires a direct subclass relationship between
 727          * caller and callee.)
 728          * @see #in
 729          */
 730         @Override
 731         public String toString() {
 732             String cname = lookupClass.getName();
 733             switch (allowedModes) {
 734             case 0:  // no privileges
 735                 return cname + "/noaccess";
 736             case PUBLIC:
 737                 return cname + "/public";
 738             case PUBLIC|PACKAGE:
 739                 return cname + "/package";
 740             case ALL_MODES & ~PROTECTED:
 741                 return cname + "/private";
 742             case ALL_MODES:
 743                 return cname;
 744             case TRUSTED:
 745                 return "/trusted";  // internal only; not exported
 746             default:  // Should not happen, but it's a bitfield...
 747                 cname = cname + "/" + Integer.toHexString(allowedModes);
 748                 assert(false) : cname;
 749                 return cname;
 750             }
 751         }
 752 
 753         /**
 754          * Produces a method handle for a static method.
 755          * The type of the method handle will be that of the method.
 756          * (Since static methods do not take receivers, there is no
 757          * additional receiver argument inserted into the method handle type,
 758          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
 759          * The method and all its argument types must be accessible to the lookup object.
 760          * <p>
 761          * The returned method handle will have
 762          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 763          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 764          * <p>
 765          * If the returned method handle is invoked, the method's class will
 766          * be initialized, if it has not already been initialized.
 767          * <p><b>Example:</b>
 768          * <blockquote><pre>{@code
 769 import static java.lang.invoke.MethodHandles.*;
 770 import static java.lang.invoke.MethodType.*;
 771 ...
 772 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
 773   "asList", methodType(List.class, Object[].class));
 774 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
 775          * }</pre></blockquote>
 776          * @param refc the class from which the method is accessed
 777          * @param name the name of the method
 778          * @param type the type of the method
 779          * @return the desired method handle
 780          * @throws NoSuchMethodException if the method does not exist
 781          * @throws IllegalAccessException if access checking fails,
 782          *                                or if the method is not {@code static},
 783          *                                or if the method's variable arity modifier bit
 784          *                                is set and {@code asVarargsCollector} fails
 785          * @exception SecurityException if a security manager is present and it
 786          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 787          * @throws NullPointerException if any argument is null
 788          */
 789         public
 790         MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 791             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
 792             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method));
 793         }
 794 
 795         /**
 796          * Produces a method handle for a virtual method.
 797          * The type of the method handle will be that of the method,
 798          * with the receiver type (usually {@code refc}) prepended.
 799          * The method and all its argument types must be accessible to the lookup object.
 800          * <p>
 801          * When called, the handle will treat the first argument as a receiver
 802          * and dispatch on the receiver's type to determine which method
 803          * implementation to enter.
 804          * (The dispatching action is identical with that performed by an
 805          * {@code invokevirtual} or {@code invokeinterface} instruction.)
 806          * <p>
 807          * The first argument will be of type {@code refc} if the lookup
 808          * class has full privileges to access the member.  Otherwise
 809          * the member must be {@code protected} and the first argument
 810          * will be restricted in type to the lookup class.
 811          * <p>
 812          * The returned method handle will have
 813          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 814          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 815          * <p>
 816          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
 817          * instructions and method handles produced by {@code findVirtual},
 818          * if the class is {@code MethodHandle} and the name string is
 819          * {@code invokeExact} or {@code invoke}, the resulting
 820          * method handle is equivalent to one produced by
 821          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
 822          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
 823          * with the same {@code type} argument.
 824          *
 825          * <b>Example:</b>
 826          * <blockquote><pre>{@code
 827 import static java.lang.invoke.MethodHandles.*;
 828 import static java.lang.invoke.MethodType.*;
 829 ...
 830 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
 831   "concat", methodType(String.class, String.class));
 832 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
 833   "hashCode", methodType(int.class));
 834 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
 835   "hashCode", methodType(int.class));
 836 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
 837 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
 838 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
 839 // interface method:
 840 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
 841   "subSequence", methodType(CharSequence.class, int.class, int.class));
 842 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
 843 // constructor "internal method" must be accessed differently:
 844 MethodType MT_newString = methodType(void.class); //()V for new String()
 845 try { assertEquals("impossible", lookup()
 846         .findVirtual(String.class, "<init>", MT_newString));
 847  } catch (NoSuchMethodException ex) { } // OK
 848 MethodHandle MH_newString = publicLookup()
 849   .findConstructor(String.class, MT_newString);
 850 assertEquals("", (String) MH_newString.invokeExact());
 851          * }</pre></blockquote>
 852          *
 853          * @param refc the class or interface from which the method is accessed
 854          * @param name the name of the method
 855          * @param type the type of the method, with the receiver argument omitted
 856          * @return the desired method handle
 857          * @throws NoSuchMethodException if the method does not exist
 858          * @throws IllegalAccessException if access checking fails,
 859          *                                or if the method is {@code static}
 860          *                                or if the method's variable arity modifier bit
 861          *                                is set and {@code asVarargsCollector} fails
 862          * @exception SecurityException if a security manager is present and it
 863          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 864          * @throws NullPointerException if any argument is null
 865          */
 866         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 867             if (refc == MethodHandle.class) {
 868                 MethodHandle mh = findVirtualForMH(name, type);
 869                 if (mh != null)  return mh;
 870             }
 871             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
 872             MemberName method = resolveOrFail(refKind, refc, name, type);
 873             return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
 874         }
 875         private MethodHandle findVirtualForMH(String name, MethodType type) {
 876             // these names require special lookups because of the implicit MethodType argument
 877             if ("invoke".equals(name))
 878                 return invoker(type);
 879             if ("invokeExact".equals(name))
 880                 return exactInvoker(type);
 881             if ("invokeBasic".equals(name))
 882                 return basicInvoker(type);
 883             assert(!MemberName.isMethodHandleInvokeName(name));
 884             return null;
 885         }
 886 
 887         /**
 888          * Produces a method handle which creates an object and initializes it, using
 889          * the constructor of the specified type.
 890          * The parameter types of the method handle will be those of the constructor,
 891          * while the return type will be a reference to the constructor's class.
 892          * The constructor and all its argument types must be accessible to the lookup object.
 893          * <p>
 894          * The requested type must have a return type of {@code void}.
 895          * (This is consistent with the JVM's treatment of constructor type descriptors.)
 896          * <p>
 897          * The returned method handle will have
 898          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 899          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
 900          * <p>
 901          * If the returned method handle is invoked, the constructor's class will
 902          * be initialized, if it has not already been initialized.
 903          * <p><b>Example:</b>
 904          * <blockquote><pre>{@code
 905 import static java.lang.invoke.MethodHandles.*;
 906 import static java.lang.invoke.MethodType.*;
 907 ...
 908 MethodHandle MH_newArrayList = publicLookup().findConstructor(
 909   ArrayList.class, methodType(void.class, Collection.class));
 910 Collection orig = Arrays.asList("x", "y");
 911 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
 912 assert(orig != copy);
 913 assertEquals(orig, copy);
 914 // a variable-arity constructor:
 915 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
 916   ProcessBuilder.class, methodType(void.class, String[].class));
 917 ProcessBuilder pb = (ProcessBuilder)
 918   MH_newProcessBuilder.invoke("x", "y", "z");
 919 assertEquals("[x, y, z]", pb.command().toString());
 920          * }</pre></blockquote>
 921          * @param refc the class or interface from which the method is accessed
 922          * @param type the type of the method, with the receiver argument omitted, and a void return type
 923          * @return the desired method handle
 924          * @throws NoSuchMethodException if the constructor does not exist
 925          * @throws IllegalAccessException if access checking fails
 926          *                                or if the method's variable arity modifier bit
 927          *                                is set and {@code asVarargsCollector} fails
 928          * @exception SecurityException if a security manager is present and it
 929          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 930          * @throws NullPointerException if any argument is null
 931          */
 932         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 933             String name = "<init>";
 934             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
 935             return getDirectConstructor(refc, ctor);
 936         }
 937 
 938         /**
 939          * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static
 940          * initializer of the class is not run.
 941          *
 942          * @param targetName the fully qualified name of the class to be looked up.
 943          * @return the requested class.
 944          * @exception SecurityException if a security manager is present and it
 945          *            <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 946          * @throws LinkageError if the linkage fails
 947          * @throws ClassNotFoundException if the class does not exist.
 948          * @throws IllegalAccessException if the class is not accessible, using the allowed access
 949          * modes.
 950          * @exception SecurityException if a security manager is present and it
 951          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 952          * @since 9
 953          */
 954         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
 955             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
 956             return accessClass(targetClass);
 957         }
 958 
 959         /**
 960          * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The
 961          * static initializer of the class is not run.
 962          *
 963          * @param targetClass the class to be access-checked
 964          *
 965          * @return the class that has been access-checked
 966          *
 967          * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access
 968          * modes.
 969          * @exception SecurityException if a security manager is present and it
 970          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 971          * @since 9
 972          */
 973         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
 974             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) {
 975                 throw new MemberName(targetClass).makeAccessException("access violation", this);
 976             }
 977             checkSecurityManager(targetClass, null);
 978             return targetClass;
 979         }
 980 
 981         /**
 982          * Produces an early-bound method handle for a virtual method.
 983          * It will bypass checks for overriding methods on the receiver,
 984          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
 985          * instruction from within the explicitly specified {@code specialCaller}.
 986          * The type of the method handle will be that of the method,
 987          * with a suitably restricted receiver type prepended.
 988          * (The receiver type will be {@code specialCaller} or a subtype.)
 989          * The method and all its argument types must be accessible
 990          * to the lookup object.
 991          * <p>
 992          * Before method resolution,
 993          * if the explicitly specified caller class is not identical with the
 994          * lookup class, or if this lookup object does not have
 995          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
 996          * privileges, the access fails.
 997          * <p>
 998          * The returned method handle will have
 999          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1000          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1001          * <p style="font-size:smaller;">
1002          * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
1003          * even though the {@code invokespecial} instruction can refer to them
1004          * in special circumstances.  Use {@link #findConstructor findConstructor}
1005          * to access instance initialization methods in a safe manner.)</em>
1006          * <p><b>Example:</b>
1007          * <blockquote><pre>{@code
1008 import static java.lang.invoke.MethodHandles.*;
1009 import static java.lang.invoke.MethodType.*;
1010 ...
1011 static class Listie extends ArrayList {
1012   public String toString() { return "[wee Listie]"; }
1013   static Lookup lookup() { return MethodHandles.lookup(); }
1014 }
1015 ...
1016 // no access to constructor via invokeSpecial:
1017 MethodHandle MH_newListie = Listie.lookup()
1018   .findConstructor(Listie.class, methodType(void.class));
1019 Listie l = (Listie) MH_newListie.invokeExact();
1020 try { assertEquals("impossible", Listie.lookup().findSpecial(
1021         Listie.class, "<init>", methodType(void.class), Listie.class));
1022  } catch (NoSuchMethodException ex) { } // OK
1023 // access to super and self methods via invokeSpecial:
1024 MethodHandle MH_super = Listie.lookup().findSpecial(
1025   ArrayList.class, "toString" , methodType(String.class), Listie.class);
1026 MethodHandle MH_this = Listie.lookup().findSpecial(
1027   Listie.class, "toString" , methodType(String.class), Listie.class);
1028 MethodHandle MH_duper = Listie.lookup().findSpecial(
1029   Object.class, "toString" , methodType(String.class), Listie.class);
1030 assertEquals("[]", (String) MH_super.invokeExact(l));
1031 assertEquals(""+l, (String) MH_this.invokeExact(l));
1032 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
1033 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
1034         String.class, "toString", methodType(String.class), Listie.class));
1035  } catch (IllegalAccessException ex) { } // OK
1036 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
1037 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
1038          * }</pre></blockquote>
1039          *
1040          * @param refc the class or interface from which the method is accessed
1041          * @param name the name of the method (which must not be "&lt;init&gt;")
1042          * @param type the type of the method, with the receiver argument omitted
1043          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
1044          * @return the desired method handle
1045          * @throws NoSuchMethodException if the method does not exist
1046          * @throws IllegalAccessException if access checking fails
1047          *                                or if the method's variable arity modifier bit
1048          *                                is set and {@code asVarargsCollector} fails
1049          * @exception SecurityException if a security manager is present and it
1050          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1051          * @throws NullPointerException if any argument is null
1052          */
1053         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
1054                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
1055             checkSpecialCaller(specialCaller, refc);
1056             Lookup specialLookup = this.in(specialCaller);
1057             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
1058             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1059         }
1060 
1061         /**
1062          * Produces a method handle giving read access to a non-static field.
1063          * The type of the method handle will have a return type of the field's
1064          * value type.
1065          * The method handle's single argument will be the instance containing
1066          * the field.
1067          * Access checking is performed immediately on behalf of the lookup class.
1068          * @param refc the class or interface from which the method is accessed
1069          * @param name the field's name
1070          * @param type the field's type
1071          * @return a method handle which can load values from the field
1072          * @throws NoSuchFieldException if the field does not exist
1073          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1074          * @exception SecurityException if a security manager is present and it
1075          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1076          * @throws NullPointerException if any argument is null
1077          */
1078         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1079             MemberName field = resolveOrFail(REF_getField, refc, name, type);
1080             return getDirectField(REF_getField, refc, field);
1081         }
1082 
1083         /**
1084          * Produces a method handle giving write access to a non-static field.
1085          * The type of the method handle will have a void return type.
1086          * The method handle will take two arguments, the instance containing
1087          * the field, and the value to be stored.
1088          * The second argument will be of the field's value type.
1089          * Access checking is performed immediately on behalf of the lookup class.
1090          * @param refc the class or interface from which the method is accessed
1091          * @param name the field's name
1092          * @param type the field's type
1093          * @return a method handle which can store values into the field
1094          * @throws NoSuchFieldException if the field does not exist
1095          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1096          * @exception SecurityException if a security manager is present and it
1097          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1098          * @throws NullPointerException if any argument is null
1099          */
1100         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1101             MemberName field = resolveOrFail(REF_putField, refc, name, type);
1102             return getDirectField(REF_putField, refc, field);
1103         }
1104 
1105         /**
1106          * Produces a method handle giving read access to a static field.
1107          * The type of the method handle will have a return type of the field's
1108          * value type.
1109          * The method handle will take no arguments.
1110          * Access checking is performed immediately on behalf of the lookup class.
1111          * <p>
1112          * If the returned method handle is invoked, the field's class will
1113          * be initialized, if it has not already been initialized.
1114          * @param refc the class or interface from which the method is accessed
1115          * @param name the field's name
1116          * @param type the field's type
1117          * @return a method handle which can load values from the field
1118          * @throws NoSuchFieldException if the field does not exist
1119          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1120          * @exception SecurityException if a security manager is present and it
1121          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1122          * @throws NullPointerException if any argument is null
1123          */
1124         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1125             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
1126             return getDirectField(REF_getStatic, refc, field);
1127         }
1128 
1129         /**
1130          * Produces a method handle giving write access to a static field.
1131          * The type of the method handle will have a void return type.
1132          * The method handle will take a single
1133          * argument, of the field's value type, the value to be stored.
1134          * Access checking is performed immediately on behalf of the lookup class.
1135          * <p>
1136          * If the returned method handle is invoked, the field's class will
1137          * be initialized, if it has not already been initialized.
1138          * @param refc the class or interface from which the method is accessed
1139          * @param name the field's name
1140          * @param type the field's type
1141          * @return a method handle which can store values into the field
1142          * @throws NoSuchFieldException if the field does not exist
1143          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1144          * @exception SecurityException if a security manager is present and it
1145          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1146          * @throws NullPointerException if any argument is null
1147          */
1148         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1149             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
1150             return getDirectField(REF_putStatic, refc, field);
1151         }
1152 
1153         /**
1154          * Produces an early-bound method handle for a non-static method.
1155          * The receiver must have a supertype {@code defc} in which a method
1156          * of the given name and type is accessible to the lookup class.
1157          * The method and all its argument types must be accessible to the lookup object.
1158          * The type of the method handle will be that of the method,
1159          * without any insertion of an additional receiver parameter.
1160          * The given receiver will be bound into the method handle,
1161          * so that every call to the method handle will invoke the
1162          * requested method on the given receiver.
1163          * <p>
1164          * The returned method handle will have
1165          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1166          * the method's variable arity modifier bit ({@code 0x0080}) is set
1167          * <em>and</em> the trailing array argument is not the only argument.
1168          * (If the trailing array argument is the only argument,
1169          * the given receiver value will be bound to it.)
1170          * <p>
1171          * This is equivalent to the following code:
1172          * <blockquote><pre>{@code
1173 import static java.lang.invoke.MethodHandles.*;
1174 import static java.lang.invoke.MethodType.*;
1175 ...
1176 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
1177 MethodHandle mh1 = mh0.bindTo(receiver);
1178 MethodType mt1 = mh1.type();
1179 if (mh0.isVarargsCollector())
1180   mh1 = mh1.asVarargsCollector(mt1.parameterType(mt1.parameterCount()-1));
1181 return mh1;
1182          * }</pre></blockquote>
1183          * where {@code defc} is either {@code receiver.getClass()} or a super
1184          * type of that class, in which the requested method is accessible
1185          * to the lookup class.
1186          * (Note that {@code bindTo} does not preserve variable arity.)
1187          * @param receiver the object from which the method is accessed
1188          * @param name the name of the method
1189          * @param type the type of the method, with the receiver argument omitted
1190          * @return the desired method handle
1191          * @throws NoSuchMethodException if the method does not exist
1192          * @throws IllegalAccessException if access checking fails
1193          *                                or if the method's variable arity modifier bit
1194          *                                is set and {@code asVarargsCollector} fails
1195          * @exception SecurityException if a security manager is present and it
1196          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1197          * @throws NullPointerException if any argument is null
1198          * @see MethodHandle#bindTo
1199          * @see #findVirtual
1200          */
1201         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1202             Class<? extends Object> refc = receiver.getClass(); // may get NPE
1203             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
1204             MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1205             return mh.bindArgumentL(0, receiver).setVarargs(method);
1206         }
1207 
1208         /**
1209          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1210          * to <i>m</i>, if the lookup class has permission.
1211          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
1212          * If <i>m</i> is virtual, overriding is respected on every call.
1213          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
1214          * The type of the method handle will be that of the method,
1215          * with the receiver type prepended (but only if it is non-static).
1216          * If the method's {@code accessible} flag is not set,
1217          * access checking is performed immediately on behalf of the lookup class.
1218          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
1219          * <p>
1220          * The returned method handle will have
1221          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1222          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1223          * <p>
1224          * If <i>m</i> is static, and
1225          * if the returned method handle is invoked, the method's class will
1226          * be initialized, if it has not already been initialized.
1227          * @param m the reflected method
1228          * @return a method handle which can invoke the reflected method
1229          * @throws IllegalAccessException if access checking fails
1230          *                                or if the method's variable arity modifier bit
1231          *                                is set and {@code asVarargsCollector} fails
1232          * @throws NullPointerException if the argument is null
1233          */
1234         public MethodHandle unreflect(Method m) throws IllegalAccessException {
1235             if (m.getDeclaringClass() == MethodHandle.class) {
1236                 MethodHandle mh = unreflectForMH(m);
1237                 if (mh != null)  return mh;
1238             }
1239             MemberName method = new MemberName(m);
1240             byte refKind = method.getReferenceKind();
1241             if (refKind == REF_invokeSpecial)
1242                 refKind = REF_invokeVirtual;
1243             assert(method.isMethod());
1244             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
1245             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
1246         }
1247         private MethodHandle unreflectForMH(Method m) {
1248             // these names require special lookups because they throw UnsupportedOperationException
1249             if (MemberName.isMethodHandleInvokeName(m.getName()))
1250                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
1251             return null;
1252         }
1253 
1254         /**
1255          * Produces a method handle for a reflected method.
1256          * It will bypass checks for overriding methods on the receiver,
1257          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1258          * instruction from within the explicitly specified {@code specialCaller}.
1259          * The type of the method handle will be that of the method,
1260          * with a suitably restricted receiver type prepended.
1261          * (The receiver type will be {@code specialCaller} or a subtype.)
1262          * If the method's {@code accessible} flag is not set,
1263          * access checking is performed immediately on behalf of the lookup class,
1264          * as if {@code invokespecial} instruction were being linked.
1265          * <p>
1266          * Before method resolution,
1267          * if the explicitly specified caller class is not identical with the
1268          * lookup class, or if this lookup object does not have
1269          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1270          * privileges, the access fails.
1271          * <p>
1272          * The returned method handle will have
1273          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1274          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1275          * @param m the reflected method
1276          * @param specialCaller the class nominally calling the method
1277          * @return a method handle which can invoke the reflected method
1278          * @throws IllegalAccessException if access checking fails
1279          *                                or if the method's variable arity modifier bit
1280          *                                is set and {@code asVarargsCollector} fails
1281          * @throws NullPointerException if any argument is null
1282          */
1283         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
1284             checkSpecialCaller(specialCaller, null);
1285             Lookup specialLookup = this.in(specialCaller);
1286             MemberName method = new MemberName(m, true);
1287             assert(method.isMethod());
1288             // ignore m.isAccessible:  this is a new kind of access
1289             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
1290         }
1291 
1292         /**
1293          * Produces a method handle for a reflected constructor.
1294          * The type of the method handle will be that of the constructor,
1295          * with the return type changed to the declaring class.
1296          * The method handle will perform a {@code newInstance} operation,
1297          * creating a new instance of the constructor's class on the
1298          * arguments passed to the method handle.
1299          * <p>
1300          * If the constructor's {@code accessible} flag is not set,
1301          * access checking is performed immediately on behalf of the lookup class.
1302          * <p>
1303          * The returned method handle will have
1304          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1305          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
1306          * <p>
1307          * If the returned method handle is invoked, the constructor's class will
1308          * be initialized, if it has not already been initialized.
1309          * @param c the reflected constructor
1310          * @return a method handle which can invoke the reflected constructor
1311          * @throws IllegalAccessException if access checking fails
1312          *                                or if the method's variable arity modifier bit
1313          *                                is set and {@code asVarargsCollector} fails
1314          * @throws NullPointerException if the argument is null
1315          */
1316         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
1317             MemberName ctor = new MemberName(c);
1318             assert(ctor.isConstructor());
1319             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
1320             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
1321         }
1322 
1323         /**
1324          * Produces a method handle giving read access to a reflected field.
1325          * The type of the method handle will have a return type of the field's
1326          * value type.
1327          * If the field is static, the method handle will take no arguments.
1328          * Otherwise, its single argument will be the instance containing
1329          * the field.
1330          * If the field's {@code accessible} flag is not set,
1331          * access checking is performed immediately on behalf of the lookup class.
1332          * <p>
1333          * If the field is static, and
1334          * if the returned method handle is invoked, the field's class will
1335          * be initialized, if it has not already been initialized.
1336          * @param f the reflected field
1337          * @return a method handle which can load values from the reflected field
1338          * @throws IllegalAccessException if access checking fails
1339          * @throws NullPointerException if the argument is null
1340          */
1341         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
1342             return unreflectField(f, false);
1343         }
1344         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
1345             MemberName field = new MemberName(f, isSetter);
1346             assert(isSetter
1347                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
1348                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
1349             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
1350             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
1351         }
1352 
1353         /**
1354          * Produces a method handle giving write access to a reflected field.
1355          * The type of the method handle will have a void return type.
1356          * If the field is static, the method handle will take a single
1357          * argument, of the field's value type, the value to be stored.
1358          * Otherwise, the two arguments will be the instance containing
1359          * the field, and the value to be stored.
1360          * If the field's {@code accessible} flag is not set,
1361          * access checking is performed immediately on behalf of the lookup class.
1362          * <p>
1363          * If the field is static, and
1364          * if the returned method handle is invoked, the field's class will
1365          * be initialized, if it has not already been initialized.
1366          * @param f the reflected field
1367          * @return a method handle which can store values into the reflected field
1368          * @throws IllegalAccessException if access checking fails
1369          * @throws NullPointerException if the argument is null
1370          */
1371         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
1372             return unreflectField(f, true);
1373         }
1374 
1375         /**
1376          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1377          * created by this lookup object or a similar one.
1378          * Security and access checks are performed to ensure that this lookup object
1379          * is capable of reproducing the target method handle.
1380          * This means that the cracking may fail if target is a direct method handle
1381          * but was created by an unrelated lookup object.
1382          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
1383          * and was created by a lookup object for a different class.
1384          * @param target a direct method handle to crack into symbolic reference components
1385          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
1386          * @exception SecurityException if a security manager is present and it
1387          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1388          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
1389          * @exception NullPointerException if the target is {@code null}
1390          * @see MethodHandleInfo
1391          * @since 1.8
1392          */
1393         public MethodHandleInfo revealDirect(MethodHandle target) {
1394             MemberName member = target.internalMemberName();
1395             if (member == null || (!member.isResolved() && !member.isMethodHandleInvoke()))
1396                 throw newIllegalArgumentException("not a direct method handle");
1397             Class<?> defc = member.getDeclaringClass();
1398             byte refKind = member.getReferenceKind();
1399             assert(MethodHandleNatives.refKindIsValid(refKind));
1400             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
1401                 // Devirtualized method invocation is usually formally virtual.
1402                 // To avoid creating extra MemberName objects for this common case,
1403                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
1404                 refKind = REF_invokeVirtual;
1405             if (refKind == REF_invokeVirtual && defc.isInterface())
1406                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
1407                 refKind = REF_invokeInterface;
1408             // Check SM permissions and member access before cracking.
1409             try {
1410                 checkAccess(refKind, defc, member);
1411                 checkSecurityManager(defc, member);
1412             } catch (IllegalAccessException ex) {
1413                 throw new IllegalArgumentException(ex);
1414             }
1415             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
1416                 Class<?> callerClass = target.internalCallerClass();
1417                 if (!hasPrivateAccess() || callerClass != lookupClass())
1418                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
1419             }
1420             // Produce the handle to the results.
1421             return new InfoFromMemberName(this, member, refKind);
1422         }
1423 
1424         /// Helper methods, all package-private.
1425 
1426         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1427             checkSymbolicClass(refc);  // do this before attempting to resolve
1428             Objects.requireNonNull(name);
1429             Objects.requireNonNull(type);
1430             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1431                                             NoSuchFieldException.class);
1432         }
1433 
1434         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1435             checkSymbolicClass(refc);  // do this before attempting to resolve
1436             Objects.requireNonNull(name);
1437             Objects.requireNonNull(type);
1438             checkMethodName(refKind, name);  // NPE check on name
1439             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1440                                             NoSuchMethodException.class);
1441         }
1442 
1443         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
1444             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
1445             Objects.requireNonNull(member.getName());
1446             Objects.requireNonNull(member.getType());
1447             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
1448                                             ReflectiveOperationException.class);
1449         }
1450 
1451         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
1452             Objects.requireNonNull(refc);
1453             Class<?> caller = lookupClassOrNull();
1454             if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes))
1455                 throw new MemberName(refc).makeAccessException("symbolic reference class is not public", this);
1456         }
1457 
1458         /** Check name for an illegal leading "&lt;" character. */
1459         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
1460             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
1461                 throw new NoSuchMethodException("illegal method name: "+name);
1462         }
1463 
1464 
1465         /**
1466          * Find my trustable caller class if m is a caller sensitive method.
1467          * If this lookup object has private access, then the caller class is the lookupClass.
1468          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
1469          */
1470         Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
1471             Class<?> callerClass = null;
1472             if (MethodHandleNatives.isCallerSensitive(m)) {
1473                 // Only lookups with private access are allowed to resolve caller-sensitive methods
1474                 if (hasPrivateAccess()) {
1475                     callerClass = lookupClass;
1476                 } else {
1477                     throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
1478                 }
1479             }
1480             return callerClass;
1481         }
1482 
1483         private boolean hasPrivateAccess() {
1484             return (allowedModes & PRIVATE) != 0;
1485         }
1486 
1487         /**
1488          * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
1489          * Determines a trustable caller class to compare with refc, the symbolic reference class.
1490          * If this lookup object has private access, then the caller class is the lookupClass.
1491          */
1492         void checkSecurityManager(Class<?> refc, MemberName m) {
1493             SecurityManager smgr = System.getSecurityManager();
1494             if (smgr == null)  return;
1495             if (allowedModes == TRUSTED)  return;
1496 
1497             // Step 1:
1498             boolean fullPowerLookup = hasPrivateAccess();
1499             if (!fullPowerLookup ||
1500                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
1501                 ReflectUtil.checkPackageAccess(refc);
1502             }
1503 
1504             if (m == null) {  // findClass or accessClass
1505                 // Step 2b:
1506                 if (!fullPowerLookup) {
1507                     smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
1508                 }
1509                 return;
1510             }
1511 
1512             // Step 2a:
1513             if (m.isPublic()) return;
1514             if (!fullPowerLookup) {
1515                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
1516             }
1517 
1518             // Step 3:
1519             Class<?> defc = m.getDeclaringClass();
1520             if (!fullPowerLookup && defc != refc) {
1521                 ReflectUtil.checkPackageAccess(defc);
1522             }
1523         }
1524 
1525         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1526             boolean wantStatic = (refKind == REF_invokeStatic);
1527             String message;
1528             if (m.isConstructor())
1529                 message = "expected a method, not a constructor";
1530             else if (!m.isMethod())
1531                 message = "expected a method";
1532             else if (wantStatic != m.isStatic())
1533                 message = wantStatic ? "expected a static method" : "expected a non-static method";
1534             else
1535                 { checkAccess(refKind, refc, m); return; }
1536             throw m.makeAccessException(message, this);
1537         }
1538 
1539         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1540             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
1541             String message;
1542             if (wantStatic != m.isStatic())
1543                 message = wantStatic ? "expected a static field" : "expected a non-static field";
1544             else
1545                 { checkAccess(refKind, refc, m); return; }
1546             throw m.makeAccessException(message, this);
1547         }
1548 
1549         /** Check public/protected/private bits on the symbolic reference class and its member. */
1550         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1551             assert(m.referenceKindIsConsistentWith(refKind) &&
1552                    MethodHandleNatives.refKindIsValid(refKind) &&
1553                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
1554             int allowedModes = this.allowedModes;
1555             if (allowedModes == TRUSTED)  return;
1556             int mods = m.getModifiers();
1557             if (Modifier.isProtected(mods) &&
1558                     refKind == REF_invokeVirtual &&
1559                     m.getDeclaringClass() == Object.class &&
1560                     m.getName().equals("clone") &&
1561                     refc.isArray()) {
1562                 // The JVM does this hack also.
1563                 // (See ClassVerifier::verify_invoke_instructions
1564                 // and LinkResolver::check_method_accessability.)
1565                 // Because the JVM does not allow separate methods on array types,
1566                 // there is no separate method for int[].clone.
1567                 // All arrays simply inherit Object.clone.
1568                 // But for access checking logic, we make Object.clone
1569                 // (normally protected) appear to be public.
1570                 // Later on, when the DirectMethodHandle is created,
1571                 // its leading argument will be restricted to the
1572                 // requested array type.
1573                 // N.B. The return type is not adjusted, because
1574                 // that is *not* the bytecode behavior.
1575                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
1576             }
1577             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
1578                 // cannot "new" a protected ctor in a different package
1579                 mods ^= Modifier.PROTECTED;
1580             }
1581             if (Modifier.isFinal(mods) &&
1582                     MethodHandleNatives.refKindIsSetter(refKind))
1583                 throw m.makeAccessException("unexpected set of a final field", this);
1584             if (Modifier.isPublic(mods) && Modifier.isPublic(refc.getModifiers()) && allowedModes != 0)
1585                 return;  // common case
1586             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
1587             if ((requestedModes & allowedModes) != 0) {
1588                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
1589                                                     mods, lookupClass(), allowedModes))
1590                     return;
1591             } else {
1592                 // Protected members can also be checked as if they were package-private.
1593                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
1594                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
1595                     return;
1596             }
1597             throw m.makeAccessException(accessFailedMessage(refc, m), this);
1598         }
1599 
1600         String accessFailedMessage(Class<?> refc, MemberName m) {
1601             Class<?> defc = m.getDeclaringClass();
1602             int mods = m.getModifiers();
1603             // check the class first:
1604             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
1605                                (defc == refc ||
1606                                 Modifier.isPublic(refc.getModifiers())));
1607             if (!classOK && (allowedModes & PACKAGE) != 0) {
1608                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
1609                            (defc == refc ||
1610                             VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
1611             }
1612             if (!classOK)
1613                 return "class is not public";
1614             if (Modifier.isPublic(mods))
1615                 return "access to public member failed";  // (how?)
1616             if (Modifier.isPrivate(mods))
1617                 return "member is private";
1618             if (Modifier.isProtected(mods))
1619                 return "member is protected";
1620             return "member is private to package";
1621         }
1622 
1623         private static final boolean ALLOW_NESTMATE_ACCESS = false;
1624 
1625         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
1626             int allowedModes = this.allowedModes;
1627             if (allowedModes == TRUSTED)  return;
1628             if (!hasPrivateAccess()
1629                 || (specialCaller != lookupClass()
1630                        // ensure non-abstract methods in superinterfaces can be special-invoked
1631                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))
1632                     && !(ALLOW_NESTMATE_ACCESS &&
1633                          VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
1634                 throw new MemberName(specialCaller).
1635                     makeAccessException("no private access for invokespecial", this);
1636         }
1637 
1638         private boolean restrictProtectedReceiver(MemberName method) {
1639             // The accessing class only has the right to use a protected member
1640             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
1641             if (!method.isProtected() || method.isStatic()
1642                 || allowedModes == TRUSTED
1643                 || method.getDeclaringClass() == lookupClass()
1644                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
1645                 || (ALLOW_NESTMATE_ACCESS &&
1646                     VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass())))
1647                 return false;
1648             return true;
1649         }
1650         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
1651             assert(!method.isStatic());
1652             // receiver type of mh is too wide; narrow to caller
1653             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
1654                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
1655             }
1656             MethodType rawType = mh.type();
1657             if (rawType.parameterType(0) == caller)  return mh;
1658             MethodType narrowType = rawType.changeParameterType(0, caller);
1659             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
1660             assert(mh.viewAsTypeChecks(narrowType, true));
1661             return mh.copyWith(narrowType, mh.form);
1662         }
1663 
1664         /** Check access and get the requested method. */
1665         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1666             final boolean doRestrict    = true;
1667             final boolean checkSecurity = true;
1668             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1669         }
1670         /** Check access and get the requested method, eliding receiver narrowing rules. */
1671         private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1672             final boolean doRestrict    = false;
1673             final boolean checkSecurity = true;
1674             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1675         }
1676         /** Check access and get the requested method, eliding security manager checks. */
1677         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1678             final boolean doRestrict    = true;
1679             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
1680             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1681         }
1682         /** Common code for all methods; do not call directly except from immediately above. */
1683         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
1684                                                    boolean checkSecurity,
1685                                                    boolean doRestrict, Class<?> callerClass) throws IllegalAccessException {
1686             checkMethod(refKind, refc, method);
1687             // Optionally check with the security manager; this isn't needed for unreflect* calls.
1688             if (checkSecurity)
1689                 checkSecurityManager(refc, method);
1690             assert(!method.isMethodHandleInvoke());
1691 
1692             if (refKind == REF_invokeSpecial &&
1693                 refc != lookupClass() &&
1694                 !refc.isInterface() &&
1695                 refc != lookupClass().getSuperclass() &&
1696                 refc.isAssignableFrom(lookupClass())) {
1697                 assert(!method.getName().equals("<init>"));  // not this code path
1698                 // Per JVMS 6.5, desc. of invokespecial instruction:
1699                 // If the method is in a superclass of the LC,
1700                 // and if our original search was above LC.super,
1701                 // repeat the search (symbolic lookup) from LC.super
1702                 // and continue with the direct superclass of that class,
1703                 // and so forth, until a match is found or no further superclasses exist.
1704                 // FIXME: MemberName.resolve should handle this instead.
1705                 Class<?> refcAsSuper = lookupClass();
1706                 MemberName m2;
1707                 do {
1708                     refcAsSuper = refcAsSuper.getSuperclass();
1709                     m2 = new MemberName(refcAsSuper,
1710                                         method.getName(),
1711                                         method.getMethodType(),
1712                                         REF_invokeSpecial);
1713                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
1714                 } while (m2 == null &&         // no method is found yet
1715                          refc != refcAsSuper); // search up to refc
1716                 if (m2 == null)  throw new InternalError(method.toString());
1717                 method = m2;
1718                 refc = refcAsSuper;
1719                 // redo basic checks
1720                 checkMethod(refKind, refc, method);
1721             }
1722 
1723             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method);
1724             MethodHandle mh = dmh;
1725             // Optionally narrow the receiver argument to refc using restrictReceiver.
1726             if (doRestrict &&
1727                    (refKind == REF_invokeSpecial ||
1728                        (MethodHandleNatives.refKindHasReceiver(refKind) &&
1729                            restrictProtectedReceiver(method)))) {
1730                 mh = restrictReceiver(method, dmh, lookupClass());
1731             }
1732             mh = maybeBindCaller(method, mh, callerClass);
1733             mh = mh.setVarargs(method);
1734             return mh;
1735         }
1736         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
1737                                              Class<?> callerClass)
1738                                              throws IllegalAccessException {
1739             if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
1740                 return mh;
1741             Class<?> hostClass = lookupClass;
1742             if (!hasPrivateAccess())  // caller must have private access
1743                 hostClass = callerClass;  // callerClass came from a security manager style stack walk
1744             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
1745             // Note: caller will apply varargs after this step happens.
1746             return cbmh;
1747         }
1748         /** Check access and get the requested field. */
1749         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
1750             final boolean checkSecurity = true;
1751             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
1752         }
1753         /** Check access and get the requested field, eliding security manager checks. */
1754         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
1755             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
1756             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
1757         }
1758         /** Common code for all fields; do not call directly except from immediately above. */
1759         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
1760                                                   boolean checkSecurity) throws IllegalAccessException {
1761             checkField(refKind, refc, field);
1762             // Optionally check with the security manager; this isn't needed for unreflect* calls.
1763             if (checkSecurity)
1764                 checkSecurityManager(refc, field);
1765             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
1766             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
1767                                     restrictProtectedReceiver(field));
1768             if (doRestrict)
1769                 return restrictReceiver(field, dmh, lookupClass());
1770             return dmh;
1771         }
1772         /** Check access and get the requested constructor. */
1773         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
1774             final boolean checkSecurity = true;
1775             return getDirectConstructorCommon(refc, ctor, checkSecurity);
1776         }
1777         /** Check access and get the requested constructor, eliding security manager checks. */
1778         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
1779             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
1780             return getDirectConstructorCommon(refc, ctor, checkSecurity);
1781         }
1782         /** Common code for all constructors; do not call directly except from immediately above. */
1783         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
1784                                                   boolean checkSecurity) throws IllegalAccessException {
1785             assert(ctor.isConstructor());
1786             checkAccess(REF_newInvokeSpecial, refc, ctor);
1787             // Optionally check with the security manager; this isn't needed for unreflect* calls.
1788             if (checkSecurity)
1789                 checkSecurityManager(refc, ctor);
1790             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
1791             return DirectMethodHandle.make(ctor).setVarargs(ctor);
1792         }
1793 
1794         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
1795          */
1796         /*non-public*/
1797         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException {
1798             if (!(type instanceof Class || type instanceof MethodType))
1799                 throw new InternalError("unresolved MemberName");
1800             MemberName member = new MemberName(refKind, defc, name, type);
1801             MethodHandle mh = LOOKASIDE_TABLE.get(member);
1802             if (mh != null) {
1803                 checkSymbolicClass(defc);
1804                 return mh;
1805             }
1806             // Treat MethodHandle.invoke and invokeExact specially.
1807             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
1808                 mh = findVirtualForMH(member.getName(), member.getMethodType());
1809                 if (mh != null) {
1810                     return mh;
1811                 }
1812             }
1813             MemberName resolved = resolveOrFail(refKind, member);
1814             mh = getDirectMethodForConstant(refKind, defc, resolved);
1815             if (mh instanceof DirectMethodHandle
1816                     && canBeCached(refKind, defc, resolved)) {
1817                 MemberName key = mh.internalMemberName();
1818                 if (key != null) {
1819                     key = key.asNormalOriginal();
1820                 }
1821                 if (member.equals(key)) {  // better safe than sorry
1822                     LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
1823                 }
1824             }
1825             return mh;
1826         }
1827         private
1828         boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
1829             if (refKind == REF_invokeSpecial) {
1830                 return false;
1831             }
1832             if (!Modifier.isPublic(defc.getModifiers()) ||
1833                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
1834                     !member.isPublic() ||
1835                     member.isCallerSensitive()) {
1836                 return false;
1837             }
1838             ClassLoader loader = defc.getClassLoader();
1839             if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) {
1840                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
1841                 boolean found = false;
1842                 while (sysl != null) {
1843                     if (loader == sysl) { found = true; break; }
1844                     sysl = sysl.getParent();
1845                 }
1846                 if (!found) {
1847                     return false;
1848                 }
1849             }
1850             try {
1851                 MemberName resolved2 = publicLookup().resolveOrFail(refKind,
1852                     new MemberName(refKind, defc, member.getName(), member.getType()));
1853                 checkSecurityManager(defc, resolved2);
1854             } catch (ReflectiveOperationException | SecurityException ex) {
1855                 return false;
1856             }
1857             return true;
1858         }
1859         private
1860         MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
1861                 throws ReflectiveOperationException {
1862             if (MethodHandleNatives.refKindIsField(refKind)) {
1863                 return getDirectFieldNoSecurityManager(refKind, defc, member);
1864             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
1865                 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
1866             } else if (refKind == REF_newInvokeSpecial) {
1867                 return getDirectConstructorNoSecurityManager(defc, member);
1868             }
1869             // oops
1870             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
1871         }
1872 
1873         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
1874     }
1875 
1876     /**
1877      * Produces a method handle giving read access to elements of an array.
1878      * The type of the method handle will have a return type of the array's
1879      * element type.  Its first argument will be the array type,
1880      * and the second will be {@code int}.
1881      * @param arrayClass an array type
1882      * @return a method handle which can load values from the given array type
1883      * @throws NullPointerException if the argument is null
1884      * @throws  IllegalArgumentException if arrayClass is not an array type
1885      */
1886     public static
1887     MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
1888         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false);
1889     }
1890 
1891     /**
1892      * Produces a method handle giving write access to elements of an array.
1893      * The type of the method handle will have a void return type.
1894      * Its last argument will be the array's element type.
1895      * The first and second arguments will be the array type and int.
1896      * @param arrayClass the class of an array
1897      * @return a method handle which can store values into the array type
1898      * @throws NullPointerException if the argument is null
1899      * @throws IllegalArgumentException if arrayClass is not an array type
1900      */
1901     public static
1902     MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
1903         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true);
1904     }
1905 
1906     /// method handle invocation (reflective style)
1907 
1908     /**
1909      * Produces a method handle which will invoke any method handle of the
1910      * given {@code type}, with a given number of trailing arguments replaced by
1911      * a single trailing {@code Object[]} array.
1912      * The resulting invoker will be a method handle with the following
1913      * arguments:
1914      * <ul>
1915      * <li>a single {@code MethodHandle} target
1916      * <li>zero or more leading values (counted by {@code leadingArgCount})
1917      * <li>an {@code Object[]} array containing trailing arguments
1918      * </ul>
1919      * <p>
1920      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
1921      * the indicated {@code type}.
1922      * That is, if the target is exactly of the given {@code type}, it will behave
1923      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
1924      * is used to convert the target to the required {@code type}.
1925      * <p>
1926      * The type of the returned invoker will not be the given {@code type}, but rather
1927      * will have all parameters except the first {@code leadingArgCount}
1928      * replaced by a single array of type {@code Object[]}, which will be
1929      * the final parameter.
1930      * <p>
1931      * Before invoking its target, the invoker will spread the final array, apply
1932      * reference casts as necessary, and unbox and widen primitive arguments.
1933      * If, when the invoker is called, the supplied array argument does
1934      * not have the correct number of elements, the invoker will throw
1935      * an {@link IllegalArgumentException} instead of invoking the target.
1936      * <p>
1937      * This method is equivalent to the following code (though it may be more efficient):
1938      * <blockquote><pre>{@code
1939 MethodHandle invoker = MethodHandles.invoker(type);
1940 int spreadArgCount = type.parameterCount() - leadingArgCount;
1941 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
1942 return invoker;
1943      * }</pre></blockquote>
1944      * This method throws no reflective or security exceptions.
1945      * @param type the desired target type
1946      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
1947      * @return a method handle suitable for invoking any method handle of the given type
1948      * @throws NullPointerException if {@code type} is null
1949      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
1950      *                  the range from 0 to {@code type.parameterCount()} inclusive,
1951      *                  or if the resulting method handle's type would have
1952      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
1953      */
1954     public static
1955     MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
1956         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
1957             throw newIllegalArgumentException("bad argument count", leadingArgCount);
1958         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
1959         return type.invokers().spreadInvoker(leadingArgCount);
1960     }
1961 
1962     /**
1963      * Produces a special <em>invoker method handle</em> which can be used to
1964      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
1965      * The resulting invoker will have a type which is
1966      * exactly equal to the desired type, except that it will accept
1967      * an additional leading argument of type {@code MethodHandle}.
1968      * <p>
1969      * This method is equivalent to the following code (though it may be more efficient):
1970      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
1971      *
1972      * <p style="font-size:smaller;">
1973      * <em>Discussion:</em>
1974      * Invoker method handles can be useful when working with variable method handles
1975      * of unknown types.
1976      * For example, to emulate an {@code invokeExact} call to a variable method
1977      * handle {@code M}, extract its type {@code T},
1978      * look up the invoker method {@code X} for {@code T},
1979      * and call the invoker method, as {@code X.invoke(T, A...)}.
1980      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
1981      * is unknown.)
1982      * If spreading, collecting, or other argument transformations are required,
1983      * they can be applied once to the invoker {@code X} and reused on many {@code M}
1984      * method handle values, as long as they are compatible with the type of {@code X}.
1985      * <p style="font-size:smaller;">
1986      * <em>(Note:  The invoker method is not available via the Core Reflection API.
1987      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
1988      * on the declared {@code invokeExact} or {@code invoke} method will raise an
1989      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
1990      * <p>
1991      * This method throws no reflective or security exceptions.
1992      * @param type the desired target type
1993      * @return a method handle suitable for invoking any method handle of the given type
1994      * @throws IllegalArgumentException if the resulting method handle's type would have
1995      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
1996      */
1997     public static
1998     MethodHandle exactInvoker(MethodType type) {
1999         return type.invokers().exactInvoker();
2000     }
2001 
2002     /**
2003      * Produces a special <em>invoker method handle</em> which can be used to
2004      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
2005      * The resulting invoker will have a type which is
2006      * exactly equal to the desired type, except that it will accept
2007      * an additional leading argument of type {@code MethodHandle}.
2008      * <p>
2009      * Before invoking its target, if the target differs from the expected type,
2010      * the invoker will apply reference casts as
2011      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
2012      * Similarly, the return value will be converted as necessary.
2013      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
2014      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
2015      * <p>
2016      * This method is equivalent to the following code (though it may be more efficient):
2017      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
2018      * <p style="font-size:smaller;">
2019      * <em>Discussion:</em>
2020      * A {@linkplain MethodType#genericMethodType general method type} is one which
2021      * mentions only {@code Object} arguments and return values.
2022      * An invoker for such a type is capable of calling any method handle
2023      * of the same arity as the general type.
2024      * <p style="font-size:smaller;">
2025      * <em>(Note:  The invoker method is not available via the Core Reflection API.
2026      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
2027      * on the declared {@code invokeExact} or {@code invoke} method will raise an
2028      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
2029      * <p>
2030      * This method throws no reflective or security exceptions.
2031      * @param type the desired target type
2032      * @return a method handle suitable for invoking any method handle convertible to the given type
2033      * @throws IllegalArgumentException if the resulting method handle's type would have
2034      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2035      */
2036     public static
2037     MethodHandle invoker(MethodType type) {
2038         return type.invokers().genericInvoker();
2039     }
2040 
2041     static /*non-public*/
2042     MethodHandle basicInvoker(MethodType type) {
2043         return type.invokers().basicInvoker();
2044     }
2045 
2046      /// method handle modification (creation from other method handles)
2047 
2048     /**
2049      * Produces a method handle which adapts the type of the
2050      * given method handle to a new type by pairwise argument and return type conversion.
2051      * The original type and new type must have the same number of arguments.
2052      * The resulting method handle is guaranteed to report a type
2053      * which is equal to the desired new type.
2054      * <p>
2055      * If the original type and new type are equal, returns target.
2056      * <p>
2057      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
2058      * and some additional conversions are also applied if those conversions fail.
2059      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
2060      * if possible, before or instead of any conversions done by {@code asType}:
2061      * <ul>
2062      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
2063      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
2064      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
2065      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
2066      *     the boolean is converted to a byte value, 1 for true, 0 for false.
2067      *     (This treatment follows the usage of the bytecode verifier.)
2068      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
2069      *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
2070      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
2071      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
2072      *     then a Java casting conversion (JLS 5.5) is applied.
2073      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
2074      *     widening and/or narrowing.)
2075      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
2076      *     conversion will be applied at runtime, possibly followed
2077      *     by a Java casting conversion (JLS 5.5) on the primitive value,
2078      *     possibly followed by a conversion from byte to boolean by testing
2079      *     the low-order bit.
2080      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
2081      *     and if the reference is null at runtime, a zero value is introduced.
2082      * </ul>
2083      * @param target the method handle to invoke after arguments are retyped
2084      * @param newType the expected type of the new method handle
2085      * @return a method handle which delegates to the target after performing
2086      *           any necessary argument conversions, and arranges for any
2087      *           necessary return value conversions
2088      * @throws NullPointerException if either argument is null
2089      * @throws WrongMethodTypeException if the conversion cannot be made
2090      * @see MethodHandle#asType
2091      */
2092     public static
2093     MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
2094         explicitCastArgumentsChecks(target, newType);
2095         // use the asTypeCache when possible:
2096         MethodType oldType = target.type();
2097         if (oldType == newType)  return target;
2098         if (oldType.explicitCastEquivalentToAsType(newType)) {
2099             return target.asFixedArity().asType(newType);
2100         }
2101         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
2102     }
2103 
2104     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
2105         if (target.type().parameterCount() != newType.parameterCount()) {
2106             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
2107         }
2108     }
2109 
2110     /**
2111      * Produces a method handle which adapts the calling sequence of the
2112      * given method handle to a new type, by reordering the arguments.
2113      * The resulting method handle is guaranteed to report a type
2114      * which is equal to the desired new type.
2115      * <p>
2116      * The given array controls the reordering.
2117      * Call {@code #I} the number of incoming parameters (the value
2118      * {@code newType.parameterCount()}, and call {@code #O} the number
2119      * of outgoing parameters (the value {@code target.type().parameterCount()}).
2120      * Then the length of the reordering array must be {@code #O},
2121      * and each element must be a non-negative number less than {@code #I}.
2122      * For every {@code N} less than {@code #O}, the {@code N}-th
2123      * outgoing argument will be taken from the {@code I}-th incoming
2124      * argument, where {@code I} is {@code reorder[N]}.
2125      * <p>
2126      * No argument or return value conversions are applied.
2127      * The type of each incoming argument, as determined by {@code newType},
2128      * must be identical to the type of the corresponding outgoing parameter
2129      * or parameters in the target method handle.
2130      * The return type of {@code newType} must be identical to the return
2131      * type of the original target.
2132      * <p>
2133      * The reordering array need not specify an actual permutation.
2134      * An incoming argument will be duplicated if its index appears
2135      * more than once in the array, and an incoming argument will be dropped
2136      * if its index does not appear in the array.
2137      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
2138      * incoming arguments which are not mentioned in the reordering array
2139      * are may be any type, as determined only by {@code newType}.
2140      * <blockquote><pre>{@code
2141 import static java.lang.invoke.MethodHandles.*;
2142 import static java.lang.invoke.MethodType.*;
2143 ...
2144 MethodType intfn1 = methodType(int.class, int.class);
2145 MethodType intfn2 = methodType(int.class, int.class, int.class);
2146 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
2147 assert(sub.type().equals(intfn2));
2148 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
2149 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
2150 assert((int)rsub.invokeExact(1, 100) == 99);
2151 MethodHandle add = ... (int x, int y) -> (x+y) ...;
2152 assert(add.type().equals(intfn2));
2153 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
2154 assert(twice.type().equals(intfn1));
2155 assert((int)twice.invokeExact(21) == 42);
2156      * }</pre></blockquote>
2157      * @param target the method handle to invoke after arguments are reordered
2158      * @param newType the expected type of the new method handle
2159      * @param reorder an index array which controls the reordering
2160      * @return a method handle which delegates to the target after it
2161      *           drops unused arguments and moves and/or duplicates the other arguments
2162      * @throws NullPointerException if any argument is null
2163      * @throws IllegalArgumentException if the index array length is not equal to
2164      *                  the arity of the target, or if any index array element
2165      *                  not a valid index for a parameter of {@code newType},
2166      *                  or if two corresponding parameter types in
2167      *                  {@code target.type()} and {@code newType} are not identical,
2168      */
2169     public static
2170     MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
2171         reorder = reorder.clone();  // get a private copy
2172         MethodType oldType = target.type();
2173         permuteArgumentChecks(reorder, newType, oldType);
2174         // first detect dropped arguments and handle them separately
2175         int[] originalReorder = reorder;
2176         BoundMethodHandle result = target.rebind();
2177         LambdaForm form = result.form;
2178         int newArity = newType.parameterCount();
2179         // Normalize the reordering into a real permutation,
2180         // by removing duplicates and adding dropped elements.
2181         // This somewhat improves lambda form caching, as well
2182         // as simplifying the transform by breaking it up into steps.
2183         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
2184             if (ddIdx > 0) {
2185                 // We found a duplicated entry at reorder[ddIdx].
2186                 // Example:  (x,y,z)->asList(x,y,z)
2187                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
2188                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
2189                 // The starred element corresponds to the argument
2190                 // deleted by the dupArgumentForm transform.
2191                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
2192                 boolean killFirst = false;
2193                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
2194                     // Set killFirst if the dup is larger than an intervening position.
2195                     // This will remove at least one inversion from the permutation.
2196                     if (dupVal > val) killFirst = true;
2197                 }
2198                 if (!killFirst) {
2199                     srcPos = dstPos;
2200                     dstPos = ddIdx;
2201                 }
2202                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
2203                 assert (reorder[srcPos] == reorder[dstPos]);
2204                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
2205                 // contract the reordering by removing the element at dstPos
2206                 int tailPos = dstPos + 1;
2207                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
2208                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
2209             } else {
2210                 int dropVal = ~ddIdx, insPos = 0;
2211                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
2212                     // Find first element of reorder larger than dropVal.
2213                     // This is where we will insert the dropVal.
2214                     insPos += 1;
2215                 }
2216                 Class<?> ptype = newType.parameterType(dropVal);
2217                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
2218                 oldType = oldType.insertParameterTypes(insPos, ptype);
2219                 // expand the reordering by inserting an element at insPos
2220                 int tailPos = insPos + 1;
2221                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
2222                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
2223                 reorder[insPos] = dropVal;
2224             }
2225             assert (permuteArgumentChecks(reorder, newType, oldType));
2226         }
2227         assert (reorder.length == newArity);  // a perfect permutation
2228         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
2229         form = form.editor().permuteArgumentsForm(1, reorder);
2230         if (newType == result.type() && form == result.internalForm())
2231             return result;
2232         return result.copyWith(newType, form);
2233     }
2234 
2235     /**
2236      * Return an indication of any duplicate or omission in reorder.
2237      * If the reorder contains a duplicate entry, return the index of the second occurrence.
2238      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
2239      * Otherwise, return zero.
2240      * If an element not in [0..newArity-1] is encountered, return reorder.length.
2241      */
2242     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
2243         final int BIT_LIMIT = 63;  // max number of bits in bit mask
2244         if (newArity < BIT_LIMIT) {
2245             long mask = 0;
2246             for (int i = 0; i < reorder.length; i++) {
2247                 int arg = reorder[i];
2248                 if (arg >= newArity) {
2249                     return reorder.length;
2250                 }
2251                 long bit = 1L << arg;
2252                 if ((mask & bit) != 0) {
2253                     return i;  // >0 indicates a dup
2254                 }
2255                 mask |= bit;
2256             }
2257             if (mask == (1L << newArity) - 1) {
2258                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
2259                 return 0;
2260             }
2261             // find first zero
2262             long zeroBit = Long.lowestOneBit(~mask);
2263             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
2264             assert(zeroPos <= newArity);
2265             if (zeroPos == newArity) {
2266                 return 0;
2267             }
2268             return ~zeroPos;
2269         } else {
2270             // same algorithm, different bit set
2271             BitSet mask = new BitSet(newArity);
2272             for (int i = 0; i < reorder.length; i++) {
2273                 int arg = reorder[i];
2274                 if (arg >= newArity) {
2275                     return reorder.length;
2276                 }
2277                 if (mask.get(arg)) {
2278                     return i;  // >0 indicates a dup
2279                 }
2280                 mask.set(arg);
2281             }
2282             int zeroPos = mask.nextClearBit(0);
2283             assert(zeroPos <= newArity);
2284             if (zeroPos == newArity) {
2285                 return 0;
2286             }
2287             return ~zeroPos;
2288         }
2289     }
2290 
2291     private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
2292         if (newType.returnType() != oldType.returnType())
2293             throw newIllegalArgumentException("return types do not match",
2294                     oldType, newType);
2295         if (reorder.length == oldType.parameterCount()) {
2296             int limit = newType.parameterCount();
2297             boolean bad = false;
2298             for (int j = 0; j < reorder.length; j++) {
2299                 int i = reorder[j];
2300                 if (i < 0 || i >= limit) {
2301                     bad = true; break;
2302                 }
2303                 Class<?> src = newType.parameterType(i);
2304                 Class<?> dst = oldType.parameterType(j);
2305                 if (src != dst)
2306                     throw newIllegalArgumentException("parameter types do not match after reorder",
2307                             oldType, newType);
2308             }
2309             if (!bad)  return true;
2310         }
2311         throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
2312     }
2313 
2314     /**
2315      * Produces a method handle of the requested return type which returns the given
2316      * constant value every time it is invoked.
2317      * <p>
2318      * Before the method handle is returned, the passed-in value is converted to the requested type.
2319      * If the requested type is primitive, widening primitive conversions are attempted,
2320      * else reference conversions are attempted.
2321      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
2322      * @param type the return type of the desired method handle
2323      * @param value the value to return
2324      * @return a method handle of the given return type and no arguments, which always returns the given value
2325      * @throws NullPointerException if the {@code type} argument is null
2326      * @throws ClassCastException if the value cannot be converted to the required return type
2327      * @throws IllegalArgumentException if the given type is {@code void.class}
2328      */
2329     public static
2330     MethodHandle constant(Class<?> type, Object value) {
2331         if (type.isPrimitive()) {
2332             if (type == void.class)
2333                 throw newIllegalArgumentException("void type");
2334             Wrapper w = Wrapper.forPrimitiveType(type);
2335             value = w.convert(value, type);
2336             if (w.zero().equals(value))
2337                 return zero(w, type);
2338             return insertArguments(identity(type), 0, value);
2339         } else {
2340             if (value == null)
2341                 return zero(Wrapper.OBJECT, type);
2342             return identity(type).bindTo(value);
2343         }
2344     }
2345 
2346     /**
2347      * Produces a method handle which returns its sole argument when invoked.
2348      * @param type the type of the sole parameter and return value of the desired method handle
2349      * @return a unary method handle which accepts and returns the given type
2350      * @throws NullPointerException if the argument is null
2351      * @throws IllegalArgumentException if the given type is {@code void.class}
2352      */
2353     public static
2354     MethodHandle identity(Class<?> type) {
2355         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
2356         int pos = btw.ordinal();
2357         MethodHandle ident = IDENTITY_MHS[pos];
2358         if (ident == null) {
2359             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
2360         }
2361         if (ident.type().returnType() == type)
2362             return ident;
2363         // something like identity(Foo.class); do not bother to intern these
2364         assert(btw == Wrapper.OBJECT);
2365         return makeIdentity(type);
2366     }
2367     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.values().length];
2368     private static MethodHandle makeIdentity(Class<?> ptype) {
2369         MethodType mtype = MethodType.methodType(ptype, ptype);
2370         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
2371         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
2372     }
2373 
2374     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
2375         int pos = btw.ordinal();
2376         MethodHandle zero = ZERO_MHS[pos];
2377         if (zero == null) {
2378             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
2379         }
2380         if (zero.type().returnType() == rtype)
2381             return zero;
2382         assert(btw == Wrapper.OBJECT);
2383         return makeZero(rtype);
2384     }
2385     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.values().length];
2386     private static MethodHandle makeZero(Class<?> rtype) {
2387         MethodType mtype = MethodType.methodType(rtype);
2388         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
2389         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
2390     }
2391 
2392     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
2393         // Simulate a CAS, to avoid racy duplication of results.
2394         MethodHandle prev = cache[pos];
2395         if (prev != null) return prev;
2396         return cache[pos] = value;
2397     }
2398 
2399     /**
2400      * Provides a target method handle with one or more <em>bound arguments</em>
2401      * in advance of the method handle's invocation.
2402      * The formal parameters to the target corresponding to the bound
2403      * arguments are called <em>bound parameters</em>.
2404      * Returns a new method handle which saves away the bound arguments.
2405      * When it is invoked, it receives arguments for any non-bound parameters,
2406      * binds the saved arguments to their corresponding parameters,
2407      * and calls the original target.
2408      * <p>
2409      * The type of the new method handle will drop the types for the bound
2410      * parameters from the original target type, since the new method handle
2411      * will no longer require those arguments to be supplied by its callers.
2412      * <p>
2413      * Each given argument object must match the corresponding bound parameter type.
2414      * If a bound parameter type is a primitive, the argument object
2415      * must be a wrapper, and will be unboxed to produce the primitive value.
2416      * <p>
2417      * The {@code pos} argument selects which parameters are to be bound.
2418      * It may range between zero and <i>N-L</i> (inclusively),
2419      * where <i>N</i> is the arity of the target method handle
2420      * and <i>L</i> is the length of the values array.
2421      * @param target the method handle to invoke after the argument is inserted
2422      * @param pos where to insert the argument (zero for the first)
2423      * @param values the series of arguments to insert
2424      * @return a method handle which inserts an additional argument,
2425      *         before calling the original method handle
2426      * @throws NullPointerException if the target or the {@code values} array is null
2427      * @see MethodHandle#bindTo
2428      */
2429     public static
2430     MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
2431         int insCount = values.length;
2432         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
2433         if (insCount == 0)  return target;
2434         BoundMethodHandle result = target.rebind();
2435         for (int i = 0; i < insCount; i++) {
2436             Object value = values[i];
2437             Class<?> ptype = ptypes[pos+i];
2438             if (ptype.isPrimitive()) {
2439                 result = insertArgumentPrimitive(result, pos, ptype, value);
2440             } else {
2441                 value = ptype.cast(value);  // throw CCE if needed
2442                 result = result.bindArgumentL(pos, value);
2443             }
2444         }
2445         return result;
2446     }
2447 
2448     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
2449                                                              Class<?> ptype, Object value) {
2450         Wrapper w = Wrapper.forPrimitiveType(ptype);
2451         // perform unboxing and/or primitive conversion
2452         value = w.convert(value, ptype);
2453         switch (w) {
2454         case INT:     return result.bindArgumentI(pos, (int)value);
2455         case LONG:    return result.bindArgumentJ(pos, (long)value);
2456         case FLOAT:   return result.bindArgumentF(pos, (float)value);
2457         case DOUBLE:  return result.bindArgumentD(pos, (double)value);
2458         default:      return result.bindArgumentI(pos, ValueConversions.widenSubword(value));
2459         }
2460     }
2461 
2462     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
2463         MethodType oldType = target.type();
2464         int outargs = oldType.parameterCount();
2465         int inargs  = outargs - insCount;
2466         if (inargs < 0)
2467             throw newIllegalArgumentException("too many values to insert");
2468         if (pos < 0 || pos > inargs)
2469             throw newIllegalArgumentException("no argument type to append");
2470         return oldType.ptypes();
2471     }
2472 
2473     /**
2474      * Produces a method handle which will discard some dummy arguments
2475      * before calling some other specified <i>target</i> method handle.
2476      * The type of the new method handle will be the same as the target's type,
2477      * except it will also include the dummy argument types,
2478      * at some given position.
2479      * <p>
2480      * The {@code pos} argument may range between zero and <i>N</i>,
2481      * where <i>N</i> is the arity of the target.
2482      * If {@code pos} is zero, the dummy arguments will precede
2483      * the target's real arguments; if {@code pos} is <i>N</i>
2484      * they will come after.
2485      * <p>
2486      * <b>Example:</b>
2487      * <blockquote><pre>{@code
2488 import static java.lang.invoke.MethodHandles.*;
2489 import static java.lang.invoke.MethodType.*;
2490 ...
2491 MethodHandle cat = lookup().findVirtual(String.class,
2492   "concat", methodType(String.class, String.class));
2493 assertEquals("xy", (String) cat.invokeExact("x", "y"));
2494 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
2495 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
2496 assertEquals(bigType, d0.type());
2497 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
2498      * }</pre></blockquote>
2499      * <p>
2500      * This method is also equivalent to the following code:
2501      * <blockquote><pre>
2502      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
2503      * </pre></blockquote>
2504      * @param target the method handle to invoke after the arguments are dropped
2505      * @param valueTypes the type(s) of the argument(s) to drop
2506      * @param pos position of first argument to drop (zero for the leftmost)
2507      * @return a method handle which drops arguments of the given types,
2508      *         before calling the original method handle
2509      * @throws NullPointerException if the target is null,
2510      *                              or if the {@code valueTypes} list or any of its elements is null
2511      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
2512      *                  or if {@code pos} is negative or greater than the arity of the target,
2513      *                  or if the new method handle's type would have too many parameters
2514      */
2515     public static
2516     MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
2517         MethodType oldType = target.type();  // get NPE
2518         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
2519         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
2520         if (dropped == 0)  return target;
2521         BoundMethodHandle result = target.rebind();
2522         LambdaForm lform = result.form;
2523         int insertFormArg = 1 + pos;
2524         for (Class<?> ptype : valueTypes) {
2525             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
2526         }
2527         result = result.copyWith(newType, lform);
2528         return result;
2529     }
2530 
2531     private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
2532         int dropped = valueTypes.size();
2533         MethodType.checkSlotCount(dropped);
2534         int outargs = oldType.parameterCount();
2535         int inargs  = outargs + dropped;
2536         if (pos < 0 || pos > outargs)
2537             throw newIllegalArgumentException("no argument type to remove"
2538                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
2539                     );
2540         return dropped;
2541     }
2542 
2543     /**
2544      * Produces a method handle which will discard some dummy arguments
2545      * before calling some other specified <i>target</i> method handle.
2546      * The type of the new method handle will be the same as the target's type,
2547      * except it will also include the dummy argument types,
2548      * at some given position.
2549      * <p>
2550      * The {@code pos} argument may range between zero and <i>N</i>,
2551      * where <i>N</i> is the arity of the target.
2552      * If {@code pos} is zero, the dummy arguments will precede
2553      * the target's real arguments; if {@code pos} is <i>N</i>
2554      * they will come after.
2555      * <p>
2556      * <b>Example:</b>
2557      * <blockquote><pre>{@code
2558 import static java.lang.invoke.MethodHandles.*;
2559 import static java.lang.invoke.MethodType.*;
2560 ...
2561 MethodHandle cat = lookup().findVirtual(String.class,
2562   "concat", methodType(String.class, String.class));
2563 assertEquals("xy", (String) cat.invokeExact("x", "y"));
2564 MethodHandle d0 = dropArguments(cat, 0, String.class);
2565 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
2566 MethodHandle d1 = dropArguments(cat, 1, String.class);
2567 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
2568 MethodHandle d2 = dropArguments(cat, 2, String.class);
2569 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
2570 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
2571 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
2572      * }</pre></blockquote>
2573      * <p>
2574      * This method is also equivalent to the following code:
2575      * <blockquote><pre>
2576      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
2577      * </pre></blockquote>
2578      * @param target the method handle to invoke after the arguments are dropped
2579      * @param valueTypes the type(s) of the argument(s) to drop
2580      * @param pos position of first argument to drop (zero for the leftmost)
2581      * @return a method handle which drops arguments of the given types,
2582      *         before calling the original method handle
2583      * @throws NullPointerException if the target is null,
2584      *                              or if the {@code valueTypes} array or any of its elements is null
2585      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
2586      *                  or if {@code pos} is negative or greater than the arity of the target,
2587      *                  or if the new method handle's type would have
2588      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
2589      */
2590     public static
2591     MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
2592         return dropArguments(target, pos, Arrays.asList(valueTypes));
2593     }
2594 
2595     /**
2596      * Adapts a target method handle by pre-processing
2597      * one or more of its arguments, each with its own unary filter function,
2598      * and then calling the target with each pre-processed argument
2599      * replaced by the result of its corresponding filter function.
2600      * <p>
2601      * The pre-processing is performed by one or more method handles,
2602      * specified in the elements of the {@code filters} array.
2603      * The first element of the filter array corresponds to the {@code pos}
2604      * argument of the target, and so on in sequence.
2605      * <p>
2606      * Null arguments in the array are treated as identity functions,
2607      * and the corresponding arguments left unchanged.
2608      * (If there are no non-null elements in the array, the original target is returned.)
2609      * Each filter is applied to the corresponding argument of the adapter.
2610      * <p>
2611      * If a filter {@code F} applies to the {@code N}th argument of
2612      * the target, then {@code F} must be a method handle which
2613      * takes exactly one argument.  The type of {@code F}'s sole argument
2614      * replaces the corresponding argument type of the target
2615      * in the resulting adapted method handle.
2616      * The return type of {@code F} must be identical to the corresponding
2617      * parameter type of the target.
2618      * <p>
2619      * It is an error if there are elements of {@code filters}
2620      * (null or not)
2621      * which do not correspond to argument positions in the target.
2622      * <p><b>Example:</b>
2623      * <blockquote><pre>{@code
2624 import static java.lang.invoke.MethodHandles.*;
2625 import static java.lang.invoke.MethodType.*;
2626 ...
2627 MethodHandle cat = lookup().findVirtual(String.class,
2628   "concat", methodType(String.class, String.class));
2629 MethodHandle upcase = lookup().findVirtual(String.class,
2630   "toUpperCase", methodType(String.class));
2631 assertEquals("xy", (String) cat.invokeExact("x", "y"));
2632 MethodHandle f0 = filterArguments(cat, 0, upcase);
2633 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
2634 MethodHandle f1 = filterArguments(cat, 1, upcase);
2635 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
2636 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
2637 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
2638      * }</pre></blockquote>
2639      * <p> Here is pseudocode for the resulting adapter:
2640      * <blockquote><pre>{@code
2641      * V target(P... p, A[i]... a[i], B... b);
2642      * A[i] filter[i](V[i]);
2643      * T adapter(P... p, V[i]... v[i], B... b) {
2644      *   return target(p..., f[i](v[i])..., b...);
2645      * }
2646      * }</pre></blockquote>
2647      *
2648      * @param target the method handle to invoke after arguments are filtered
2649      * @param pos the position of the first argument to filter
2650      * @param filters method handles to call initially on filtered arguments
2651      * @return method handle which incorporates the specified argument filtering logic
2652      * @throws NullPointerException if the target is null
2653      *                              or if the {@code filters} array is null
2654      * @throws IllegalArgumentException if a non-null element of {@code filters}
2655      *          does not match a corresponding argument type of target as described above,
2656      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
2657      *          or if the resulting method handle's type would have
2658      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2659      */
2660     public static
2661     MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
2662         filterArgumentsCheckArity(target, pos, filters);
2663         MethodHandle adapter = target;
2664         int curPos = pos-1;  // pre-incremented
2665         for (MethodHandle filter : filters) {
2666             curPos += 1;
2667             if (filter == null)  continue;  // ignore null elements of filters
2668             adapter = filterArgument(adapter, curPos, filter);
2669         }
2670         return adapter;
2671     }
2672 
2673     /*non-public*/ static
2674     MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
2675         filterArgumentChecks(target, pos, filter);
2676         MethodType targetType = target.type();
2677         MethodType filterType = filter.type();
2678         BoundMethodHandle result = target.rebind();
2679         Class<?> newParamType = filterType.parameterType(0);
2680         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
2681         MethodType newType = targetType.changeParameterType(pos, newParamType);
2682         result = result.copyWithExtendL(newType, lform, filter);
2683         return result;
2684     }
2685 
2686     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
2687         MethodType targetType = target.type();
2688         int maxPos = targetType.parameterCount();
2689         if (pos + filters.length > maxPos)
2690             throw newIllegalArgumentException("too many filters");
2691     }
2692 
2693     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
2694         MethodType targetType = target.type();
2695         MethodType filterType = filter.type();
2696         if (filterType.parameterCount() != 1
2697             || filterType.returnType() != targetType.parameterType(pos))
2698             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
2699     }
2700 
2701     /**
2702      * Adapts a target method handle by pre-processing
2703      * a sub-sequence of its arguments with a filter (another method handle).
2704      * The pre-processed arguments are replaced by the result (if any) of the
2705      * filter function.
2706      * The target is then called on the modified (usually shortened) argument list.
2707      * <p>
2708      * If the filter returns a value, the target must accept that value as
2709      * its argument in position {@code pos}, preceded and/or followed by
2710      * any arguments not passed to the filter.
2711      * If the filter returns void, the target must accept all arguments
2712      * not passed to the filter.
2713      * No arguments are reordered, and a result returned from the filter
2714      * replaces (in order) the whole subsequence of arguments originally
2715      * passed to the adapter.
2716      * <p>
2717      * The argument types (if any) of the filter
2718      * replace zero or one argument types of the target, at position {@code pos},
2719      * in the resulting adapted method handle.
2720      * The return type of the filter (if any) must be identical to the
2721      * argument type of the target at position {@code pos}, and that target argument
2722      * is supplied by the return value of the filter.
2723      * <p>
2724      * In all cases, {@code pos} must be greater than or equal to zero, and
2725      * {@code pos} must also be less than or equal to the target's arity.
2726      * <p><b>Example:</b>
2727      * <blockquote><pre>{@code
2728 import static java.lang.invoke.MethodHandles.*;
2729 import static java.lang.invoke.MethodType.*;
2730 ...
2731 MethodHandle deepToString = publicLookup()
2732   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
2733 
2734 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
2735 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
2736 
2737 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
2738 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
2739 
2740 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
2741 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
2742 assertEquals("[top, [up, down], strange]",
2743              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
2744 
2745 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
2746 assertEquals("[top, [up, down], [strange]]",
2747              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
2748 
2749 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
2750 assertEquals("[top, [[up, down, strange], charm], bottom]",
2751              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
2752      * }</pre></blockquote>
2753      * <p> Here is pseudocode for the resulting adapter:
2754      * <blockquote><pre>{@code
2755      * T target(A...,V,C...);
2756      * V filter(B...);
2757      * T adapter(A... a,B... b,C... c) {
2758      *   V v = filter(b...);
2759      *   return target(a...,v,c...);
2760      * }
2761      * // and if the filter has no arguments:
2762      * T target2(A...,V,C...);
2763      * V filter2();
2764      * T adapter2(A... a,C... c) {
2765      *   V v = filter2();
2766      *   return target2(a...,v,c...);
2767      * }
2768      * // and if the filter has a void return:
2769      * T target3(A...,C...);
2770      * void filter3(B...);
2771      * void adapter3(A... a,B... b,C... c) {
2772      *   filter3(b...);
2773      *   return target3(a...,c...);
2774      * }
2775      * }</pre></blockquote>
2776      * <p>
2777      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
2778      * one which first "folds" the affected arguments, and then drops them, in separate
2779      * steps as follows:
2780      * <blockquote><pre>{@code
2781      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
2782      * mh = MethodHandles.foldArguments(mh, coll); //step 1
2783      * }</pre></blockquote>
2784      * If the target method handle consumes no arguments besides than the result
2785      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
2786      * is equivalent to {@code filterReturnValue(coll, mh)}.
2787      * If the filter method handle {@code coll} consumes one argument and produces
2788      * a non-void result, then {@code collectArguments(mh, N, coll)}
2789      * is equivalent to {@code filterArguments(mh, N, coll)}.
2790      * Other equivalences are possible but would require argument permutation.
2791      *
2792      * @param target the method handle to invoke after filtering the subsequence of arguments
2793      * @param pos the position of the first adapter argument to pass to the filter,
2794      *            and/or the target argument which receives the result of the filter
2795      * @param filter method handle to call on the subsequence of arguments
2796      * @return method handle which incorporates the specified argument subsequence filtering logic
2797      * @throws NullPointerException if either argument is null
2798      * @throws IllegalArgumentException if the return type of {@code filter}
2799      *          is non-void and is not the same as the {@code pos} argument of the target,
2800      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
2801      *          or if the resulting method handle's type would have
2802      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2803      * @see MethodHandles#foldArguments
2804      * @see MethodHandles#filterArguments
2805      * @see MethodHandles#filterReturnValue
2806      */
2807     public static
2808     MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
2809         MethodType newType = collectArgumentsChecks(target, pos, filter);
2810         MethodType collectorType = filter.type();
2811         BoundMethodHandle result = target.rebind();
2812         LambdaForm lform;
2813         if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) {
2814             lform = result.editor().collectArgumentArrayForm(1 + pos, filter);
2815             if (lform != null) {
2816                 return result.copyWith(newType, lform);
2817             }
2818         }
2819         lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
2820         return result.copyWithExtendL(newType, lform, filter);
2821     }
2822 
2823     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
2824         MethodType targetType = target.type();
2825         MethodType filterType = filter.type();
2826         Class<?> rtype = filterType.returnType();
2827         List<Class<?>> filterArgs = filterType.parameterList();
2828         if (rtype == void.class) {
2829             return targetType.insertParameterTypes(pos, filterArgs);
2830         }
2831         if (rtype != targetType.parameterType(pos)) {
2832             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
2833         }
2834         return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
2835     }
2836 
2837     /**
2838      * Adapts a target method handle by post-processing
2839      * its return value (if any) with a filter (another method handle).
2840      * The result of the filter is returned from the adapter.
2841      * <p>
2842      * If the target returns a value, the filter must accept that value as
2843      * its only argument.
2844      * If the target returns void, the filter must accept no arguments.
2845      * <p>
2846      * The return type of the filter
2847      * replaces the return type of the target
2848      * in the resulting adapted method handle.
2849      * The argument type of the filter (if any) must be identical to the
2850      * return type of the target.
2851      * <p><b>Example:</b>
2852      * <blockquote><pre>{@code
2853 import static java.lang.invoke.MethodHandles.*;
2854 import static java.lang.invoke.MethodType.*;
2855 ...
2856 MethodHandle cat = lookup().findVirtual(String.class,
2857   "concat", methodType(String.class, String.class));
2858 MethodHandle length = lookup().findVirtual(String.class,
2859   "length", methodType(int.class));
2860 System.out.println((String) cat.invokeExact("x", "y")); // xy
2861 MethodHandle f0 = filterReturnValue(cat, length);
2862 System.out.println((int) f0.invokeExact("x", "y")); // 2
2863      * }</pre></blockquote>
2864      * <p> Here is pseudocode for the resulting adapter:
2865      * <blockquote><pre>{@code
2866      * V target(A...);
2867      * T filter(V);
2868      * T adapter(A... a) {
2869      *   V v = target(a...);
2870      *   return filter(v);
2871      * }
2872      * // and if the target has a void return:
2873      * void target2(A...);
2874      * T filter2();
2875      * T adapter2(A... a) {
2876      *   target2(a...);
2877      *   return filter2();
2878      * }
2879      * // and if the filter has a void return:
2880      * V target3(A...);
2881      * void filter3(V);
2882      * void adapter3(A... a) {
2883      *   V v = target3(a...);
2884      *   filter3(v);
2885      * }
2886      * }</pre></blockquote>
2887      * @param target the method handle to invoke before filtering the return value
2888      * @param filter method handle to call on the return value
2889      * @return method handle which incorporates the specified return value filtering logic
2890      * @throws NullPointerException if either argument is null
2891      * @throws IllegalArgumentException if the argument list of {@code filter}
2892      *          does not match the return type of target as described above
2893      */
2894     public static
2895     MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
2896         MethodType targetType = target.type();
2897         MethodType filterType = filter.type();
2898         filterReturnValueChecks(targetType, filterType);
2899         BoundMethodHandle result = target.rebind();
2900         BasicType rtype = BasicType.basicType(filterType.returnType());
2901         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
2902         MethodType newType = targetType.changeReturnType(filterType.returnType());
2903         result = result.copyWithExtendL(newType, lform, filter);
2904         return result;
2905     }
2906 
2907     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
2908         Class<?> rtype = targetType.returnType();
2909         int filterValues = filterType.parameterCount();
2910         if (filterValues == 0
2911                 ? (rtype != void.class)
2912                 : (rtype != filterType.parameterType(0)))
2913             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
2914     }
2915 
2916     /**
2917      * Adapts a target method handle by pre-processing
2918      * some of its arguments, and then calling the target with
2919      * the result of the pre-processing, inserted into the original
2920      * sequence of arguments.
2921      * <p>
2922      * The pre-processing is performed by {@code combiner}, a second method handle.
2923      * Of the arguments passed to the adapter, the first {@code N} arguments
2924      * are copied to the combiner, which is then called.
2925      * (Here, {@code N} is defined as the parameter count of the combiner.)
2926      * After this, control passes to the target, with any result
2927      * from the combiner inserted before the original {@code N} incoming
2928      * arguments.
2929      * <p>
2930      * If the combiner returns a value, the first parameter type of the target
2931      * must be identical with the return type of the combiner, and the next
2932      * {@code N} parameter types of the target must exactly match the parameters
2933      * of the combiner.
2934      * <p>
2935      * If the combiner has a void return, no result will be inserted,
2936      * and the first {@code N} parameter types of the target
2937      * must exactly match the parameters of the combiner.
2938      * <p>
2939      * The resulting adapter is the same type as the target, except that the
2940      * first parameter type is dropped,
2941      * if it corresponds to the result of the combiner.
2942      * <p>
2943      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
2944      * that either the combiner or the target does not wish to receive.
2945      * If some of the incoming arguments are destined only for the combiner,
2946      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
2947      * arguments will not need to be live on the stack on entry to the
2948      * target.)
2949      * <p><b>Example:</b>
2950      * <blockquote><pre>{@code
2951 import static java.lang.invoke.MethodHandles.*;
2952 import static java.lang.invoke.MethodType.*;
2953 ...
2954 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
2955   "println", methodType(void.class, String.class))
2956     .bindTo(System.out);
2957 MethodHandle cat = lookup().findVirtual(String.class,
2958   "concat", methodType(String.class, String.class));
2959 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
2960 MethodHandle catTrace = foldArguments(cat, trace);
2961 // also prints "boo":
2962 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
2963      * }</pre></blockquote>
2964      * <p> Here is pseudocode for the resulting adapter:
2965      * <blockquote><pre>{@code
2966      * // there are N arguments in A...
2967      * T target(V, A[N]..., B...);
2968      * V combiner(A...);
2969      * T adapter(A... a, B... b) {
2970      *   V v = combiner(a...);
2971      *   return target(v, a..., b...);
2972      * }
2973      * // and if the combiner has a void return:
2974      * T target2(A[N]..., B...);
2975      * void combiner2(A...);
2976      * T adapter2(A... a, B... b) {
2977      *   combiner2(a...);
2978      *   return target2(a..., b...);
2979      * }
2980      * }</pre></blockquote>
2981      * @param target the method handle to invoke after arguments are combined
2982      * @param combiner method handle to call initially on the incoming arguments
2983      * @return method handle which incorporates the specified argument folding logic
2984      * @throws NullPointerException if either argument is null
2985      * @throws IllegalArgumentException if {@code combiner}'s return type
2986      *          is non-void and not the same as the first argument type of
2987      *          the target, or if the initial {@code N} argument types
2988      *          of the target
2989      *          (skipping one matching the {@code combiner}'s return type)
2990      *          are not identical with the argument types of {@code combiner}
2991      */
2992     public static
2993     MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
2994         return foldArguments(target, 0, combiner);
2995     }
2996 
2997     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
2998         int foldArgs   = combinerType.parameterCount();
2999         Class<?> rtype = combinerType.returnType();
3000         int foldVals = rtype == void.class ? 0 : 1;
3001         int afterInsertPos = foldPos + foldVals;
3002         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
3003         if (ok && !(combinerType.parameterList()
3004                     .equals(targetType.parameterList().subList(afterInsertPos,
3005                                                                afterInsertPos + foldArgs))))
3006             ok = false;
3007         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
3008             ok = false;
3009         if (!ok)
3010             throw misMatchedTypes("target and combiner types", targetType, combinerType);
3011         return rtype;
3012     }
3013 
3014     /**
3015      * Makes a method handle which adapts a target method handle,
3016      * by guarding it with a test, a boolean-valued method handle.
3017      * If the guard fails, a fallback handle is called instead.
3018      * All three method handles must have the same corresponding
3019      * argument and return types, except that the return type
3020      * of the test must be boolean, and the test is allowed
3021      * to have fewer arguments than the other two method handles.
3022      * <p> Here is pseudocode for the resulting adapter:
3023      * <blockquote><pre>{@code
3024      * boolean test(A...);
3025      * T target(A...,B...);
3026      * T fallback(A...,B...);
3027      * T adapter(A... a,B... b) {
3028      *   if (test(a...))
3029      *     return target(a..., b...);
3030      *   else
3031      *     return fallback(a..., b...);
3032      * }
3033      * }</pre></blockquote>
3034      * Note that the test arguments ({@code a...} in the pseudocode) cannot
3035      * be modified by execution of the test, and so are passed unchanged
3036      * from the caller to the target or fallback as appropriate.
3037      * @param test method handle used for test, must return boolean
3038      * @param target method handle to call if test passes
3039      * @param fallback method handle to call if test fails
3040      * @return method handle which incorporates the specified if/then/else logic
3041      * @throws NullPointerException if any argument is null
3042      * @throws IllegalArgumentException if {@code test} does not return boolean,
3043      *          or if all three method types do not match (with the return
3044      *          type of {@code test} changed to match that of the target).
3045      */
3046     public static
3047     MethodHandle guardWithTest(MethodHandle test,
3048                                MethodHandle target,
3049                                MethodHandle fallback) {
3050         MethodType gtype = test.type();
3051         MethodType ttype = target.type();
3052         MethodType ftype = fallback.type();
3053         if (!ttype.equals(ftype))
3054             throw misMatchedTypes("target and fallback types", ttype, ftype);
3055         if (gtype.returnType() != boolean.class)
3056             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
3057         List<Class<?>> targs = ttype.parameterList();
3058         List<Class<?>> gargs = gtype.parameterList();
3059         if (!targs.equals(gargs)) {
3060             int gpc = gargs.size(), tpc = targs.size();
3061             if (gpc >= tpc || !targs.subList(0, gpc).equals(gargs))
3062                 throw misMatchedTypes("target and test types", ttype, gtype);
3063             test = dropArguments(test, gpc, targs.subList(gpc, tpc));
3064             gtype = test.type();
3065         }
3066         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
3067     }
3068 
3069     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
3070         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
3071     }
3072 
3073     /**
3074      * Makes a method handle which adapts a target method handle,
3075      * by running it inside an exception handler.
3076      * If the target returns normally, the adapter returns that value.
3077      * If an exception matching the specified type is thrown, the fallback
3078      * handle is called instead on the exception, plus the original arguments.
3079      * <p>
3080      * The target and handler must have the same corresponding
3081      * argument and return types, except that handler may omit trailing arguments
3082      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
3083      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
3084      * <p> Here is pseudocode for the resulting adapter:
3085      * <blockquote><pre>{@code
3086      * T target(A..., B...);
3087      * T handler(ExType, A...);
3088      * T adapter(A... a, B... b) {
3089      *   try {
3090      *     return target(a..., b...);
3091      *   } catch (ExType ex) {
3092      *     return handler(ex, a...);
3093      *   }
3094      * }
3095      * }</pre></blockquote>
3096      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
3097      * be modified by execution of the target, and so are passed unchanged
3098      * from the caller to the handler, if the handler is invoked.
3099      * <p>
3100      * The target and handler must return the same type, even if the handler
3101      * always throws.  (This might happen, for instance, because the handler
3102      * is simulating a {@code finally} clause).
3103      * To create such a throwing handler, compose the handler creation logic
3104      * with {@link #throwException throwException},
3105      * in order to create a method handle of the correct return type.
3106      * @param target method handle to call
3107      * @param exType the type of exception which the handler will catch
3108      * @param handler method handle to call if a matching exception is thrown
3109      * @return method handle which incorporates the specified try/catch logic
3110      * @throws NullPointerException if any argument is null
3111      * @throws IllegalArgumentException if {@code handler} does not accept
3112      *          the given exception type, or if the method handle types do
3113      *          not match in their return types and their
3114      *          corresponding parameters
3115      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
3116      */
3117     public static
3118     MethodHandle catchException(MethodHandle target,
3119                                 Class<? extends Throwable> exType,
3120                                 MethodHandle handler) {
3121         MethodType ttype = target.type();
3122         MethodType htype = handler.type();
3123         if (!Throwable.class.isAssignableFrom(exType))
3124             throw new ClassCastException(exType.getName());
3125         if (htype.parameterCount() < 1 ||
3126             !htype.parameterType(0).isAssignableFrom(exType))
3127             throw newIllegalArgumentException("handler does not accept exception type "+exType);
3128         if (htype.returnType() != ttype.returnType())
3129             throw misMatchedTypes("target and handler return types", ttype, htype);
3130         List<Class<?>> targs = ttype.parameterList();
3131         List<Class<?>> hargs = htype.parameterList();
3132         hargs = hargs.subList(1, hargs.size());  // omit leading parameter from handler
3133         if (!targs.equals(hargs)) {
3134             int hpc = hargs.size(), tpc = targs.size();
3135             if (hpc >= tpc || !targs.subList(0, hpc).equals(hargs))
3136                 throw misMatchedTypes("target and handler types", ttype, htype);
3137             handler = dropArguments(handler, 1+hpc, targs.subList(hpc, tpc));
3138             htype = handler.type();
3139         }
3140         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
3141     }
3142 
3143     /**
3144      * Produces a method handle which will throw exceptions of the given {@code exType}.
3145      * The method handle will accept a single argument of {@code exType},
3146      * and immediately throw it as an exception.
3147      * The method type will nominally specify a return of {@code returnType}.
3148      * The return type may be anything convenient:  It doesn't matter to the
3149      * method handle's behavior, since it will never return normally.
3150      * @param returnType the return type of the desired method handle
3151      * @param exType the parameter type of the desired method handle
3152      * @return method handle which can throw the given exceptions
3153      * @throws NullPointerException if either argument is null
3154      */
3155     public static
3156     MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
3157         if (!Throwable.class.isAssignableFrom(exType))
3158             throw new ClassCastException(exType.getName());
3159         return MethodHandleImpl.throwException(MethodType.methodType(returnType, exType));
3160     }
3161 
3162     /**
3163      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
3164      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
3165      * delivers the loop's result, which is the return value of the resulting handle.
3166      * <p>
3167      * Intuitively, every loop is formed by one or more "clauses", each specifying a local iteration value and/or a loop
3168      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
3169      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
3170      * terms of method handles, each clause will determine four actions:<ul>
3171      * <li>Before the loop executes, the initialization of an iteration variable or loop invariant local.
3172      * <li>When a clause executes, an update step for the iteration variable.
3173      * <li>When a clause executes, a predicate execution to test for loop exit.
3174      * <li>If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
3175      * </ul>
3176      * <p>
3177      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
3178      * this case. See below for a detailed description.
3179      * <p>
3180      * Each clause function, with the exception of clause initializers, is able to observe the entire loop state,
3181      * because it will be passed <em>all</em> current iteration variable values, as well as all incoming loop
3182      * parameters. Most clause functions will not need all of this information, but they will be formally connected as
3183      * if by {@link #dropArguments}.
3184      * <p>
3185      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
3186      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
3187      * corresponds to a place where {@link IllegalArgumentException} may be thrown if the required constraint is not met
3188      * by the inputs to the loop combinator. The term "effectively identical", applied to parameter type lists, means
3189      * that they must be identical, or else one list must be a proper prefix of the other.
3190      * <p>
3191      * <em>Step 0: Determine clause structure.</em><ol type="a">
3192      * <li>The clause array (of type {@code MethodHandle[][]} must be non-{@code null} and contain at least one element.
3193      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
3194      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
3195      * four. Padding takes place by appending elements to the array.
3196      * <li>Clauses with all {@code null}s are disregarded.
3197      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
3198      * </ol>
3199      * <p>
3200      * <em>Step 1A: Determine iteration variables.</em><ol type="a">
3201      * <li>Examine init and step function return types, pairwise, to determine each clause's iteration variable type.
3202      * <li>If both functions are omitted, use {@code void}; else if one is omitted, use the other's return type; else
3203      * use the common return type (they must be identical).
3204      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
3205      * <li>This list of types is called the "common prefix".
3206      * </ol>
3207      * <p>
3208      * <em>Step 1B: Determine loop parameters.</em><ol type="a">
3209      * <li>Examine init function parameter lists.
3210      * <li>Omitted init functions are deemed to have {@code null} parameter lists.
3211      * <li>All init function parameter lists must be effectively identical.
3212      * <li>The longest parameter list (which is necessarily unique) is called the "common suffix".
3213      * </ol>
3214      * <p>
3215      * <em>Step 1C: Determine loop return type.</em><ol type="a">
3216      * <li>Examine fini function return types, disregarding omitted fini functions.
3217      * <li>If there are no fini functions, use {@code void} as the loop return type.
3218      * <li>Otherwise, use the common return type of the fini functions; they must all be identical.
3219      * </ol>
3220      * <p>
3221      * <em>Step 1D: Check other types.</em><ol type="a">
3222      * <li>There must be at least one non-omitted pred function.
3223      * <li>Every non-omitted pred function must have a {@code boolean} return type.
3224      * </ol>
3225      * <p>
3226      * (Implementation Note: Steps 1A, 1B, 1C, 1D are logically independent of each other, and may be performed in any
3227      * order.)
3228      * <p>
3229      * <em>Step 2: Determine parameter lists.</em><ol type="a">
3230      * <li>The parameter list for the resulting loop handle will be the "common suffix".
3231      * <li>The parameter list for init functions will be adjusted to the "common suffix". (Note that their parameter
3232      * lists are already effectively identical to the common suffix.)
3233      * <li>The parameter list for non-init (step, pred, and fini) functions will be adjusted to the common prefix
3234      * followed by the common suffix, called the "common parameter sequence".
3235      * <li>Every non-init, non-omitted function parameter list must be effectively identical to the common parameter
3236      * sequence.
3237      * </ol>
3238      * <p>
3239      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
3240      * <li>If an init function is omitted, use a {@linkplain #constant constant function} of the appropriate
3241      * {@code null}/zero/{@code false}/{@code void} type. (For this purpose, a constant {@code void} is simply a
3242      * function which does nothing and returns {@code void}; it can be obtained from another constant function by
3243      * {@linkplain MethodHandle#asType type conversion}.)
3244      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
3245      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
3246      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
3247      * <li>If a pred function is omitted, the corresponding fini function must also be omitted.
3248      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
3249      * as this clause is concerned.)
3250      * <li>If a fini function is omitted, use a constant {@code null}/zero/{@code false}/{@code void} function of the
3251      * loop return type.
3252      * </ol>
3253      * <p>
3254      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
3255      * <li>At this point, every init function parameter list is effectively identical to the common suffix, but some
3256      * lists may be shorter. For every init function with a short parameter list, pad out the end of the list by
3257      * {@linkplain #dropArguments dropping arguments}.
3258      * <li>At this point, every non-init function parameter list is effectively identical to the common parameter
3259      * sequence, but some lists may be shorter. For every non-init function with a short parameter list, pad out the end
3260      * of the list by {@linkplain #dropArguments dropping arguments}.
3261      * </ol>
3262      * <p>
3263      * <em>Final observations.</em><ol type="a">
3264      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
3265      * <li>All init functions have a common parameter type list, which the final loop handle will also have.
3266      * <li>All fini functions have a common return type, which the final loop handle will also have.
3267      * <li>All non-init functions have a common parameter type list, which is the common parameter sequence, of
3268      * (non-{@code void}) iteration variables followed by loop parameters.
3269      * <li>Each pair of init and step functions agrees in their return types.
3270      * <li>Each non-init function will be able to observe the current values of all iteration variables, by means of the
3271      * common prefix.
3272      * </ol>
3273      * <p>
3274      * <em>Loop execution.</em><ol type="a">
3275      * <li>When the loop is called, the loop input values are saved in locals, to be passed (as the common suffix) to
3276      * every clause function. These locals are loop invariant.
3277      * <li>Each init function is executed in clause order (passing the common suffix) and the non-{@code void} values
3278      * are saved (as the common prefix) into locals. These locals are loop varying (unless their steps are identity
3279      * functions, as noted above).
3280      * <li>All function executions (except init functions) will be passed the common parameter sequence, consisting of
3281      * the non-{@code void} iteration values (in clause order) and then the loop inputs (in argument order).
3282      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
3283      * returns {@code false}.
3284      * <li>The non-{@code void} result from a step function call is used to update the corresponding loop variable. The
3285      * updated value is immediately visible to all subsequent function calls.
3286      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
3287      * is returned from the loop as a whole.
3288      * </ol>
3289      * <p>
3290      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the types / values
3291      * of loop variables; {@code A}/{@code a}, those of arguments passed to the resulting loop; and {@code R}, the
3292      * result types of finalizers as well as of the resulting loop.
3293      * <blockquote><pre>{@code
3294      * V... init...(A...);
3295      * boolean pred...(V..., A...);
3296      * V... step...(V..., A...);
3297      * R fini...(V..., A...);
3298      * R loop(A... a) {
3299      *   V... v... = init...(a...);
3300      *   for (;;) {
3301      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
3302      *       v = s(v..., a...);
3303      *       if (!p(v..., a...)) {
3304      *         return f(v..., a...);
3305      *       }
3306      *     }
3307      *   }
3308      * }
3309      * }</pre></blockquote>
3310      * <p>
3311      * @apiNote Example:
3312      * <blockquote><pre>{@code
3313      * // iterative implementation of the factorial function as a loop handle
3314      * static int one(int k) { return 1; }
3315      * int inc(int i, int acc, int k) { return i + 1; }
3316      * int mult(int i, int acc, int k) { return i * acc; }
3317      * boolean pred(int i, int acc, int k) { return i < k; }
3318      * int fin(int i, int acc, int k) { return acc; }
3319      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
3320      * // null initializer for counter, should initialize to 0
3321      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
3322      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
3323      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
3324      * assertEquals(120, loop.invoke(5));
3325      * }</pre></blockquote>
3326      *
3327      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
3328      *
3329      * @return a method handle embodying the looping behavior as defined by the arguments.
3330      *
3331      * @throws IllegalArgumentException in case any of the constraints described above is violated.
3332      *
3333      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
3334      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
3335      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
3336      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
3337      * @since 9
3338      */
3339     public static MethodHandle loop(MethodHandle[]... clauses) {
3340         // Step 0: determine clause structure.
3341         checkLoop0(clauses);
3342 
3343         List<MethodHandle> init = new ArrayList<>();
3344         List<MethodHandle> step = new ArrayList<>();
3345         List<MethodHandle> pred = new ArrayList<>();
3346         List<MethodHandle> fini = new ArrayList<>();
3347 
3348         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
3349             init.add(clause[0]); // all clauses have at least length 1
3350             step.add(clause.length <= 1 ? null : clause[1]);
3351             pred.add(clause.length <= 2 ? null : clause[2]);
3352             fini.add(clause.length <= 3 ? null : clause[3]);
3353         });
3354 
3355         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
3356         final int nclauses = init.size();
3357 
3358         // Step 1A: determine iteration variables.
3359         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
3360         for (int i = 0; i < nclauses; ++i) {
3361             MethodHandle in = init.get(i);
3362             MethodHandle st = step.get(i);
3363             if (in == null && st == null) {
3364                 iterationVariableTypes.add(void.class);
3365             } else if (in != null && st != null) {
3366                 checkLoop1a(i, in, st);
3367                 iterationVariableTypes.add(in.type().returnType());
3368             } else {
3369                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
3370             }
3371         }
3372         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).
3373                 collect(Collectors.toList());
3374 
3375         // Step 1B: determine loop parameters.
3376         final List<Class<?>> empty = new ArrayList<>();
3377         final List<Class<?>> commonSuffix = init.stream().filter(Objects::nonNull).map(MethodHandle::type).
3378                 map(MethodType::parameterList).reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
3379         checkLoop1b(init, commonSuffix);
3380 
3381         // Step 1C: determine loop return type.
3382         // Step 1D: check other types.
3383         final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type).
3384                 map(MethodType::returnType).findFirst().orElse(void.class);
3385         checkLoop1cd(pred, fini, loopReturnType);
3386 
3387         // Step 2: determine parameter lists.
3388         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
3389         commonParameterSequence.addAll(commonSuffix);
3390         checkLoop2(step, pred, fini, commonParameterSequence);
3391 
3392         // Step 3: fill in omitted functions.
3393         for (int i = 0; i < nclauses; ++i) {
3394             Class<?> t = iterationVariableTypes.get(i);
3395             if (init.get(i) == null) {
3396                 init.set(i, zeroHandle(t));
3397             }
3398             if (step.get(i) == null) {
3399                 step.set(i, dropArguments(t == void.class ? zeroHandle(t) : identity(t), 0, commonPrefix.subList(0, i)));
3400             }
3401             if (pred.get(i) == null) {
3402                 pred.set(i, constant(boolean.class, true));
3403             }
3404             if (fini.get(i) == null) {
3405                 fini.set(i, zeroHandle(t));
3406             }
3407         }
3408 
3409         // Step 4: fill in missing parameter types.
3410         List<MethodHandle> finit = fillParameterTypes(init, commonSuffix);
3411         List<MethodHandle> fstep = fillParameterTypes(step, commonParameterSequence);
3412         List<MethodHandle> fpred = fillParameterTypes(pred, commonParameterSequence);
3413         List<MethodHandle> ffini = fillParameterTypes(fini, commonParameterSequence);
3414 
3415         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
3416                 allMatch(pl -> pl.equals(commonSuffix));
3417         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
3418                 allMatch(pl -> pl.equals(commonParameterSequence));
3419 
3420         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, commonPrefix, finit, fstep, fpred, ffini);
3421     }
3422 
3423     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
3424         return hs.stream().map(h -> {
3425             int pc = h.type().parameterCount();
3426             int tpsize = targetParams.size();
3427             return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
3428         }).collect(Collectors.toList());
3429     }
3430 
3431     /**
3432      * Constructs a {@code while} loop from an initializer, a body, and a predicate. This is a convenience wrapper for
3433      * the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
3434      * <p>
3435      * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}.
3436      * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle
3437      * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code
3438      * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][])
3439      * generic loop combinator}.
3440      * <p>
3441      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
3442      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
3443      * passed to the loop.
3444      * <blockquote><pre>{@code
3445      * V init(A);
3446      * boolean pred(V, A);
3447      * V body(V, A);
3448      * V whileLoop(A a) {
3449      *   V v = init(a);
3450      *   while (pred(v, a)) {
3451      *     v = body(v, a);
3452      *   }
3453      *   return v;
3454      * }
3455      * }</pre></blockquote>
3456      * <p>
3457      * @apiNote Example:
3458      * <blockquote><pre>{@code
3459      * // implement the zip function for lists as a loop handle
3460      * List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
3461      * boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
3462      * List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
3463      *   zip.add(a.next());
3464      *   zip.add(b.next());
3465      *   return zip;
3466      * }
3467      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
3468      * MethodHandle loop = MethodHandles.doWhileLoop(MH_initZip, MH_zipStep, MH_zipPred);
3469      * List<String> a = Arrays.asList("a", "b", "c", "d");
3470      * List<String> b = Arrays.asList("e", "f", "g", "h");
3471      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
3472      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
3473      * }</pre></blockquote>
3474      *
3475      * <p>
3476      * @implSpec The implementation of this method is equivalent to:
3477      * <blockquote><pre>{@code
3478      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
3479      *     MethodHandle[]
3480      *         checkExit = {null, null, pred, identity(init.type().returnType())},
3481      *         varBody = {init, body};
3482      *     return loop(checkExit, varBody);
3483      * }
3484      * }</pre></blockquote>
3485      *
3486      * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's
3487      *             result type. Passing {@code null} or a {@code void} init function will make the loop's result type
3488      *             {@code void}.
3489      * @param pred condition for the loop, which may not be {@code null}.
3490      * @param body body of the loop, which may not be {@code null}.
3491      *
3492      * @return the value of the loop variable as the loop terminates.
3493      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
3494      *
3495      * @see MethodHandles#loop(MethodHandle[][])
3496      * @since 9
3497      */
3498     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
3499         MethodHandle fin = init == null ? zeroHandle(void.class) : identity(init.type().returnType());
3500         MethodHandle[] checkExit = {null, null, pred, fin};
3501         MethodHandle[] varBody = {init, body};
3502         return loop(checkExit, varBody);
3503     }
3504 
3505     /**
3506      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. This is a convenience wrapper
3507      * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
3508      * <p>
3509      * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}.
3510      * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle
3511      * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code
3512      * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][])
3513      * generic loop combinator}.
3514      * <p>
3515      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
3516      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
3517      * passed to the loop.
3518      * <blockquote><pre>{@code
3519      * V init(A);
3520      * boolean pred(V, A);
3521      * V body(V, A);
3522      * V doWhileLoop(A a) {
3523      *   V v = init(a);
3524      *   do {
3525      *     v = body(v, a);
3526      *   } while (pred(v, a));
3527      *   return v;
3528      * }
3529      * }</pre></blockquote>
3530      * <p>
3531      * @apiNote Example:
3532      * <blockquote><pre>{@code
3533      * // int i = 0; while (i < limit) { ++i; } return i; => limit
3534      * int zero(int limit) { return 0; }
3535      * int step(int i, int limit) { return i + 1; }
3536      * boolean pred(int i, int limit) { return i < limit; }
3537      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
3538      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
3539      * assertEquals(23, loop.invoke(23));
3540      * }</pre></blockquote>
3541      *
3542      * <p>
3543      * @implSpec The implementation of this method is equivalent to:
3544      * <blockquote><pre>{@code
3545      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
3546      *     MethodHandle[] clause = { init, body, pred, identity(init.type().returnType()) };
3547      *     return loop(clause);
3548      * }
3549      * }</pre></blockquote>
3550      *
3551      *
3552      * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's
3553      *             result type. Passing {@code null} or a {@code void} init function will make the loop's result type
3554      *             {@code void}.
3555      * @param pred condition for the loop, which may not be {@code null}.
3556      * @param body body of the loop, which may not be {@code null}.
3557      *
3558      * @return the value of the loop variable as the loop terminates.
3559      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
3560      *
3561      * @see MethodHandles#loop(MethodHandle[][])
3562      * @since 9
3563      */
3564     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
3565         MethodHandle fin = init == null ? zeroHandle(void.class) : identity(init.type().returnType());
3566         MethodHandle[] clause = {init, body, pred, fin};
3567         return loop(clause);
3568     }
3569 
3570     /**
3571      * Constructs a loop that runs a given number of iterations. The loop counter is an {@code int} initialized from the
3572      * {@code iterations} handle evaluation result. The counter is passed to the {@code body} function, so that must
3573      * accept an initial {@code int} argument. The result of the loop execution is the final value of the additional
3574      * local state. This is a convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop
3575      * combinator}.
3576      * <p>
3577      * The result type and parameter type list of {@code init} determine those of the resulting handle. The {@code
3578      * iterations} handle must accept the same parameter types as {@code init} but return an {@code int}. The {@code
3579      * body} handle must accept the same parameter types as well, preceded by an {@code int} parameter for the counter,
3580      * and a parameter of the same type as {@code init}'s result. These constraints follow directly from those described
3581      * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
3582      * <p>
3583      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
3584      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
3585      * passed to the loop.
3586      * <blockquote><pre>{@code
3587      * int iterations(A);
3588      * V init(A);
3589      * V body(int, V, A);
3590      * V countedLoop(A a) {
3591      *   int end = iterations(a);
3592      *   V v = init(a);
3593      *   for (int i = 0; i < end; ++i) {
3594      *     v = body(i, v, a);
3595      *   }
3596      *   return v;
3597      * }
3598      * }</pre></blockquote>
3599      * <p>
3600      * @apiNote Example:
3601      * <blockquote><pre>{@code
3602      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
3603      * // => a variation on a well known theme
3604      * String start(String arg) { return arg; }
3605      * String step(int counter, String v, String arg) { return "na " + v; }
3606      * // assume MH_start and MH_step are handles to the two methods above
3607      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
3608      * MethodHandle loop = MethodHandles.countedLoop(fit13, MH_start, MH_step);
3609      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
3610      * }</pre></blockquote>
3611      *
3612      * <p>
3613      * @implSpec The implementation of this method is equivalent to:
3614      * <blockquote><pre>{@code
3615      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
3616      *     return countedLoop(null, iterations, init, body);  // null => constant zero
3617      * }
3618      * }</pre></blockquote>
3619      *
3620      * @param iterations a handle to return the number of iterations this loop should run.
3621      * @param init initializer for additional loop state. This determines the loop's result type.
3622      *             Passing {@code null} or a {@code void} init function will make the loop's result type
3623      *             {@code void}.
3624      * @param body the body of the loop, which must not be {@code null}.
3625      *             It must accept an initial {@code int} parameter (for the counter), and then any
3626      *             additional loop-local variable plus loop parameters.
3627      *
3628      * @return a method handle representing the loop.
3629      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
3630      *
3631      * @since 9
3632      */
3633     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
3634         return countedLoop(null, iterations, init, body);
3635     }
3636 
3637     /**
3638      * Constructs a loop that counts over a range of numbers. The loop counter is an {@code int} that will be
3639      * initialized to the {@code int} value returned from the evaluation of the {@code start} handle and run to the
3640      * value returned from {@code end} (exclusively) with a step width of 1. The counter value is passed to the {@code
3641      * body} function in each iteration; it has to accept an initial {@code int} parameter
3642      * for that. The result of the loop execution is the final value of the additional local state
3643      * obtained by running {@code init}.
3644      * This is a
3645      * convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
3646      * <p>
3647      * The constraints for the {@code init} and {@code body} handles are the same as for {@link
3648      * #countedLoop(MethodHandle, MethodHandle, MethodHandle)}. Additionally, the {@code start} and {@code end} handles
3649      * must return an {@code int} and accept the same parameters as {@code init}.
3650      * <p>
3651      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
3652      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
3653      * passed to the loop.
3654      * <blockquote><pre>{@code
3655      * int start(A);
3656      * int end(A);
3657      * V init(A);
3658      * V body(int, V, A);
3659      * V countedLoop(A a) {
3660      *   int s = start(a);
3661      *   int e = end(a);
3662      *   V v = init(a);
3663      *   for (int i = s; i < e; ++i) {
3664      *     v = body(i, v, a);
3665      *   }
3666      *   return v;
3667      * }
3668      * }</pre></blockquote>
3669      *
3670      * <p>
3671      * @implSpec The implementation of this method is equivalent to:
3672      * <blockquote><pre>{@code
3673      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
3674      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
3675      *     // assume MH_increment and MH_lessThan are handles to x+1 and x<y of type int
3676      *     MethodHandle[]
3677      *         indexVar = {start, MH_increment}, // i = start; i = i+1
3678      *         loopLimit = {end, null, MH_lessThan, returnVar }, // i<end
3679      *         bodyClause = {init, dropArguments(body, 1, int.class)};  // v = body(i, v);
3680      *     return loop(indexVar, loopLimit, bodyClause);
3681      * }
3682      * }</pre></blockquote>
3683      *
3684      * @param start a handle to return the start value of the loop counter.
3685      *              If it is {@code null}, a constant zero is assumed.
3686      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to {@code end-1}).
3687      * @param init initializer for additional loop state. This determines the loop's result type.
3688      *             Passing {@code null} or a {@code void} init function will make the loop's result type
3689      *             {@code void}.
3690      * @param body the body of the loop, which must not be {@code null}.
3691      *             It must accept an initial {@code int} parameter (for the counter), and then any
3692      *             additional loop-local variable plus loop parameters.
3693      *
3694      * @return a method handle representing the loop.
3695      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
3696      *
3697      * @since 9
3698      */
3699     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
3700         MethodHandle returnVar = dropArguments(init == null ? zeroHandle(void.class) : identity(init.type().returnType()),
3701                 0, int.class, int.class);
3702         MethodHandle[] indexVar = {start, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep)};
3703         MethodHandle[] loopLimit = {end, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred), returnVar};
3704         MethodHandle[] bodyClause = {init, dropArguments(body, 1, int.class)};
3705         return loop(indexVar, loopLimit, bodyClause);
3706     }
3707 
3708     /**
3709      * Constructs a loop that ranges over the elements produced by an {@code Iterator<T>}.
3710      * The iterator will be produced by the evaluation of the {@code iterator} handle.
3711      * If this handle is passed as {@code null} the method {@link Iterable#iterator} will be used instead,
3712      * and will be applied to a leading argument of the loop handle.
3713      * Each value produced by the iterator is passed to the {@code body}, which must accept an initial {@code T} parameter.
3714      * The result of the loop execution is the final value of the additional local state
3715      * obtained by running {@code init}.
3716      * <p>
3717      * This is a convenience wrapper for the
3718      * {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}, and the constraints imposed on the {@code body}
3719      * handle follow directly from those described for the latter.
3720      * <p>
3721      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
3722      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
3723      * structure the loop iterates over, and {@code A}/{@code a}, that of the argument passed to the loop.
3724      * <blockquote><pre>{@code
3725      * Iterator<T> iterator(A);  // defaults to Iterable::iterator
3726      * V init(A);
3727      * V body(T,V,A);
3728      * V iteratedLoop(A a) {
3729      *   Iterator<T> it = iterator(a);
3730      *   V v = init(a);
3731      *   for (T t : it) {
3732      *     v = body(t, v, a);
3733      *   }
3734      *   return v;
3735      * }
3736      * }</pre></blockquote>
3737      * <p>
3738      * The type {@code T} may be either a primitive or reference.
3739      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type
3740      * {@code Iterator}, the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body}
3741      * to {@code Object} as if by the {@link MethodHandle#asType asType} conversion method.
3742      * Therefore, if an iterator of the wrong type appears as the loop is executed,
3743      * runtime exceptions may occur as the result of dynamic conversions performed by {@code asType}.
3744      * <p>
3745      * @apiNote Example:
3746      * <blockquote><pre>{@code
3747      * // reverse a list
3748      * List<String> reverseStep(String e, List<String> r, List<String> l) {
3749      *   r.add(0, e);
3750      *   return r;
3751      * }
3752      * List<String> newArrayList(List<String> l) { return new ArrayList<>(); }
3753      * // assume MH_reverseStep, MH_newArrayList are handles to the above methods
3754      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
3755      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
3756      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
3757      * assertEquals(reversedList, (List<String>) loop.invoke(list));
3758      * }</pre></blockquote>
3759      * <p>
3760      * @implSpec The implementation of this method is equivalent to:
3761      * <blockquote><pre>{@code
3762      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
3763      *     // assume MH_next and MH_hasNext are handles to methods of Iterator
3764      *     Class<?> itype = iterator.type().returnType();
3765      *     Class<?> ttype = body.type().parameterType(0);
3766      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, itype);
3767      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
3768      *     MethodHandle[]
3769      *         iterVar = {iterator, null, MH_hasNext, returnVar}, // it = iterator(); while (it.hasNext)
3770      *         bodyClause = {init, filterArgument(body, 0, nextVal)};  // v = body(t, v, a);
3771      *     return loop(iterVar, bodyClause);
3772      * }
3773      * }</pre></blockquote>
3774      *
3775      * @param iterator a handle to return the iterator to start the loop.
3776      *             Passing {@code null} will make the loop call {@link Iterable#iterator()} on the first
3777      *             incoming value.
3778      * @param init initializer for additional loop state. This determines the loop's result type.
3779      *             Passing {@code null} or a {@code void} init function will make the loop's result type
3780      *             {@code void}.
3781      * @param body the body of the loop, which must not be {@code null}.
3782      *             It must accept an initial {@code T} parameter (for the iterated values), and then any
3783      *             additional loop-local variable plus loop parameters.
3784      *
3785      * @return a method handle embodying the iteration loop functionality.
3786      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
3787      *
3788      * @since 9
3789      */
3790     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
3791         checkIteratedLoop(body);
3792 
3793         MethodHandle initit = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
3794         MethodHandle initIterator = iterator == null ?
3795                 initit.asType(initit.type().changeParameterType(0, body.type().parameterType(init == null ? 1 : 2))) :
3796                 iterator;
3797         Class<?> itype = initIterator.type().returnType();
3798         Class<?> ttype = body.type().parameterType(0);
3799 
3800         MethodHandle returnVar =
3801                 dropArguments(init == null ? zeroHandle(void.class) : identity(init.type().returnType()), 0, itype);
3802         MethodHandle initnx = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
3803         MethodHandle nextVal = initnx.asType(initnx.type().changeReturnType(ttype));
3804 
3805         MethodHandle[] iterVar = {initIterator, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred), returnVar};
3806         MethodHandle[] bodyClause = {init, filterArgument(body, 0, nextVal)};
3807 
3808         return loop(iterVar, bodyClause);
3809     }
3810 
3811     /**
3812      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
3813      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
3814      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
3815      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
3816      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
3817      * {@code try-finally} handle.
3818      * <p>
3819      * The {@code cleanup} handle will be passed one or two additional leading arguments.
3820      * The first is the exception thrown during the
3821      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
3822      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
3823      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
3824      * The second argument is not present if the {@code target} handle has a {@code void} return type.
3825      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
3826      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
3827      * <p>
3828      * The {@code target} and {@code cleanup} handles' return types must be the same. Their parameter type lists also
3829      * must be the same, but the {@code cleanup} handle must accept one or two more leading parameters:<ul>
3830      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
3831      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
3832      * the result from the execution of the {@code target} handle.
3833      * This parameter is not present if the {@code target} returns {@code void}.
3834      * </ul>
3835      * <p>
3836      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
3837      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
3838      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
3839      * the cleanup.
3840      * <blockquote><pre>{@code
3841      * V target(A..., B...);
3842      * V cleanup(Throwable, V, A...);
3843      * V adapter(A... a, B... b) {
3844      *   V result = (zero value for V);
3845      *   Throwable throwable = null;
3846      *   try {
3847      *     result = target(a..., b...);
3848      *   } catch (Throwable t) {
3849      *     throwable = t;
3850      *     throw t;
3851      *   } finally {
3852      *     result = cleanup(throwable, result, a...);
3853      *   }
3854      *   return result;
3855      * }
3856      * }</pre></blockquote>
3857      * <p>
3858      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
3859      * be modified by execution of the target, and so are passed unchanged
3860      * from the caller to the cleanup, if it is invoked.
3861      * <p>
3862      * The target and cleanup must return the same type, even if the cleanup
3863      * always throws.
3864      * To create such a throwing cleanup, compose the cleanup logic
3865      * with {@link #throwException throwException},
3866      * in order to create a method handle of the correct return type.
3867      * <p>
3868      * Note that {@code tryFinally} never converts exceptions into normal returns.
3869      * In rare cases where exceptions must be converted in that way, first wrap
3870      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
3871      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
3872      *
3873      * @param target the handle whose execution is to be wrapped in a {@code try} block.
3874      * @param cleanup the handle that is invoked in the finally block.
3875      *
3876      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
3877      * @throws NullPointerException if any argument is null
3878      * @throws IllegalArgumentException if {@code cleanup} does not accept
3879      *          the required leading arguments, or if the method handle types do
3880      *          not match in their return types and their
3881      *          corresponding trailing parameters
3882      *
3883      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
3884      * @since 9
3885      */
3886     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
3887         List<Class<?>> targetParamTypes = target.type().parameterList();
3888         List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
3889         Class<?> rtype = target.type().returnType();
3890 
3891         checkTryFinally(target, cleanup);
3892 
3893         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
3894         int tpSize = targetParamTypes.size();
3895         int cpPrefixLength = rtype == void.class ? 1 : 2;
3896         int cpSize = cleanupParamTypes.size();
3897         MethodHandle aCleanup = cpSize - cpPrefixLength < tpSize ?
3898                 dropArguments(cleanup, cpSize, targetParamTypes.subList(tpSize - (cpSize - cpPrefixLength), tpSize)) :
3899                 cleanup;
3900 
3901         MethodHandle aTarget = target.asSpreader(Object[].class, target.type().parameterCount());
3902         aCleanup = aCleanup.asSpreader(Object[].class, tpSize);
3903 
3904         return MethodHandleImpl.makeTryFinally(aTarget, aCleanup, rtype, targetParamTypes);
3905     }
3906 
3907     /**
3908      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
3909      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
3910      * before the folded arguments.
3911      * <p>
3912      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
3913      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
3914      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
3915      * 0.
3916      * <p>
3917      * @apiNote Example:
3918      * <blockquote><pre>{@code
3919     import static java.lang.invoke.MethodHandles.*;
3920     import static java.lang.invoke.MethodType.*;
3921     ...
3922     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
3923     "println", methodType(void.class, String.class))
3924     .bindTo(System.out);
3925     MethodHandle cat = lookup().findVirtual(String.class,
3926     "concat", methodType(String.class, String.class));
3927     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
3928     MethodHandle catTrace = foldArguments(cat, 1, trace);
3929     // also prints "jum":
3930     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
3931      * }</pre></blockquote>
3932      * <p> Here is pseudocode for the resulting adapter:
3933      * <blockquote><pre>{@code
3934      * // there are N arguments in A...
3935      * T target(Z..., V, A[N]..., B...);
3936      * V combiner(A...);
3937      * T adapter(Z... z, A... a, B... b) {
3938      *   V v = combiner(a...);
3939      *   return target(z..., v, a..., b...);
3940      * }
3941      * // and if the combiner has a void return:
3942      * T target2(Z..., A[N]..., B...);
3943      * void combiner2(A...);
3944      * T adapter2(Z... z, A... a, B... b) {
3945      *   combiner2(a...);
3946      *   return target2(z..., a..., b...);
3947      * }
3948      * }</pre></blockquote>
3949      *
3950      * @param target the method handle to invoke after arguments are combined
3951      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
3952      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
3953      * @param combiner method handle to call initially on the incoming arguments
3954      * @return method handle which incorporates the specified argument folding logic
3955      * @throws NullPointerException if either argument is null
3956      * @throws IllegalArgumentException if {@code combiner}'s return type
3957      *          is non-void and not the same as the argument type at position {@code pos} of
3958      *          the target signature, or if the {@code N} argument types at position {@code pos}
3959      *          of the target signature
3960      *          (skipping one matching the {@code combiner}'s return type)
3961      *          are not identical with the argument types of {@code combiner}
3962      *
3963      * @see #foldArguments(MethodHandle, MethodHandle)
3964      * @since 9
3965      */
3966     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
3967         MethodType targetType = target.type();
3968         MethodType combinerType = combiner.type();
3969         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
3970         BoundMethodHandle result = target.rebind();
3971         boolean dropResult = rtype == void.class;
3972         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
3973         MethodType newType = targetType;
3974         if (!dropResult) {
3975             newType = newType.dropParameterTypes(pos, pos + 1);
3976         }
3977         result = result.copyWithExtendL(newType, lform, combiner);
3978         return result;
3979     }
3980 
3981     /**
3982      * Wrap creation of a proper zero handle for a given type.
3983      *
3984      * @param type the type.
3985      *
3986      * @return a zero value for the given type.
3987      */
3988     static MethodHandle zeroHandle(Class<?> type) {
3989         return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
3990     }
3991 
3992     private static void checkLoop0(MethodHandle[][] clauses) {
3993         if (clauses == null || clauses.length == 0) {
3994             throw newIllegalArgumentException("null or no clauses passed");
3995         }
3996         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
3997             throw newIllegalArgumentException("null clauses are not allowed");
3998         }
3999         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
4000             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
4001         }
4002     }
4003 
4004     private static void checkLoop1a(int i, MethodHandle in, MethodHandle st) {
4005         if (in.type().returnType() != st.type().returnType()) {
4006             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
4007                     st.type().returnType());
4008         }
4009     }
4010 
4011     private static void checkLoop1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
4012         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::parameterList).
4013                 anyMatch(pl -> !pl.equals(commonSuffix.subList(0, pl.size())))) {
4014             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
4015                     " (common suffix: " + commonSuffix + ")");
4016         }
4017     }
4018 
4019     private static void checkLoop1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
4020         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
4021                 anyMatch(t -> t != loopReturnType)) {
4022             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
4023                     loopReturnType + ")");
4024         }
4025 
4026         if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
4027             throw newIllegalArgumentException("no predicate found", pred);
4028         }
4029         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
4030                 anyMatch(t -> t != boolean.class)) {
4031             throw newIllegalArgumentException("predicates must have boolean return type", pred);
4032         }
4033     }
4034 
4035     private static void checkLoop2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
4036         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
4037                 map(MethodType::parameterList).anyMatch(pl -> !pl.equals(commonParameterSequence.subList(0, pl.size())))) {
4038             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
4039                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
4040         }
4041     }
4042 
4043     private static void checkIteratedLoop(MethodHandle body) {
4044         if (null == body) {
4045             throw newIllegalArgumentException("iterated loop body must not be null");
4046         }
4047     }
4048 
4049     private static void checkTryFinally(MethodHandle target, MethodHandle cleanup) {
4050         Class<?> rtype = target.type().returnType();
4051         if (rtype != cleanup.type().returnType()) {
4052             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
4053         }
4054         List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
4055         if (!Throwable.class.isAssignableFrom(cleanupParamTypes.get(0))) {
4056             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
4057         }
4058         if (rtype != void.class && cleanupParamTypes.get(1) != rtype) {
4059             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
4060         }
4061         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
4062         // target parameter list.
4063         int cleanupArgIndex = rtype == void.class ? 1 : 2;
4064         if (!cleanupParamTypes.subList(cleanupArgIndex, cleanupParamTypes.size()).
4065                 equals(target.type().parameterList().subList(0, cleanupParamTypes.size() - cleanupArgIndex))) {
4066             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
4067                     cleanup.type(), target.type());
4068         }
4069     }
4070 
4071 }
--- EOF ---