1 /*
   2  * Copyright (c) 2008, 2014, 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.List;
  30 import java.util.ArrayList;
  31 import java.util.Arrays;
  32 
  33 import sun.invoke.util.ValueConversions;
  34 import sun.invoke.util.VerifyAccess;
  35 import sun.invoke.util.Wrapper;
  36 import sun.reflect.CallerSensitive;
  37 import sun.reflect.Reflection;
  38 import sun.reflect.misc.ReflectUtil;
  39 import sun.security.util.SecurityConstants;
  40 import java.lang.invoke.LambdaForm.BasicType;
  41 import static java.lang.invoke.LambdaForm.BasicType.*;
  42 import static java.lang.invoke.MethodHandleStatics.*;
  43 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  44 import java.util.concurrent.ConcurrentHashMap;
  45 
  46 /**
  47  * This class consists exclusively of static methods that operate on or return
  48  * method handles. They fall into several categories:
  49  * <ul>
  50  * <li>Lookup methods which help create method handles for methods and fields.
  51  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  52  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  53  * </ul>
  54  *
  55  * @author John Rose, JSR 292 EG
  56  * @since 1.7
  57  */
  58 public class MethodHandles {
  59 
  60     private MethodHandles() { }  // do not instantiate
  61 
  62     private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  63     static { MethodHandleImpl.initStatics(); }
  64     // See IMPL_LOOKUP below.
  65 
  66     //// Method handle creation from ordinary methods.
  67 
  68     /**
  69      * Returns a {@link Lookup lookup object} with
  70      * full capabilities to emulate all supported bytecode behaviors of the caller.
  71      * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller.
  72      * Factory methods on the lookup object can create
  73      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
  74      * for any member that the caller has access to via bytecodes,
  75      * including protected and private fields and methods.
  76      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
  77      * Do not store it in place where untrusted code can access it.
  78      * <p>
  79      * This method is caller sensitive, which means that it may return different
  80      * values to different callers.
  81      * <p>
  82      * For any given caller class {@code C}, the lookup object returned by this call
  83      * has equivalent capabilities to any lookup object
  84      * supplied by the JVM to the bootstrap method of an
  85      * <a href="package-summary.html#indyinsn">invokedynamic instruction</a>
  86      * executing in the same caller class {@code C}.
  87      * @return a lookup object for the caller of this method, with private access
  88      */
  89     @CallerSensitive
  90     public static Lookup lookup() {
  91         return new Lookup(Reflection.getCallerClass());
  92     }
  93 
  94     /**
  95      * Returns a {@link Lookup lookup object} which is trusted minimally.
  96      * It can only be used to create method handles to
  97      * publicly accessible fields and methods.
  98      * <p>
  99      * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class}
 100      * of this lookup object will be {@link java.lang.Object}.
 101      *
 102      * <p style="font-size:smaller;">
 103      * <em>Discussion:</em>
 104      * The lookup class can be changed to any other class {@code C} using an expression of the form
 105      * {@link Lookup#in publicLookup().in(C.class)}.
 106      * Since all classes have equal access to public names,
 107      * such a change would confer no new access rights.
 108      * A public lookup object is always subject to
 109      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 110      * Also, it cannot access
 111      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 112      * @return a lookup object which is trusted minimally
 113      */
 114     public static Lookup publicLookup() {
 115         return Lookup.PUBLIC_LOOKUP;
 116     }
 117 
 118     /**
 119      * Performs an unchecked "crack" of a
 120      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 121      * The result is as if the user had obtained a lookup object capable enough
 122      * to crack the target method handle, called
 123      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 124      * on the target to obtain its symbolic reference, and then called
 125      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 126      * to resolve the symbolic reference to a member.
 127      * <p>
 128      * If there is a security manager, its {@code checkPermission} method
 129      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 130      * @param <T> the desired type of the result, either {@link Member} or a subtype
 131      * @param target a direct method handle to crack into symbolic reference components
 132      * @param expected a class object representing the desired result type {@code T}
 133      * @return a reference to the method, constructor, or field object
 134      * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
 135      * @exception NullPointerException if either argument is {@code null}
 136      * @exception IllegalArgumentException if the target is not a direct method handle
 137      * @exception ClassCastException if the member is not of the expected type
 138      * @since 1.8
 139      */
 140     public static <T extends Member> T
 141     reflectAs(Class<T> expected, MethodHandle target) {
 142         SecurityManager smgr = System.getSecurityManager();
 143         if (smgr != null)  smgr.checkPermission(ACCESS_PERMISSION);
 144         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 145         return lookup.revealDirect(target).reflectAs(expected, lookup);
 146     }
 147     // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
 148     static final private java.security.Permission ACCESS_PERMISSION =
 149         new ReflectPermission("suppressAccessChecks");
 150 
 151     /**
 152      * A <em>lookup object</em> is a factory for creating method handles,
 153      * when the creation requires access checking.
 154      * Method handles do not perform
 155      * access checks when they are called, but rather when they are created.
 156      * Therefore, method handle access
 157      * restrictions must be enforced when a method handle is created.
 158      * The caller class against which those restrictions are enforced
 159      * is known as the {@linkplain #lookupClass lookup class}.
 160      * <p>
 161      * A lookup class which needs to create method handles will call
 162      * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself.
 163      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 164      * determined, and securely stored in the {@code Lookup} object.
 165      * The lookup class (or its delegates) may then use factory methods
 166      * on the {@code Lookup} object to create method handles for access-checked members.
 167      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 168      * even private ones.
 169      *
 170      * <h1><a name="lookups"></a>Lookup Factory Methods</h1>
 171      * The factory methods on a {@code Lookup} object correspond to all major
 172      * use cases for methods, constructors, and fields.
 173      * Each method handle created by a factory method is the functional
 174      * equivalent of a particular <em>bytecode behavior</em>.
 175      * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
 176      * Here is a summary of the correspondence between these factory methods and
 177      * the behavior the resulting method handles:
 178      * <table border=1 cellpadding=5 summary="lookup method behaviors">
 179      * <tr>
 180      *     <th><a name="equiv"></a>lookup expression</th>
 181      *     <th>member</th>
 182      *     <th>bytecode behavior</th>
 183      * </tr>
 184      * <tr>
 185      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td>
 186      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 187      * </tr>
 188      * <tr>
 189      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td>
 190      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
 191      * </tr>
 192      * <tr>
 193      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td>
 194      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 195      * </tr>
 196      * <tr>
 197      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td>
 198      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 199      * </tr>
 200      * <tr>
 201      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td>
 202      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 203      * </tr>
 204      * <tr>
 205      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td>
 206      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 207      * </tr>
 208      * <tr>
 209      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td>
 210      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 211      * </tr>
 212      * <tr>
 213      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td>
 214      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 215      * </tr>
 216      * <tr>
 217      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td>
 218      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 219      * </tr>
 220      * <tr>
 221      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td>
 222      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 223      * </tr>
 224      * <tr>
 225      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
 226      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 227      * </tr>
 228      * <tr>
 229      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td>
 230      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 231      * </tr>
 232      * <tr>
 233      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
 234      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 235      * </tr>
 236      * </table>
 237      *
 238      * Here, the type {@code C} is the class or interface being searched for a member,
 239      * documented as a parameter named {@code refc} in the lookup methods.
 240      * The method type {@code MT} is composed from the return type {@code T}
 241      * and the sequence of argument types {@code A*}.
 242      * The constructor also has a sequence of argument types {@code A*} and
 243      * is deemed to return the newly-created object of type {@code C}.
 244      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 245      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 246      * if it is present, it is always the leading argument to the method handle invocation.
 247      * (In the case of some {@code protected} members, {@code this} may be
 248      * restricted in type to the lookup class; see below.)
 249      * The name {@code arg} stands for all the other method handle arguments.
 250      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 251      * stands for a null reference if the accessed method or field is static,
 252      * and {@code this} otherwise.
 253      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 254      * for reflective objects corresponding to the given members.
 255      * <p>
 256      * In cases where the given member is of variable arity (i.e., a method or constructor)
 257      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 258      * In all other cases, the returned method handle will be of fixed arity.
 259      * <p style="font-size:smaller;">
 260      * <em>Discussion:</em>
 261      * The equivalence between looked-up method handles and underlying
 262      * class members and bytecode behaviors
 263      * can break down in a few ways:
 264      * <ul style="font-size:smaller;">
 265      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 266      * the lookup can still succeed, even when there is no equivalent
 267      * Java expression or bytecoded constant.
 268      * <li>Likewise, if {@code T} or {@code MT}
 269      * is not symbolically accessible from the lookup class's loader,
 270      * the lookup can still succeed.
 271      * For example, lookups for {@code MethodHandle.invokeExact} and
 272      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 273      * <li>If there is a security manager installed, it can forbid the lookup
 274      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 275      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 276      * constant is not subject to security manager checks.
 277      * <li>If the looked-up method has a
 278      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 279      * the method handle creation may fail, due to the method handle
 280      * type having too many parameters.
 281      * </ul>
 282      *
 283      * <h1><a name="access"></a>Access checking</h1>
 284      * Access checks are applied in the factory methods of {@code Lookup},
 285      * when a method handle is created.
 286      * This is a key difference from the Core Reflection API, since
 287      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 288      * performs access checking against every caller, on every call.
 289      * <p>
 290      * All access checks start from a {@code Lookup} object, which
 291      * compares its recorded lookup class against all requests to
 292      * create method handles.
 293      * A single {@code Lookup} object can be used to create any number
 294      * of access-checked method handles, all checked against a single
 295      * lookup class.
 296      * <p>
 297      * A {@code Lookup} object can be shared with other trusted code,
 298      * such as a metaobject protocol.
 299      * A shared {@code Lookup} object delegates the capability
 300      * to create method handles on private members of the lookup class.
 301      * Even if privileged code uses the {@code Lookup} object,
 302      * the access checking is confined to the privileges of the
 303      * original lookup class.
 304      * <p>
 305      * A lookup can fail, because
 306      * the containing class is not accessible to the lookup class, or
 307      * because the desired class member is missing, or because the
 308      * desired class member is not accessible to the lookup class, or
 309      * because the lookup object is not trusted enough to access the member.
 310      * In any of these cases, a {@code ReflectiveOperationException} will be
 311      * thrown from the attempted lookup.  The exact class will be one of
 312      * the following:
 313      * <ul>
 314      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 315      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 316      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 317      * </ul>
 318      * <p>
 319      * In general, the conditions under which a method handle may be
 320      * looked up for a method {@code M} are no more restrictive than the conditions
 321      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 322      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 323      * a method handle lookup will generally raise a corresponding
 324      * checked exception, such as {@code NoSuchMethodException}.
 325      * And the effect of invoking the method handle resulting from the lookup
 326      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 327      * to executing the compiled, verified, and resolved call to {@code M}.
 328      * The same point is true of fields and constructors.
 329      * <p style="font-size:smaller;">
 330      * <em>Discussion:</em>
 331      * Access checks only apply to named and reflected methods,
 332      * constructors, and fields.
 333      * Other method handle creation methods, such as
 334      * {@link MethodHandle#asType MethodHandle.asType},
 335      * do not require any access checks, and are used
 336      * independently of any {@code Lookup} object.
 337      * <p>
 338      * If the desired member is {@code protected}, the usual JVM rules apply,
 339      * including the requirement that the lookup class must be either be in the
 340      * same package as the desired member, or must inherit that member.
 341      * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.)
 342      * In addition, if the desired member is a non-static field or method
 343      * in a different package, the resulting method handle may only be applied
 344      * to objects of the lookup class or one of its subclasses.
 345      * This requirement is enforced by narrowing the type of the leading
 346      * {@code this} parameter from {@code C}
 347      * (which will necessarily be a superclass of the lookup class)
 348      * to the lookup class itself.
 349      * <p>
 350      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 351      * that the receiver argument must match both the resolved method <em>and</em>
 352      * the current class.  Again, this requirement is enforced by narrowing the
 353      * type of the leading parameter to the resulting method handle.
 354      * (See the Java Virtual Machine Specification, section 4.10.1.9.)
 355      * <p>
 356      * The JVM represents constructors and static initializer blocks as internal methods
 357      * with special names ({@code "<init>"} and {@code "<clinit>"}).
 358      * The internal syntax of invocation instructions allows them to refer to such internal
 359      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 360      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 361      * <p>
 362      * In some cases, access between nested classes is obtained by the Java compiler by creating
 363      * an wrapper method to access a private method of another class
 364      * in the same top-level declaration.
 365      * For example, a nested class {@code C.D}
 366      * can access private members within other related classes such as
 367      * {@code C}, {@code C.D.E}, or {@code C.B},
 368      * but the Java compiler may need to generate wrapper methods in
 369      * those related classes.  In such cases, a {@code Lookup} object on
 370      * {@code C.E} would be unable to those private members.
 371      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 372      * which can transform a lookup on {@code C.E} into one on any of those other
 373      * classes, without special elevation of privilege.
 374      * <p>
 375      * The accesses permitted to a given lookup object may be limited,
 376      * according to its set of {@link #lookupModes lookupModes},
 377      * to a subset of members normally accessible to the lookup class.
 378      * For example, the {@link MethodHandles#publicLookup publicLookup}
 379      * method produces a lookup object which is only allowed to access
 380      * public members in public classes.
 381      * The caller sensitive method {@link MethodHandles#lookup lookup}
 382      * produces a lookup object with full capabilities relative to
 383      * its caller class, to emulate all supported bytecode behaviors.
 384      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 385      * with fewer access modes than the original lookup object.
 386      *
 387      * <p style="font-size:smaller;">
 388      * <a name="privacc"></a>
 389      * <em>Discussion of private access:</em>
 390      * We say that a lookup has <em>private access</em>
 391      * if its {@linkplain #lookupModes lookup modes}
 392      * include the possibility of accessing {@code private} members.
 393      * As documented in the relevant methods elsewhere,
 394      * only lookups with private access possess the following capabilities:
 395      * <ul style="font-size:smaller;">
 396      * <li>access private fields, methods, and constructors of the lookup class
 397      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 398      *     such as {@code Class.forName}
 399      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 400      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 401      *     for classes accessible to the lookup class
 402      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 403      *     within the same package member
 404      * </ul>
 405      * <p style="font-size:smaller;">
 406      * Each of these permissions is a consequence of the fact that a lookup object
 407      * with private access can be securely traced back to an originating class,
 408      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 409      * can be reliably determined and emulated by method handles.
 410      *
 411      * <h1><a name="secmgr"></a>Security manager interactions</h1>
 412      * Although bytecode instructions can only refer to classes in
 413      * a related class loader, this API can search for methods in any
 414      * class, as long as a reference to its {@code Class} object is
 415      * available.  Such cross-loader references are also possible with the
 416      * Core Reflection API, and are impossible to bytecode instructions
 417      * such as {@code invokestatic} or {@code getfield}.
 418      * There is a {@linkplain java.lang.SecurityManager security manager API}
 419      * to allow applications to check such cross-loader references.
 420      * These checks apply to both the {@code MethodHandles.Lookup} API
 421      * and the Core Reflection API
 422      * (as found on {@link java.lang.Class Class}).
 423      * <p>
 424      * If a security manager is present, member lookups are subject to
 425      * additional checks.
 426      * From one to three calls are made to the security manager.
 427      * Any of these calls can refuse access by throwing a
 428      * {@link java.lang.SecurityException SecurityException}.
 429      * Define {@code smgr} as the security manager,
 430      * {@code lookc} as the lookup class of the current lookup object,
 431      * {@code refc} as the containing class in which the member
 432      * is being sought, and {@code defc} as the class in which the
 433      * member is actually defined.
 434      * The value {@code lookc} is defined as <em>not present</em>
 435      * if the current lookup object does not have
 436      * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 437      * The calls are made according to the following rules:
 438      * <ul>
 439      * <li><b>Step 1:</b>
 440      *     If {@code lookc} is not present, or if its class loader is not
 441      *     the same as or an ancestor of the class loader of {@code refc},
 442      *     then {@link SecurityManager#checkPackageAccess
 443      *     smgr.checkPackageAccess(refcPkg)} is called,
 444      *     where {@code refcPkg} is the package of {@code refc}.
 445      * <li><b>Step 2:</b>
 446      *     If the retrieved member is not public and
 447      *     {@code lookc} is not present, then
 448      *     {@link SecurityManager#checkPermission smgr.checkPermission}
 449      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
 450      * <li><b>Step 3:</b>
 451      *     If the retrieved member is not public,
 452      *     and if {@code lookc} is not present,
 453      *     and if {@code defc} and {@code refc} are different,
 454      *     then {@link SecurityManager#checkPackageAccess
 455      *     smgr.checkPackageAccess(defcPkg)} is called,
 456      *     where {@code defcPkg} is the package of {@code defc}.
 457      * </ul>
 458      * Security checks are performed after other access checks have passed.
 459      * Therefore, the above rules presuppose a member that is public,
 460      * or else that is being accessed from a lookup class that has
 461      * rights to access the member.
 462      *
 463      * <h1><a name="callsens"></a>Caller sensitive methods</h1>
 464      * A small number of Java methods have a special property called caller sensitivity.
 465      * A <em>caller-sensitive</em> method can behave differently depending on the
 466      * identity of its immediate caller.
 467      * <p>
 468      * If a method handle for a caller-sensitive method is requested,
 469      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
 470      * but they take account of the lookup class in a special way.
 471      * The resulting method handle behaves as if it were called
 472      * from an instruction contained in the lookup class,
 473      * so that the caller-sensitive method detects the lookup class.
 474      * (By contrast, the invoker of the method handle is disregarded.)
 475      * Thus, in the case of caller-sensitive methods,
 476      * different lookup classes may give rise to
 477      * differently behaving method handles.
 478      * <p>
 479      * In cases where the lookup object is
 480      * {@link MethodHandles#publicLookup() publicLookup()},
 481      * or some other lookup object without
 482      * <a href="MethodHandles.Lookup.html#privacc">private access</a>,
 483      * the lookup class is disregarded.
 484      * In such cases, no caller-sensitive method handle can be created,
 485      * access is forbidden, and the lookup fails with an
 486      * {@code IllegalAccessException}.
 487      * <p style="font-size:smaller;">
 488      * <em>Discussion:</em>
 489      * For example, the caller-sensitive method
 490      * {@link java.lang.Class#forName(String) Class.forName(x)}
 491      * can return varying classes or throw varying exceptions,
 492      * depending on the class loader of the class that calls it.
 493      * A public lookup of {@code Class.forName} will fail, because
 494      * there is no reasonable way to determine its bytecode behavior.
 495      * <p style="font-size:smaller;">
 496      * If an application caches method handles for broad sharing,
 497      * it should use {@code publicLookup()} to create them.
 498      * If there is a lookup of {@code Class.forName}, it will fail,
 499      * and the application must take appropriate action in that case.
 500      * It may be that a later lookup, perhaps during the invocation of a
 501      * bootstrap method, can incorporate the specific identity
 502      * of the caller, making the method accessible.
 503      * <p style="font-size:smaller;">
 504      * The function {@code MethodHandles.lookup} is caller sensitive
 505      * so that there can be a secure foundation for lookups.
 506      * Nearly all other methods in the JSR 292 API rely on lookup
 507      * objects to check access requests.
 508      */
 509     public static final
 510     class Lookup {
 511         /** The class on behalf of whom the lookup is being performed. */
 512         private final Class<?> lookupClass;
 513 
 514         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
 515         private final int allowedModes;
 516 
 517         /** A single-bit mask representing {@code public} access,
 518          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 519          *  The value, {@code 0x01}, happens to be the same as the value of the
 520          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
 521          */
 522         public static final int PUBLIC = Modifier.PUBLIC;
 523 
 524         /** A single-bit mask representing {@code private} access,
 525          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 526          *  The value, {@code 0x02}, happens to be the same as the value of the
 527          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
 528          */
 529         public static final int PRIVATE = Modifier.PRIVATE;
 530 
 531         /** A single-bit mask representing {@code protected} access,
 532          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 533          *  The value, {@code 0x04}, happens to be the same as the value of the
 534          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
 535          */
 536         public static final int PROTECTED = Modifier.PROTECTED;
 537 
 538         /** A single-bit mask representing {@code package} access (default access),
 539          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 540          *  The value is {@code 0x08}, which does not correspond meaningfully to
 541          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
 542          */
 543         public static final int PACKAGE = Modifier.STATIC;
 544 
 545         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE);
 546         private static final int TRUSTED   = -1;
 547 
 548         private static int fixmods(int mods) {
 549             mods &= (ALL_MODES - PACKAGE);
 550             return (mods != 0) ? mods : PACKAGE;
 551         }
 552 
 553         /** Tells which class is performing the lookup.  It is this class against
 554          *  which checks are performed for visibility and access permissions.
 555          *  <p>
 556          *  The class implies a maximum level of access permission,
 557          *  but the permissions may be additionally limited by the bitmask
 558          *  {@link #lookupModes lookupModes}, which controls whether non-public members
 559          *  can be accessed.
 560          *  @return the lookup class, on behalf of which this lookup object finds members
 561          */
 562         public Class<?> lookupClass() {
 563             return lookupClass;
 564         }
 565 
 566         // This is just for calling out to MethodHandleImpl.
 567         private Class<?> lookupClassOrNull() {
 568             return (allowedModes == TRUSTED) ? null : lookupClass;
 569         }
 570 
 571         /** Tells which access-protection classes of members this lookup object can produce.
 572          *  The result is a bit-mask of the bits
 573          *  {@linkplain #PUBLIC PUBLIC (0x01)},
 574          *  {@linkplain #PRIVATE PRIVATE (0x02)},
 575          *  {@linkplain #PROTECTED PROTECTED (0x04)},
 576          *  and {@linkplain #PACKAGE PACKAGE (0x08)}.
 577          *  <p>
 578          *  A freshly-created lookup object
 579          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
 580          *  has all possible bits set, since the caller class can access all its own members.
 581          *  A lookup object on a new lookup class
 582          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
 583          *  may have some mode bits set to zero.
 584          *  The purpose of this is to restrict access via the new lookup object,
 585          *  so that it can access only names which can be reached by the original
 586          *  lookup object, and also by the new lookup class.
 587          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
 588          */
 589         public int lookupModes() {
 590             return allowedModes & ALL_MODES;
 591         }
 592 
 593         /** Embody the current class (the lookupClass) as a lookup class
 594          * for method handle creation.
 595          * Must be called by from a method in this package,
 596          * which in turn is called by a method not in this package.
 597          */
 598         Lookup(Class<?> lookupClass) {
 599             this(lookupClass, ALL_MODES);
 600             // make sure we haven't accidentally picked up a privileged class:
 601             checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
 602         }
 603 
 604         private Lookup(Class<?> lookupClass, int allowedModes) {
 605             this.lookupClass = lookupClass;
 606             this.allowedModes = allowedModes;
 607         }
 608 
 609         /**
 610          * Creates a lookup on the specified new lookup class.
 611          * The resulting object will report the specified
 612          * class as its own {@link #lookupClass lookupClass}.
 613          * <p>
 614          * However, the resulting {@code Lookup} object is guaranteed
 615          * to have no more access capabilities than the original.
 616          * In particular, access capabilities can be lost as follows:<ul>
 617          * <li>If the new lookup class differs from the old one,
 618          * protected members will not be accessible by virtue of inheritance.
 619          * (Protected members may continue to be accessible because of package sharing.)
 620          * <li>If the new lookup class is in a different package
 621          * than the old one, protected and default (package) members will not be accessible.
 622          * <li>If the new lookup class is not within the same package member
 623          * as the old one, private members will not be accessible.
 624          * <li>If the new lookup class is not accessible to the old lookup class,
 625          * then no members, not even public members, will be accessible.
 626          * (In all other cases, public members will continue to be accessible.)
 627          * </ul>
 628          *
 629          * @param requestedLookupClass the desired lookup class for the new lookup object
 630          * @return a lookup object which reports the desired lookup class
 631          * @throws NullPointerException if the argument is null
 632          */
 633         public Lookup in(Class<?> requestedLookupClass) {
 634             requestedLookupClass.getClass();  // null check
 635             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
 636                 return new Lookup(requestedLookupClass, ALL_MODES);
 637             if (requestedLookupClass == this.lookupClass)
 638                 return this;  // keep same capabilities
 639             int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
 640             if ((newModes & PACKAGE) != 0
 641                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
 642                 newModes &= ~(PACKAGE|PRIVATE);
 643             }
 644             // Allow nestmate lookups to be created without special privilege:
 645             if ((newModes & PRIVATE) != 0
 646                 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
 647                 newModes &= ~PRIVATE;
 648             }
 649             if ((newModes & PUBLIC) != 0
 650                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
 651                 // The requested class it not accessible from the lookup class.
 652                 // No permissions.
 653                 newModes = 0;
 654             }
 655             checkUnprivilegedlookupClass(requestedLookupClass, newModes);
 656             return new Lookup(requestedLookupClass, newModes);
 657         }
 658 
 659         // Make sure outer class is initialized first.
 660         static { IMPL_NAMES.getClass(); }
 661 
 662         /** Version of lookup which is trusted minimally.
 663          *  It can only be used to create method handles to
 664          *  publicly accessible members.
 665          */
 666         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, PUBLIC);
 667 
 668         /** Package-private version of lookup which is trusted. */
 669         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
 670 
 671         private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) {
 672             String name = lookupClass.getName();
 673             if (name.startsWith("java.lang.invoke."))
 674                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
 675 
 676             // For caller-sensitive MethodHandles.lookup()
 677             // disallow lookup more restricted packages
 678             if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) {
 679                 if (name.startsWith("java.") ||
 680                         (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) {
 681                     throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
 682                 }
 683             }
 684         }
 685 
 686         /**
 687          * Displays the name of the class from which lookups are to be made.
 688          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
 689          * If there are restrictions on the access permitted to this lookup,
 690          * this is indicated by adding a suffix to the class name, consisting
 691          * of a slash and a keyword.  The keyword represents the strongest
 692          * allowed access, and is chosen as follows:
 693          * <ul>
 694          * <li>If no access is allowed, the suffix is "/noaccess".
 695          * <li>If only public access is allowed, the suffix is "/public".
 696          * <li>If only public and package access are allowed, the suffix is "/package".
 697          * <li>If only public, package, and private access are allowed, the suffix is "/private".
 698          * </ul>
 699          * If none of the above cases apply, it is the case that full
 700          * access (public, package, private, and protected) is allowed.
 701          * In this case, no suffix is added.
 702          * This is true only of an object obtained originally from
 703          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
 704          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
 705          * always have restricted access, and will display a suffix.
 706          * <p>
 707          * (It may seem strange that protected access should be
 708          * stronger than private access.  Viewed independently from
 709          * package access, protected access is the first to be lost,
 710          * because it requires a direct subclass relationship between
 711          * caller and callee.)
 712          * @see #in
 713          */
 714         @Override
 715         public String toString() {
 716             String cname = lookupClass.getName();
 717             switch (allowedModes) {
 718             case 0:  // no privileges
 719                 return cname + "/noaccess";
 720             case PUBLIC:
 721                 return cname + "/public";
 722             case PUBLIC|PACKAGE:
 723                 return cname + "/package";
 724             case ALL_MODES & ~PROTECTED:
 725                 return cname + "/private";
 726             case ALL_MODES:
 727                 return cname;
 728             case TRUSTED:
 729                 return "/trusted";  // internal only; not exported
 730             default:  // Should not happen, but it's a bitfield...
 731                 cname = cname + "/" + Integer.toHexString(allowedModes);
 732                 assert(false) : cname;
 733                 return cname;
 734             }
 735         }
 736 
 737         /**
 738          * Produces a method handle for a static method.
 739          * The type of the method handle will be that of the method.
 740          * (Since static methods do not take receivers, there is no
 741          * additional receiver argument inserted into the method handle type,
 742          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
 743          * The method and all its argument types must be accessible to the lookup object.
 744          * <p>
 745          * The returned method handle will have
 746          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 747          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 748          * <p>
 749          * If the returned method handle is invoked, the method's class will
 750          * be initialized, if it has not already been initialized.
 751          * <p><b>Example:</b>
 752          * <blockquote><pre>{@code
 753 import static java.lang.invoke.MethodHandles.*;
 754 import static java.lang.invoke.MethodType.*;
 755 ...
 756 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
 757   "asList", methodType(List.class, Object[].class));
 758 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
 759          * }</pre></blockquote>
 760          * @param refc the class from which the method is accessed
 761          * @param name the name of the method
 762          * @param type the type of the method
 763          * @return the desired method handle
 764          * @throws NoSuchMethodException if the method does not exist
 765          * @throws IllegalAccessException if access checking fails,
 766          *                                or if the method is not {@code static},
 767          *                                or if the method's variable arity modifier bit
 768          *                                is set and {@code asVarargsCollector} fails
 769          * @exception SecurityException if a security manager is present and it
 770          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 771          * @throws NullPointerException if any argument is null
 772          */
 773         public
 774         MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 775             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
 776             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method));
 777         }
 778 
 779         /**
 780          * Produces a method handle for a virtual method.
 781          * The type of the method handle will be that of the method,
 782          * with the receiver type (usually {@code refc}) prepended.
 783          * The method and all its argument types must be accessible to the lookup object.
 784          * <p>
 785          * When called, the handle will treat the first argument as a receiver
 786          * and dispatch on the receiver's type to determine which method
 787          * implementation to enter.
 788          * (The dispatching action is identical with that performed by an
 789          * {@code invokevirtual} or {@code invokeinterface} instruction.)
 790          * <p>
 791          * The first argument will be of type {@code refc} if the lookup
 792          * class has full privileges to access the member.  Otherwise
 793          * the member must be {@code protected} and the first argument
 794          * will be restricted in type to the lookup class.
 795          * <p>
 796          * The returned method handle will have
 797          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 798          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 799          * <p>
 800          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
 801          * instructions and method handles produced by {@code findVirtual},
 802          * if the class is {@code MethodHandle} and the name string is
 803          * {@code invokeExact} or {@code invoke}, the resulting
 804          * method handle is equivalent to one produced by
 805          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
 806          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
 807          * with the same {@code type} argument.
 808          *
 809          * <b>Example:</b>
 810          * <blockquote><pre>{@code
 811 import static java.lang.invoke.MethodHandles.*;
 812 import static java.lang.invoke.MethodType.*;
 813 ...
 814 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
 815   "concat", methodType(String.class, String.class));
 816 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
 817   "hashCode", methodType(int.class));
 818 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
 819   "hashCode", methodType(int.class));
 820 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
 821 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
 822 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
 823 // interface method:
 824 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
 825   "subSequence", methodType(CharSequence.class, int.class, int.class));
 826 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
 827 // constructor "internal method" must be accessed differently:
 828 MethodType MT_newString = methodType(void.class); //()V for new String()
 829 try { assertEquals("impossible", lookup()
 830         .findVirtual(String.class, "<init>", MT_newString));
 831  } catch (NoSuchMethodException ex) { } // OK
 832 MethodHandle MH_newString = publicLookup()
 833   .findConstructor(String.class, MT_newString);
 834 assertEquals("", (String) MH_newString.invokeExact());
 835          * }</pre></blockquote>
 836          *
 837          * @param refc the class or interface from which the method is accessed
 838          * @param name the name of the method
 839          * @param type the type of the method, with the receiver argument omitted
 840          * @return the desired method handle
 841          * @throws NoSuchMethodException if the method does not exist
 842          * @throws IllegalAccessException if access checking fails,
 843          *                                or if the method is {@code static}
 844          *                                or if the method's variable arity modifier bit
 845          *                                is set and {@code asVarargsCollector} fails
 846          * @exception SecurityException if a security manager is present and it
 847          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 848          * @throws NullPointerException if any argument is null
 849          */
 850         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 851             if (refc == MethodHandle.class) {
 852                 MethodHandle mh = findVirtualForMH(name, type);
 853                 if (mh != null)  return mh;
 854             }
 855             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
 856             MemberName method = resolveOrFail(refKind, refc, name, type);
 857             return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
 858         }
 859         private MethodHandle findVirtualForMH(String name, MethodType type) {
 860             // these names require special lookups because of the implicit MethodType argument
 861             if ("invoke".equals(name))
 862                 return invoker(type);
 863             if ("invokeExact".equals(name))
 864                 return exactInvoker(type);
 865             if ("invokeBasic".equals(name))
 866                 return basicInvoker(type);
 867             assert(!MemberName.isMethodHandleInvokeName(name));
 868             return null;
 869         }
 870 
 871         /**
 872          * Produces a method handle which creates an object and initializes it, using
 873          * the constructor of the specified type.
 874          * The parameter types of the method handle will be those of the constructor,
 875          * while the return type will be a reference to the constructor's class.
 876          * The constructor and all its argument types must be accessible to the lookup object.
 877          * <p>
 878          * The requested type must have a return type of {@code void}.
 879          * (This is consistent with the JVM's treatment of constructor type descriptors.)
 880          * <p>
 881          * The returned method handle will have
 882          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 883          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
 884          * <p>
 885          * If the returned method handle is invoked, the constructor's class will
 886          * be initialized, if it has not already been initialized.
 887          * <p><b>Example:</b>
 888          * <blockquote><pre>{@code
 889 import static java.lang.invoke.MethodHandles.*;
 890 import static java.lang.invoke.MethodType.*;
 891 ...
 892 MethodHandle MH_newArrayList = publicLookup().findConstructor(
 893   ArrayList.class, methodType(void.class, Collection.class));
 894 Collection orig = Arrays.asList("x", "y");
 895 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
 896 assert(orig != copy);
 897 assertEquals(orig, copy);
 898 // a variable-arity constructor:
 899 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
 900   ProcessBuilder.class, methodType(void.class, String[].class));
 901 ProcessBuilder pb = (ProcessBuilder)
 902   MH_newProcessBuilder.invoke("x", "y", "z");
 903 assertEquals("[x, y, z]", pb.command().toString());
 904          * }</pre></blockquote>
 905          * @param refc the class or interface from which the method is accessed
 906          * @param type the type of the method, with the receiver argument omitted, and a void return type
 907          * @return the desired method handle
 908          * @throws NoSuchMethodException if the constructor does not exist
 909          * @throws IllegalAccessException if access checking fails
 910          *                                or if the method's variable arity modifier bit
 911          *                                is set and {@code asVarargsCollector} fails
 912          * @exception SecurityException if a security manager is present and it
 913          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 914          * @throws NullPointerException if any argument is null
 915          */
 916         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 917             String name = "<init>";
 918             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
 919             return getDirectConstructor(refc, ctor);
 920         }
 921 
 922         /**
 923          * Produces an early-bound method handle for a virtual method.
 924          * It will bypass checks for overriding methods on the receiver,
 925          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
 926          * instruction from within the explicitly specified {@code specialCaller}.
 927          * The type of the method handle will be that of the method,
 928          * with a suitably restricted receiver type prepended.
 929          * (The receiver type will be {@code specialCaller} or a subtype.)
 930          * The method and all its argument types must be accessible
 931          * to the lookup object.
 932          * <p>
 933          * Before method resolution,
 934          * if the explicitly specified caller class is not identical with the
 935          * lookup class, or if this lookup object does not have
 936          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
 937          * privileges, the access fails.
 938          * <p>
 939          * The returned method handle will have
 940          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 941          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 942          * <p style="font-size:smaller;">
 943          * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
 944          * even though the {@code invokespecial} instruction can refer to them
 945          * in special circumstances.  Use {@link #findConstructor findConstructor}
 946          * to access instance initialization methods in a safe manner.)</em>
 947          * <p><b>Example:</b>
 948          * <blockquote><pre>{@code
 949 import static java.lang.invoke.MethodHandles.*;
 950 import static java.lang.invoke.MethodType.*;
 951 ...
 952 static class Listie extends ArrayList {
 953   public String toString() { return "[wee Listie]"; }
 954   static Lookup lookup() { return MethodHandles.lookup(); }
 955 }
 956 ...
 957 // no access to constructor via invokeSpecial:
 958 MethodHandle MH_newListie = Listie.lookup()
 959   .findConstructor(Listie.class, methodType(void.class));
 960 Listie l = (Listie) MH_newListie.invokeExact();
 961 try { assertEquals("impossible", Listie.lookup().findSpecial(
 962         Listie.class, "<init>", methodType(void.class), Listie.class));
 963  } catch (NoSuchMethodException ex) { } // OK
 964 // access to super and self methods via invokeSpecial:
 965 MethodHandle MH_super = Listie.lookup().findSpecial(
 966   ArrayList.class, "toString" , methodType(String.class), Listie.class);
 967 MethodHandle MH_this = Listie.lookup().findSpecial(
 968   Listie.class, "toString" , methodType(String.class), Listie.class);
 969 MethodHandle MH_duper = Listie.lookup().findSpecial(
 970   Object.class, "toString" , methodType(String.class), Listie.class);
 971 assertEquals("[]", (String) MH_super.invokeExact(l));
 972 assertEquals(""+l, (String) MH_this.invokeExact(l));
 973 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
 974 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
 975         String.class, "toString", methodType(String.class), Listie.class));
 976  } catch (IllegalAccessException ex) { } // OK
 977 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
 978 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
 979          * }</pre></blockquote>
 980          *
 981          * @param refc the class or interface from which the method is accessed
 982          * @param name the name of the method (which must not be "&lt;init&gt;")
 983          * @param type the type of the method, with the receiver argument omitted
 984          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
 985          * @return the desired method handle
 986          * @throws NoSuchMethodException if the method does not exist
 987          * @throws IllegalAccessException if access checking fails
 988          *                                or if the method's variable arity modifier bit
 989          *                                is set and {@code asVarargsCollector} fails
 990          * @exception SecurityException if a security manager is present and it
 991          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 992          * @throws NullPointerException if any argument is null
 993          */
 994         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
 995                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
 996             checkSpecialCaller(specialCaller);
 997             Lookup specialLookup = this.in(specialCaller);
 998             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
 999             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1000         }
1001 
1002         /**
1003          * Produces a method handle giving read access to a non-static field.
1004          * The type of the method handle will have a return type of the field's
1005          * value type.
1006          * The method handle's single argument will be the instance containing
1007          * the field.
1008          * Access checking is performed immediately on behalf of the lookup class.
1009          * @param refc the class or interface from which the method is accessed
1010          * @param name the field's name
1011          * @param type the field's type
1012          * @return a method handle which can load values from the field
1013          * @throws NoSuchFieldException if the field does not exist
1014          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1015          * @exception SecurityException if a security manager is present and it
1016          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1017          * @throws NullPointerException if any argument is null
1018          */
1019         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1020             MemberName field = resolveOrFail(REF_getField, refc, name, type);
1021             return getDirectField(REF_getField, refc, field);
1022         }
1023 
1024         /**
1025          * Produces a method handle giving write access to a non-static field.
1026          * The type of the method handle will have a void return type.
1027          * The method handle will take two arguments, the instance containing
1028          * the field, and the value to be stored.
1029          * The second argument will be of the field's value type.
1030          * Access checking is performed immediately on behalf of the lookup class.
1031          * @param refc the class or interface from which the method is accessed
1032          * @param name the field's name
1033          * @param type the field's type
1034          * @return a method handle which can store values into the field
1035          * @throws NoSuchFieldException if the field does not exist
1036          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1037          * @exception SecurityException if a security manager is present and it
1038          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1039          * @throws NullPointerException if any argument is null
1040          */
1041         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1042             MemberName field = resolveOrFail(REF_putField, refc, name, type);
1043             return getDirectField(REF_putField, refc, field);
1044         }
1045 
1046         /**
1047          * Produces a method handle giving read access to a static field.
1048          * The type of the method handle will have a return type of the field's
1049          * value type.
1050          * The method handle will take no arguments.
1051          * Access checking is performed immediately on behalf of the lookup class.
1052          * <p>
1053          * If the returned method handle is invoked, the field's class will
1054          * be initialized, if it has not already been initialized.
1055          * @param refc the class or interface from which the method is accessed
1056          * @param name the field's name
1057          * @param type the field's type
1058          * @return a method handle which can load values from the field
1059          * @throws NoSuchFieldException if the field does not exist
1060          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1061          * @exception SecurityException if a security manager is present and it
1062          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1063          * @throws NullPointerException if any argument is null
1064          */
1065         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1066             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
1067             return getDirectField(REF_getStatic, refc, field);
1068         }
1069 
1070         /**
1071          * Produces a method handle giving write access to a static field.
1072          * The type of the method handle will have a void return type.
1073          * The method handle will take a single
1074          * argument, of the field's value type, the value to be stored.
1075          * Access checking is performed immediately on behalf of the lookup class.
1076          * <p>
1077          * If the returned method handle is invoked, the field's class will
1078          * be initialized, if it has not already been initialized.
1079          * @param refc the class or interface from which the method is accessed
1080          * @param name the field's name
1081          * @param type the field's type
1082          * @return a method handle which can store values into the field
1083          * @throws NoSuchFieldException if the field does not exist
1084          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1085          * @exception SecurityException if a security manager is present and it
1086          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1087          * @throws NullPointerException if any argument is null
1088          */
1089         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1090             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
1091             return getDirectField(REF_putStatic, refc, field);
1092         }
1093 
1094         /**
1095          * Produces an early-bound method handle for a non-static method.
1096          * The receiver must have a supertype {@code defc} in which a method
1097          * of the given name and type is accessible to the lookup class.
1098          * The method and all its argument types must be accessible to the lookup object.
1099          * The type of the method handle will be that of the method,
1100          * without any insertion of an additional receiver parameter.
1101          * The given receiver will be bound into the method handle,
1102          * so that every call to the method handle will invoke the
1103          * requested method on the given receiver.
1104          * <p>
1105          * The returned method handle will have
1106          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1107          * the method's variable arity modifier bit ({@code 0x0080}) is set
1108          * <em>and</em> the trailing array argument is not the only argument.
1109          * (If the trailing array argument is the only argument,
1110          * the given receiver value will be bound to it.)
1111          * <p>
1112          * This is equivalent to the following code:
1113          * <blockquote><pre>{@code
1114 import static java.lang.invoke.MethodHandles.*;
1115 import static java.lang.invoke.MethodType.*;
1116 ...
1117 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
1118 MethodHandle mh1 = mh0.bindTo(receiver);
1119 MethodType mt1 = mh1.type();
1120 if (mh0.isVarargsCollector())
1121   mh1 = mh1.asVarargsCollector(mt1.parameterType(mt1.parameterCount()-1));
1122 return mh1;
1123          * }</pre></blockquote>
1124          * where {@code defc} is either {@code receiver.getClass()} or a super
1125          * type of that class, in which the requested method is accessible
1126          * to the lookup class.
1127          * (Note that {@code bindTo} does not preserve variable arity.)
1128          * @param receiver the object from which the method is accessed
1129          * @param name the name of the method
1130          * @param type the type of the method, with the receiver argument omitted
1131          * @return the desired method handle
1132          * @throws NoSuchMethodException if the method does not exist
1133          * @throws IllegalAccessException if access checking fails
1134          *                                or if the method's variable arity modifier bit
1135          *                                is set and {@code asVarargsCollector} fails
1136          * @exception SecurityException if a security manager is present and it
1137          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1138          * @throws NullPointerException if any argument is null
1139          * @see MethodHandle#bindTo
1140          * @see #findVirtual
1141          */
1142         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1143             Class<? extends Object> refc = receiver.getClass(); // may get NPE
1144             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
1145             MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1146             return mh.bindReceiver(receiver).setVarargs(method);
1147         }
1148 
1149         /**
1150          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1151          * to <i>m</i>, if the lookup class has permission.
1152          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
1153          * If <i>m</i> is virtual, overriding is respected on every call.
1154          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
1155          * The type of the method handle will be that of the method,
1156          * with the receiver type prepended (but only if it is non-static).
1157          * If the method's {@code accessible} flag is not set,
1158          * access checking is performed immediately on behalf of the lookup class.
1159          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
1160          * <p>
1161          * The returned method handle will have
1162          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1163          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1164          * <p>
1165          * If <i>m</i> is static, and
1166          * if the returned method handle is invoked, the method's class will
1167          * be initialized, if it has not already been initialized.
1168          * @param m the reflected method
1169          * @return a method handle which can invoke the reflected method
1170          * @throws IllegalAccessException if access checking fails
1171          *                                or if the method's variable arity modifier bit
1172          *                                is set and {@code asVarargsCollector} fails
1173          * @throws NullPointerException if the argument is null
1174          */
1175         public MethodHandle unreflect(Method m) throws IllegalAccessException {
1176             if (m.getDeclaringClass() == MethodHandle.class) {
1177                 MethodHandle mh = unreflectForMH(m);
1178                 if (mh != null)  return mh;
1179             }
1180             MemberName method = new MemberName(m);
1181             byte refKind = method.getReferenceKind();
1182             if (refKind == REF_invokeSpecial)
1183                 refKind = REF_invokeVirtual;
1184             assert(method.isMethod());
1185             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
1186             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
1187         }
1188         private MethodHandle unreflectForMH(Method m) {
1189             // these names require special lookups because they throw UnsupportedOperationException
1190             if (MemberName.isMethodHandleInvokeName(m.getName()))
1191                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
1192             return null;
1193         }
1194 
1195         /**
1196          * Produces a method handle for a reflected method.
1197          * It will bypass checks for overriding methods on the receiver,
1198          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1199          * instruction from within the explicitly specified {@code specialCaller}.
1200          * The type of the method handle will be that of the method,
1201          * with a suitably restricted receiver type prepended.
1202          * (The receiver type will be {@code specialCaller} or a subtype.)
1203          * If the method's {@code accessible} flag is not set,
1204          * access checking is performed immediately on behalf of the lookup class,
1205          * as if {@code invokespecial} instruction were being linked.
1206          * <p>
1207          * Before method resolution,
1208          * if the explicitly specified caller class is not identical with the
1209          * lookup class, or if this lookup object does not have
1210          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1211          * privileges, the access fails.
1212          * <p>
1213          * The returned method handle will have
1214          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1215          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1216          * @param m the reflected method
1217          * @param specialCaller the class nominally calling the method
1218          * @return a method handle which can invoke the reflected method
1219          * @throws IllegalAccessException if access checking fails
1220          *                                or if the method's variable arity modifier bit
1221          *                                is set and {@code asVarargsCollector} fails
1222          * @throws NullPointerException if any argument is null
1223          */
1224         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
1225             checkSpecialCaller(specialCaller);
1226             Lookup specialLookup = this.in(specialCaller);
1227             MemberName method = new MemberName(m, true);
1228             assert(method.isMethod());
1229             // ignore m.isAccessible:  this is a new kind of access
1230             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
1231         }
1232 
1233         /**
1234          * Produces a method handle for a reflected constructor.
1235          * The type of the method handle will be that of the constructor,
1236          * with the return type changed to the declaring class.
1237          * The method handle will perform a {@code newInstance} operation,
1238          * creating a new instance of the constructor's class on the
1239          * arguments passed to the method handle.
1240          * <p>
1241          * If the constructor's {@code accessible} flag is not set,
1242          * access checking is performed immediately on behalf of the lookup class.
1243          * <p>
1244          * The returned method handle will have
1245          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1246          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
1247          * <p>
1248          * If the returned method handle is invoked, the constructor's class will
1249          * be initialized, if it has not already been initialized.
1250          * @param c the reflected constructor
1251          * @return a method handle which can invoke the reflected constructor
1252          * @throws IllegalAccessException if access checking fails
1253          *                                or if the method's variable arity modifier bit
1254          *                                is set and {@code asVarargsCollector} fails
1255          * @throws NullPointerException if the argument is null
1256          */
1257         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
1258             MemberName ctor = new MemberName(c);
1259             assert(ctor.isConstructor());
1260             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
1261             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
1262         }
1263 
1264         /**
1265          * Produces a method handle giving read access to a reflected field.
1266          * The type of the method handle will have a return type of the field's
1267          * value type.
1268          * If the field is static, the method handle will take no arguments.
1269          * Otherwise, its single argument will be the instance containing
1270          * the field.
1271          * If the field's {@code accessible} flag is not set,
1272          * access checking is performed immediately on behalf of the lookup class.
1273          * <p>
1274          * If the field is static, and
1275          * if the returned method handle is invoked, the field's class will
1276          * be initialized, if it has not already been initialized.
1277          * @param f the reflected field
1278          * @return a method handle which can load values from the reflected field
1279          * @throws IllegalAccessException if access checking fails
1280          * @throws NullPointerException if the argument is null
1281          */
1282         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
1283             return unreflectField(f, false);
1284         }
1285         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
1286             MemberName field = new MemberName(f, isSetter);
1287             assert(isSetter
1288                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
1289                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
1290             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
1291             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
1292         }
1293 
1294         /**
1295          * Produces a method handle giving write access to a reflected field.
1296          * The type of the method handle will have a void return type.
1297          * If the field is static, the method handle will take a single
1298          * argument, of the field's value type, the value to be stored.
1299          * Otherwise, the two arguments will be the instance containing
1300          * the field, and the value to be stored.
1301          * If the field's {@code accessible} flag is not set,
1302          * access checking is performed immediately on behalf of the lookup class.
1303          * <p>
1304          * If the field is static, and
1305          * if the returned method handle is invoked, the field's class will
1306          * be initialized, if it has not already been initialized.
1307          * @param f the reflected field
1308          * @return a method handle which can store values into the reflected field
1309          * @throws IllegalAccessException if access checking fails
1310          * @throws NullPointerException if the argument is null
1311          */
1312         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
1313             return unreflectField(f, true);
1314         }
1315 
1316         /**
1317          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1318          * created by this lookup object or a similar one.
1319          * Security and access checks are performed to ensure that this lookup object
1320          * is capable of reproducing the target method handle.
1321          * This means that the cracking may fail if target is a direct method handle
1322          * but was created by an unrelated lookup object.
1323          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
1324          * and was created by a lookup object for a different class.
1325          * @param target a direct method handle to crack into symbolic reference components
1326          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
1327          * @exception SecurityException if a security manager is present and it
1328          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1329          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
1330          * @exception NullPointerException if the target is {@code null}
1331          * @see MethodHandleInfo
1332          * @since 1.8
1333          */
1334         public MethodHandleInfo revealDirect(MethodHandle target) {
1335             MemberName member = target.internalMemberName();
1336             if (member == null || (!member.isResolved() && !member.isMethodHandleInvoke()))
1337                 throw newIllegalArgumentException("not a direct method handle");
1338             Class<?> defc = member.getDeclaringClass();
1339             byte refKind = member.getReferenceKind();
1340             assert(MethodHandleNatives.refKindIsValid(refKind));
1341             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
1342                 // Devirtualized method invocation is usually formally virtual.
1343                 // To avoid creating extra MemberName objects for this common case,
1344                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
1345                 refKind = REF_invokeVirtual;
1346             if (refKind == REF_invokeVirtual && defc.isInterface())
1347                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
1348                 refKind = REF_invokeInterface;
1349             // Check SM permissions and member access before cracking.
1350             try {
1351                 checkAccess(refKind, defc, member);
1352                 checkSecurityManager(defc, member);
1353             } catch (IllegalAccessException ex) {
1354                 throw new IllegalArgumentException(ex);
1355             }
1356             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
1357                 Class<?> callerClass = target.internalCallerClass();
1358                 if (!hasPrivateAccess() || callerClass != lookupClass())
1359                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
1360             }
1361             // Produce the handle to the results.
1362             return new InfoFromMemberName(this, member, refKind);
1363         }
1364 
1365         /// Helper methods, all package-private.
1366 
1367         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1368             checkSymbolicClass(refc);  // do this before attempting to resolve
1369             name.getClass();  // NPE
1370             type.getClass();  // NPE
1371             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1372                                             NoSuchFieldException.class);
1373         }
1374 
1375         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1376             checkSymbolicClass(refc);  // do this before attempting to resolve
1377             name.getClass();  // NPE
1378             type.getClass();  // NPE
1379             checkMethodName(refKind, name);  // NPE check on name
1380             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1381                                             NoSuchMethodException.class);
1382         }
1383 
1384         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
1385             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
1386             member.getName().getClass();  // NPE
1387             member.getType().getClass();  // NPE
1388             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
1389                                             ReflectiveOperationException.class);
1390         }
1391 
1392         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
1393             refc.getClass();  // NPE
1394             Class<?> caller = lookupClassOrNull();
1395             if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes))
1396                 throw new MemberName(refc).makeAccessException("symbolic reference class is not public", this);
1397         }
1398 
1399         /** Check name for an illegal leading "&lt;" character. */
1400         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
1401             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
1402                 throw new NoSuchMethodException("illegal method name: "+name);
1403         }
1404 
1405 
1406         /**
1407          * Find my trustable caller class if m is a caller sensitive method.
1408          * If this lookup object has private access, then the caller class is the lookupClass.
1409          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
1410          */
1411         Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
1412             Class<?> callerClass = null;
1413             if (MethodHandleNatives.isCallerSensitive(m)) {
1414                 // Only lookups with private access are allowed to resolve caller-sensitive methods
1415                 if (hasPrivateAccess()) {
1416                     callerClass = lookupClass;
1417                 } else {
1418                     throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
1419                 }
1420             }
1421             return callerClass;
1422         }
1423 
1424         private boolean hasPrivateAccess() {
1425             return (allowedModes & PRIVATE) != 0;
1426         }
1427 
1428         /**
1429          * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
1430          * Determines a trustable caller class to compare with refc, the symbolic reference class.
1431          * If this lookup object has private access, then the caller class is the lookupClass.
1432          */
1433         void checkSecurityManager(Class<?> refc, MemberName m) {
1434             SecurityManager smgr = System.getSecurityManager();
1435             if (smgr == null)  return;
1436             if (allowedModes == TRUSTED)  return;
1437 
1438             // Step 1:
1439             boolean fullPowerLookup = hasPrivateAccess();
1440             if (!fullPowerLookup ||
1441                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
1442                 ReflectUtil.checkPackageAccess(refc);
1443             }
1444 
1445             // Step 2:
1446             if (m.isPublic()) return;
1447             if (!fullPowerLookup) {
1448                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
1449             }
1450 
1451             // Step 3:
1452             Class<?> defc = m.getDeclaringClass();
1453             if (!fullPowerLookup && defc != refc) {
1454                 ReflectUtil.checkPackageAccess(defc);
1455             }
1456         }
1457 
1458         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1459             boolean wantStatic = (refKind == REF_invokeStatic);
1460             String message;
1461             if (m.isConstructor())
1462                 message = "expected a method, not a constructor";
1463             else if (!m.isMethod())
1464                 message = "expected a method";
1465             else if (wantStatic != m.isStatic())
1466                 message = wantStatic ? "expected a static method" : "expected a non-static method";
1467             else
1468                 { checkAccess(refKind, refc, m); return; }
1469             throw m.makeAccessException(message, this);
1470         }
1471 
1472         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1473             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
1474             String message;
1475             if (wantStatic != m.isStatic())
1476                 message = wantStatic ? "expected a static field" : "expected a non-static field";
1477             else
1478                 { checkAccess(refKind, refc, m); return; }
1479             throw m.makeAccessException(message, this);
1480         }
1481 
1482         /** Check public/protected/private bits on the symbolic reference class and its member. */
1483         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1484             assert(m.referenceKindIsConsistentWith(refKind) &&
1485                    MethodHandleNatives.refKindIsValid(refKind) &&
1486                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
1487             int allowedModes = this.allowedModes;
1488             if (allowedModes == TRUSTED)  return;
1489             int mods = m.getModifiers();
1490             if (Modifier.isProtected(mods) &&
1491                     refKind == REF_invokeVirtual &&
1492                     m.getDeclaringClass() == Object.class &&
1493                     m.getName().equals("clone") &&
1494                     refc.isArray()) {
1495                 // The JVM does this hack also.
1496                 // (See ClassVerifier::verify_invoke_instructions
1497                 // and LinkResolver::check_method_accessability.)
1498                 // Because the JVM does not allow separate methods on array types,
1499                 // there is no separate method for int[].clone.
1500                 // All arrays simply inherit Object.clone.
1501                 // But for access checking logic, we make Object.clone
1502                 // (normally protected) appear to be public.
1503                 // Later on, when the DirectMethodHandle is created,
1504                 // its leading argument will be restricted to the
1505                 // requested array type.
1506                 // N.B. The return type is not adjusted, because
1507                 // that is *not* the bytecode behavior.
1508                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
1509             }
1510             if (Modifier.isFinal(mods) &&
1511                     MethodHandleNatives.refKindIsSetter(refKind))
1512                 throw m.makeAccessException("unexpected set of a final field", this);
1513             if (Modifier.isPublic(mods) && Modifier.isPublic(refc.getModifiers()) && allowedModes != 0)
1514                 return;  // common case
1515             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
1516             if ((requestedModes & allowedModes) != 0) {
1517                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
1518                                                     mods, lookupClass(), allowedModes))
1519                     return;
1520             } else {
1521                 // Protected members can also be checked as if they were package-private.
1522                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
1523                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
1524                     return;
1525             }
1526             throw m.makeAccessException(accessFailedMessage(refc, m), this);
1527         }
1528 
1529         String accessFailedMessage(Class<?> refc, MemberName m) {
1530             Class<?> defc = m.getDeclaringClass();
1531             int mods = m.getModifiers();
1532             // check the class first:
1533             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
1534                                (defc == refc ||
1535                                 Modifier.isPublic(refc.getModifiers())));
1536             if (!classOK && (allowedModes & PACKAGE) != 0) {
1537                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
1538                            (defc == refc ||
1539                             VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
1540             }
1541             if (!classOK)
1542                 return "class is not public";
1543             if (Modifier.isPublic(mods))
1544                 return "access to public member failed";  // (how?)
1545             if (Modifier.isPrivate(mods))
1546                 return "member is private";
1547             if (Modifier.isProtected(mods))
1548                 return "member is protected";
1549             return "member is private to package";
1550         }
1551 
1552         private static final boolean ALLOW_NESTMATE_ACCESS = false;
1553 
1554         private void checkSpecialCaller(Class<?> specialCaller) throws IllegalAccessException {
1555             int allowedModes = this.allowedModes;
1556             if (allowedModes == TRUSTED)  return;
1557             if (!hasPrivateAccess()
1558                 || (specialCaller != lookupClass()
1559                     && !(ALLOW_NESTMATE_ACCESS &&
1560                          VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
1561                 throw new MemberName(specialCaller).
1562                     makeAccessException("no private access for invokespecial", this);
1563         }
1564 
1565         private boolean restrictProtectedReceiver(MemberName method) {
1566             // The accessing class only has the right to use a protected member
1567             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
1568             if (!method.isProtected() || method.isStatic()
1569                 || allowedModes == TRUSTED
1570                 || method.getDeclaringClass() == lookupClass()
1571                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
1572                 || (ALLOW_NESTMATE_ACCESS &&
1573                     VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass())))
1574                 return false;
1575             return true;
1576         }
1577         private MethodHandle restrictReceiver(MemberName method, MethodHandle mh, Class<?> caller) throws IllegalAccessException {
1578             assert(!method.isStatic());
1579             // receiver type of mh is too wide; narrow to caller
1580             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
1581                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
1582             }
1583             MethodType rawType = mh.type();
1584             if (rawType.parameterType(0) == caller)  return mh;
1585             MethodType narrowType = rawType.changeParameterType(0, caller);
1586             return mh.viewAsType(narrowType);
1587         }
1588 
1589         /** Check access and get the requested method. */
1590         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1591             final boolean doRestrict    = true;
1592             final boolean checkSecurity = true;
1593             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1594         }
1595         /** Check access and get the requested method, eliding receiver narrowing rules. */
1596         private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1597             final boolean doRestrict    = false;
1598             final boolean checkSecurity = true;
1599             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1600         }
1601         /** Check access and get the requested method, eliding security manager checks. */
1602         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1603             final boolean doRestrict    = true;
1604             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
1605             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1606         }
1607         /** Common code for all methods; do not call directly except from immediately above. */
1608         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
1609                                                    boolean checkSecurity,
1610                                                    boolean doRestrict, Class<?> callerClass) throws IllegalAccessException {
1611             checkMethod(refKind, refc, method);
1612             // Optionally check with the security manager; this isn't needed for unreflect* calls.
1613             if (checkSecurity)
1614                 checkSecurityManager(refc, method);
1615             assert(!method.isMethodHandleInvoke());
1616 
1617             if (refKind == REF_invokeSpecial &&
1618                 refc != lookupClass() &&
1619                 !refc.isInterface() &&
1620                 refc != lookupClass().getSuperclass() &&
1621                 refc.isAssignableFrom(lookupClass())) {
1622                 assert(!method.getName().equals("<init>"));  // not this code path
1623                 // Per JVMS 6.5, desc. of invokespecial instruction:
1624                 // If the method is in a superclass of the LC,
1625                 // and if our original search was above LC.super,
1626                 // repeat the search (symbolic lookup) from LC.super
1627                 // and continue with the direct superclass of that class,
1628                 // and so forth, until a match is found or no further superclasses exist.
1629                 // FIXME: MemberName.resolve should handle this instead.
1630                 Class<?> refcAsSuper = lookupClass();
1631                 MemberName m2;
1632                 do {
1633                     refcAsSuper = refcAsSuper.getSuperclass();
1634                     m2 = new MemberName(refcAsSuper,
1635                                         method.getName(),
1636                                         method.getMethodType(),
1637                                         REF_invokeSpecial);
1638                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
1639                 } while (m2 == null &&         // no method is found yet
1640                          refc != refcAsSuper); // search up to refc
1641                 if (m2 == null)  throw new InternalError(method.toString());
1642                 method = m2;
1643                 refc = refcAsSuper;
1644                 // redo basic checks
1645                 checkMethod(refKind, refc, method);
1646             }
1647 
1648             MethodHandle mh = DirectMethodHandle.make(refKind, refc, method);
1649             mh = maybeBindCaller(method, mh, callerClass);
1650             mh = mh.setVarargs(method);
1651             // Optionally narrow the receiver argument to refc using restrictReceiver.
1652             if (doRestrict &&
1653                    (refKind == REF_invokeSpecial ||
1654                        (MethodHandleNatives.refKindHasReceiver(refKind) &&
1655                            restrictProtectedReceiver(method))))
1656                 mh = restrictReceiver(method, mh, lookupClass());
1657             return mh;
1658         }
1659         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
1660                                              Class<?> callerClass)
1661                                              throws IllegalAccessException {
1662             if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
1663                 return mh;
1664             Class<?> hostClass = lookupClass;
1665             if (!hasPrivateAccess())  // caller must have private access
1666                 hostClass = callerClass;  // callerClass came from a security manager style stack walk
1667             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
1668             // Note: caller will apply varargs after this step happens.
1669             return cbmh;
1670         }
1671         /** Check access and get the requested field. */
1672         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
1673             final boolean checkSecurity = true;
1674             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
1675         }
1676         /** Check access and get the requested field, eliding security manager checks. */
1677         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
1678             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
1679             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
1680         }
1681         /** Common code for all fields; do not call directly except from immediately above. */
1682         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
1683                                                   boolean checkSecurity) throws IllegalAccessException {
1684             checkField(refKind, refc, field);
1685             // Optionally check with the security manager; this isn't needed for unreflect* calls.
1686             if (checkSecurity)
1687                 checkSecurityManager(refc, field);
1688             MethodHandle mh = DirectMethodHandle.make(refc, field);
1689             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
1690                                     restrictProtectedReceiver(field));
1691             if (doRestrict)
1692                 mh = restrictReceiver(field, mh, lookupClass());
1693             return mh;
1694         }
1695         /** Check access and get the requested constructor. */
1696         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
1697             final boolean checkSecurity = true;
1698             return getDirectConstructorCommon(refc, ctor, checkSecurity);
1699         }
1700         /** Check access and get the requested constructor, eliding security manager checks. */
1701         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
1702             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
1703             return getDirectConstructorCommon(refc, ctor, checkSecurity);
1704         }
1705         /** Common code for all constructors; do not call directly except from immediately above. */
1706         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
1707                                                   boolean checkSecurity) throws IllegalAccessException {
1708             assert(ctor.isConstructor());
1709             checkAccess(REF_newInvokeSpecial, refc, ctor);
1710             // Optionally check with the security manager; this isn't needed for unreflect* calls.
1711             if (checkSecurity)
1712                 checkSecurityManager(refc, ctor);
1713             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
1714             return DirectMethodHandle.make(ctor).setVarargs(ctor);
1715         }
1716 
1717         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
1718          */
1719         /*non-public*/
1720         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException {
1721             if (!(type instanceof Class || type instanceof MethodType))
1722                 throw new InternalError("unresolved MemberName");
1723             MemberName member = new MemberName(refKind, defc, name, type);
1724             MethodHandle mh = LOOKASIDE_TABLE.get(member);
1725             if (mh != null) {
1726                 checkSymbolicClass(defc);
1727                 return mh;
1728             }
1729             // Treat MethodHandle.invoke and invokeExact specially.
1730             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
1731                 mh = findVirtualForMH(member.getName(), member.getMethodType());
1732                 if (mh != null) {
1733                     return mh;
1734                 }
1735             }
1736             MemberName resolved = resolveOrFail(refKind, member);
1737             mh = getDirectMethodForConstant(refKind, defc, resolved);
1738             if (mh instanceof DirectMethodHandle
1739                     && canBeCached(refKind, defc, resolved)) {
1740                 MemberName key = mh.internalMemberName();
1741                 if (key != null) {
1742                     key = key.asNormalOriginal();
1743                 }
1744                 if (member.equals(key)) {  // better safe than sorry
1745                     LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
1746                 }
1747             }
1748             return mh;
1749         }
1750         private
1751         boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
1752             if (refKind == REF_invokeSpecial) {
1753                 return false;
1754             }
1755             if (!Modifier.isPublic(defc.getModifiers()) ||
1756                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
1757                     !member.isPublic() ||
1758                     member.isCallerSensitive()) {
1759                 return false;
1760             }
1761             ClassLoader loader = defc.getClassLoader();
1762             if (!sun.misc.VM.isSystemDomainLoader(loader)) {
1763                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
1764                 boolean found = false;
1765                 while (sysl != null) {
1766                     if (loader == sysl) { found = true; break; }
1767                     sysl = sysl.getParent();
1768                 }
1769                 if (!found) {
1770                     return false;
1771                 }
1772             }
1773             try {
1774                 MemberName resolved2 = publicLookup().resolveOrFail(refKind,
1775                     new MemberName(refKind, defc, member.getName(), member.getType()));
1776                 checkSecurityManager(defc, resolved2);
1777             } catch (ReflectiveOperationException | SecurityException ex) {
1778                 return false;
1779             }
1780             return true;
1781         }
1782         private
1783         MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
1784                 throws ReflectiveOperationException {
1785             if (MethodHandleNatives.refKindIsField(refKind)) {
1786                 return getDirectFieldNoSecurityManager(refKind, defc, member);
1787             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
1788                 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
1789             } else if (refKind == REF_newInvokeSpecial) {
1790                 return getDirectConstructorNoSecurityManager(defc, member);
1791             }
1792             // oops
1793             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
1794         }
1795 
1796         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
1797     }
1798 
1799     /**
1800      * Produces a method handle giving read access to elements of an array.
1801      * The type of the method handle will have a return type of the array's
1802      * element type.  Its first argument will be the array type,
1803      * and the second will be {@code int}.
1804      * @param arrayClass an array type
1805      * @return a method handle which can load values from the given array type
1806      * @throws NullPointerException if the argument is null
1807      * @throws  IllegalArgumentException if arrayClass is not an array type
1808      */
1809     public static
1810     MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
1811         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false);
1812     }
1813 
1814     /**
1815      * Produces a method handle giving write access to elements of an array.
1816      * The type of the method handle will have a void return type.
1817      * Its last argument will be the array's element type.
1818      * The first and second arguments will be the array type and int.
1819      * @param arrayClass the class of an array
1820      * @return a method handle which can store values into the array type
1821      * @throws NullPointerException if the argument is null
1822      * @throws IllegalArgumentException if arrayClass is not an array type
1823      */
1824     public static
1825     MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
1826         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true);
1827     }
1828 
1829     /// method handle invocation (reflective style)
1830 
1831     /**
1832      * Produces a method handle which will invoke any method handle of the
1833      * given {@code type}, with a given number of trailing arguments replaced by
1834      * a single trailing {@code Object[]} array.
1835      * The resulting invoker will be a method handle with the following
1836      * arguments:
1837      * <ul>
1838      * <li>a single {@code MethodHandle} target
1839      * <li>zero or more leading values (counted by {@code leadingArgCount})
1840      * <li>an {@code Object[]} array containing trailing arguments
1841      * </ul>
1842      * <p>
1843      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
1844      * the indicated {@code type}.
1845      * That is, if the target is exactly of the given {@code type}, it will behave
1846      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
1847      * is used to convert the target to the required {@code type}.
1848      * <p>
1849      * The type of the returned invoker will not be the given {@code type}, but rather
1850      * will have all parameters except the first {@code leadingArgCount}
1851      * replaced by a single array of type {@code Object[]}, which will be
1852      * the final parameter.
1853      * <p>
1854      * Before invoking its target, the invoker will spread the final array, apply
1855      * reference casts as necessary, and unbox and widen primitive arguments.
1856      * If, when the invoker is called, the supplied array argument does
1857      * not have the correct number of elements, the invoker will throw
1858      * an {@link IllegalArgumentException} instead of invoking the target.
1859      * <p>
1860      * This method is equivalent to the following code (though it may be more efficient):
1861      * <blockquote><pre>{@code
1862 MethodHandle invoker = MethodHandles.invoker(type);
1863 int spreadArgCount = type.parameterCount() - leadingArgCount;
1864 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
1865 return invoker;
1866      * }</pre></blockquote>
1867      * This method throws no reflective or security exceptions.
1868      * @param type the desired target type
1869      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
1870      * @return a method handle suitable for invoking any method handle of the given type
1871      * @throws NullPointerException if {@code type} is null
1872      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
1873      *                  the range from 0 to {@code type.parameterCount()} inclusive,
1874      *                  or if the resulting method handle's type would have
1875      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
1876      */
1877     static public
1878     MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
1879         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
1880             throw new IllegalArgumentException("bad argument count "+leadingArgCount);
1881         return type.invokers().spreadInvoker(leadingArgCount);
1882     }
1883 
1884     /**
1885      * Produces a special <em>invoker method handle</em> which can be used to
1886      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
1887      * The resulting invoker will have a type which is
1888      * exactly equal to the desired type, except that it will accept
1889      * an additional leading argument of type {@code MethodHandle}.
1890      * <p>
1891      * This method is equivalent to the following code (though it may be more efficient):
1892      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
1893      *
1894      * <p style="font-size:smaller;">
1895      * <em>Discussion:</em>
1896      * Invoker method handles can be useful when working with variable method handles
1897      * of unknown types.
1898      * For example, to emulate an {@code invokeExact} call to a variable method
1899      * handle {@code M}, extract its type {@code T},
1900      * look up the invoker method {@code X} for {@code T},
1901      * and call the invoker method, as {@code X.invoke(T, A...)}.
1902      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
1903      * is unknown.)
1904      * If spreading, collecting, or other argument transformations are required,
1905      * they can be applied once to the invoker {@code X} and reused on many {@code M}
1906      * method handle values, as long as they are compatible with the type of {@code X}.
1907      * <p style="font-size:smaller;">
1908      * <em>(Note:  The invoker method is not available via the Core Reflection API.
1909      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
1910      * on the declared {@code invokeExact} or {@code invoke} method will raise an
1911      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
1912      * <p>
1913      * This method throws no reflective or security exceptions.
1914      * @param type the desired target type
1915      * @return a method handle suitable for invoking any method handle of the given type
1916      * @throws IllegalArgumentException if the resulting method handle's type would have
1917      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
1918      */
1919     static public
1920     MethodHandle exactInvoker(MethodType type) {
1921         return type.invokers().exactInvoker();
1922     }
1923 
1924     /**
1925      * Produces a special <em>invoker method handle</em> which can be used to
1926      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
1927      * The resulting invoker will have a type which is
1928      * exactly equal to the desired type, except that it will accept
1929      * an additional leading argument of type {@code MethodHandle}.
1930      * <p>
1931      * Before invoking its target, if the target differs from the expected type,
1932      * the invoker will apply reference casts as
1933      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
1934      * Similarly, the return value will be converted as necessary.
1935      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
1936      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
1937      * <p>
1938      * This method is equivalent to the following code (though it may be more efficient):
1939      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
1940      * <p style="font-size:smaller;">
1941      * <em>Discussion:</em>
1942      * A {@linkplain MethodType#genericMethodType general method type} is one which
1943      * mentions only {@code Object} arguments and return values.
1944      * An invoker for such a type is capable of calling any method handle
1945      * of the same arity as the general type.
1946      * <p style="font-size:smaller;">
1947      * <em>(Note:  The invoker method is not available via the Core Reflection API.
1948      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
1949      * on the declared {@code invokeExact} or {@code invoke} method will raise an
1950      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
1951      * <p>
1952      * This method throws no reflective or security exceptions.
1953      * @param type the desired target type
1954      * @return a method handle suitable for invoking any method handle convertible to the given type
1955      * @throws IllegalArgumentException if the resulting method handle's type would have
1956      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
1957      */
1958     static public
1959     MethodHandle invoker(MethodType type) {
1960         return type.invokers().generalInvoker();
1961     }
1962 
1963     static /*non-public*/
1964     MethodHandle basicInvoker(MethodType type) {
1965         return type.invokers().basicInvoker();
1966     }
1967 
1968      /// method handle modification (creation from other method handles)
1969 
1970     /**
1971      * Produces a method handle which adapts the type of the
1972      * given method handle to a new type by pairwise argument and return type conversion.
1973      * The original type and new type must have the same number of arguments.
1974      * The resulting method handle is guaranteed to report a type
1975      * which is equal to the desired new type.
1976      * <p>
1977      * If the original type and new type are equal, returns target.
1978      * <p>
1979      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
1980      * and some additional conversions are also applied if those conversions fail.
1981      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
1982      * if possible, before or instead of any conversions done by {@code asType}:
1983      * <ul>
1984      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
1985      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
1986      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
1987      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
1988      *     the boolean is converted to a byte value, 1 for true, 0 for false.
1989      *     (This treatment follows the usage of the bytecode verifier.)
1990      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
1991      *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
1992      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
1993      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
1994      *     then a Java casting conversion (JLS 5.5) is applied.
1995      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
1996      *     widening and/or narrowing.)
1997      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
1998      *     conversion will be applied at runtime, possibly followed
1999      *     by a Java casting conversion (JLS 5.5) on the primitive value,
2000      *     possibly followed by a conversion from byte to boolean by testing
2001      *     the low-order bit.
2002      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
2003      *     and if the reference is null at runtime, a zero value is introduced.
2004      * </ul>
2005      * @param target the method handle to invoke after arguments are retyped
2006      * @param newType the expected type of the new method handle
2007      * @return a method handle which delegates to the target after performing
2008      *           any necessary argument conversions, and arranges for any
2009      *           necessary return value conversions
2010      * @throws NullPointerException if either argument is null
2011      * @throws WrongMethodTypeException if the conversion cannot be made
2012      * @see MethodHandle#asType
2013      */
2014     public static
2015     MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
2016         if (!target.type().isCastableTo(newType)) {
2017             throw new WrongMethodTypeException("cannot explicitly cast "+target+" to "+newType);
2018         }
2019         return MethodHandleImpl.makePairwiseConvert(target, newType, 2);
2020     }
2021 
2022     /**
2023      * Produces a method handle which adapts the calling sequence of the
2024      * given method handle to a new type, by reordering the arguments.
2025      * The resulting method handle is guaranteed to report a type
2026      * which is equal to the desired new type.
2027      * <p>
2028      * The given array controls the reordering.
2029      * Call {@code #I} the number of incoming parameters (the value
2030      * {@code newType.parameterCount()}, and call {@code #O} the number
2031      * of outgoing parameters (the value {@code target.type().parameterCount()}).
2032      * Then the length of the reordering array must be {@code #O},
2033      * and each element must be a non-negative number less than {@code #I}.
2034      * For every {@code N} less than {@code #O}, the {@code N}-th
2035      * outgoing argument will be taken from the {@code I}-th incoming
2036      * argument, where {@code I} is {@code reorder[N]}.
2037      * <p>
2038      * No argument or return value conversions are applied.
2039      * The type of each incoming argument, as determined by {@code newType},
2040      * must be identical to the type of the corresponding outgoing parameter
2041      * or parameters in the target method handle.
2042      * The return type of {@code newType} must be identical to the return
2043      * type of the original target.
2044      * <p>
2045      * The reordering array need not specify an actual permutation.
2046      * An incoming argument will be duplicated if its index appears
2047      * more than once in the array, and an incoming argument will be dropped
2048      * if its index does not appear in the array.
2049      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
2050      * incoming arguments which are not mentioned in the reordering array
2051      * are may be any type, as determined only by {@code newType}.
2052      * <blockquote><pre>{@code
2053 import static java.lang.invoke.MethodHandles.*;
2054 import static java.lang.invoke.MethodType.*;
2055 ...
2056 MethodType intfn1 = methodType(int.class, int.class);
2057 MethodType intfn2 = methodType(int.class, int.class, int.class);
2058 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
2059 assert(sub.type().equals(intfn2));
2060 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
2061 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
2062 assert((int)rsub.invokeExact(1, 100) == 99);
2063 MethodHandle add = ... (int x, int y) -> (x+y) ...;
2064 assert(add.type().equals(intfn2));
2065 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
2066 assert(twice.type().equals(intfn1));
2067 assert((int)twice.invokeExact(21) == 42);
2068      * }</pre></blockquote>
2069      * @param target the method handle to invoke after arguments are reordered
2070      * @param newType the expected type of the new method handle
2071      * @param reorder an index array which controls the reordering
2072      * @return a method handle which delegates to the target after it
2073      *           drops unused arguments and moves and/or duplicates the other arguments
2074      * @throws NullPointerException if any argument is null
2075      * @throws IllegalArgumentException if the index array length is not equal to
2076      *                  the arity of the target, or if any index array element
2077      *                  not a valid index for a parameter of {@code newType},
2078      *                  or if two corresponding parameter types in
2079      *                  {@code target.type()} and {@code newType} are not identical,
2080      */
2081     public static
2082     MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
2083         reorder = reorder.clone();
2084         checkReorder(reorder, newType, target.type());
2085         return target.permuteArguments(newType, reorder);
2086     }
2087 
2088     private static void checkReorder(int[] reorder, MethodType newType, MethodType oldType) {
2089         if (newType.returnType() != oldType.returnType())
2090             throw newIllegalArgumentException("return types do not match",
2091                     oldType, newType);
2092         if (reorder.length == oldType.parameterCount()) {
2093             int limit = newType.parameterCount();
2094             boolean bad = false;
2095             for (int j = 0; j < reorder.length; j++) {
2096                 int i = reorder[j];
2097                 if (i < 0 || i >= limit) {
2098                     bad = true; break;
2099                 }
2100                 Class<?> src = newType.parameterType(i);
2101                 Class<?> dst = oldType.parameterType(j);
2102                 if (src != dst)
2103                     throw newIllegalArgumentException("parameter types do not match after reorder",
2104                             oldType, newType);
2105             }
2106             if (!bad)  return;
2107         }
2108         throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
2109     }
2110 
2111     /**
2112      * Produces a method handle of the requested return type which returns the given
2113      * constant value every time it is invoked.
2114      * <p>
2115      * Before the method handle is returned, the passed-in value is converted to the requested type.
2116      * If the requested type is primitive, widening primitive conversions are attempted,
2117      * else reference conversions are attempted.
2118      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
2119      * @param type the return type of the desired method handle
2120      * @param value the value to return
2121      * @return a method handle of the given return type and no arguments, which always returns the given value
2122      * @throws NullPointerException if the {@code type} argument is null
2123      * @throws ClassCastException if the value cannot be converted to the required return type
2124      * @throws IllegalArgumentException if the given type is {@code void.class}
2125      */
2126     public static
2127     MethodHandle constant(Class<?> type, Object value) {
2128         if (type.isPrimitive()) {
2129             if (type == void.class)
2130                 throw newIllegalArgumentException("void type");
2131             Wrapper w = Wrapper.forPrimitiveType(type);
2132             return insertArguments(identity(type), 0, w.convert(value, type));
2133         } else {
2134             return identity(type).bindTo(type.cast(value));
2135         }
2136     }
2137 
2138     /**
2139      * Produces a method handle which returns its sole argument when invoked.
2140      * @param type the type of the sole parameter and return value of the desired method handle
2141      * @return a unary method handle which accepts and returns the given type
2142      * @throws NullPointerException if the argument is null
2143      * @throws IllegalArgumentException if the given type is {@code void.class}
2144      */
2145     public static
2146     MethodHandle identity(Class<?> type) {
2147         if (type == void.class)
2148             throw newIllegalArgumentException("void type");
2149         else if (type == Object.class)
2150             return ValueConversions.identity();
2151         else if (type.isPrimitive())
2152             return ValueConversions.identity(Wrapper.forPrimitiveType(type));
2153         else
2154             return MethodHandleImpl.makeReferenceIdentity(type);
2155     }
2156 
2157     /**
2158      * Provides a target method handle with one or more <em>bound arguments</em>
2159      * in advance of the method handle's invocation.
2160      * The formal parameters to the target corresponding to the bound
2161      * arguments are called <em>bound parameters</em>.
2162      * Returns a new method handle which saves away the bound arguments.
2163      * When it is invoked, it receives arguments for any non-bound parameters,
2164      * binds the saved arguments to their corresponding parameters,
2165      * and calls the original target.
2166      * <p>
2167      * The type of the new method handle will drop the types for the bound
2168      * parameters from the original target type, since the new method handle
2169      * will no longer require those arguments to be supplied by its callers.
2170      * <p>
2171      * Each given argument object must match the corresponding bound parameter type.
2172      * If a bound parameter type is a primitive, the argument object
2173      * must be a wrapper, and will be unboxed to produce the primitive value.
2174      * <p>
2175      * The {@code pos} argument selects which parameters are to be bound.
2176      * It may range between zero and <i>N-L</i> (inclusively),
2177      * where <i>N</i> is the arity of the target method handle
2178      * and <i>L</i> is the length of the values array.
2179      * @param target the method handle to invoke after the argument is inserted
2180      * @param pos where to insert the argument (zero for the first)
2181      * @param values the series of arguments to insert
2182      * @return a method handle which inserts an additional argument,
2183      *         before calling the original method handle
2184      * @throws NullPointerException if the target or the {@code values} array is null
2185      * @see MethodHandle#bindTo
2186      */
2187     public static
2188     MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
2189         int insCount = values.length;
2190         MethodType oldType = target.type();
2191         int outargs = oldType.parameterCount();
2192         int inargs  = outargs - insCount;
2193         if (inargs < 0)
2194             throw newIllegalArgumentException("too many values to insert");
2195         if (pos < 0 || pos > inargs)
2196             throw newIllegalArgumentException("no argument type to append");
2197         MethodHandle result = target;
2198         for (int i = 0; i < insCount; i++) {
2199             Object value = values[i];
2200             Class<?> ptype = oldType.parameterType(pos+i);
2201             if (ptype.isPrimitive()) {
2202                 BasicType btype = I_TYPE;
2203                 Wrapper w = Wrapper.forPrimitiveType(ptype);
2204                 switch (w) {
2205                 case LONG:    btype = J_TYPE; break;
2206                 case FLOAT:   btype = F_TYPE; break;
2207                 case DOUBLE:  btype = D_TYPE; break;
2208                 }
2209                 // perform unboxing and/or primitive conversion
2210                 value = w.convert(value, ptype);
2211                 result = result.bindArgument(pos, btype, value);
2212                 continue;
2213             }
2214             value = ptype.cast(value);  // throw CCE if needed
2215             if (pos == 0) {
2216                 result = result.bindReceiver(value);
2217             } else {
2218                 result = result.bindArgument(pos, L_TYPE, value);
2219             }
2220         }
2221         return result;
2222     }
2223 
2224     /**
2225      * Produces a method handle which will discard some dummy arguments
2226      * before calling some other specified <i>target</i> method handle.
2227      * The type of the new method handle will be the same as the target's type,
2228      * except it will also include the dummy argument types,
2229      * at some given position.
2230      * <p>
2231      * The {@code pos} argument may range between zero and <i>N</i>,
2232      * where <i>N</i> is the arity of the target.
2233      * If {@code pos} is zero, the dummy arguments will precede
2234      * the target's real arguments; if {@code pos} is <i>N</i>
2235      * they will come after.
2236      * <p>
2237      * <b>Example:</b>
2238      * <blockquote><pre>{@code
2239 import static java.lang.invoke.MethodHandles.*;
2240 import static java.lang.invoke.MethodType.*;
2241 ...
2242 MethodHandle cat = lookup().findVirtual(String.class,
2243   "concat", methodType(String.class, String.class));
2244 assertEquals("xy", (String) cat.invokeExact("x", "y"));
2245 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
2246 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
2247 assertEquals(bigType, d0.type());
2248 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
2249      * }</pre></blockquote>
2250      * <p>
2251      * This method is also equivalent to the following code:
2252      * <blockquote><pre>
2253      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
2254      * </pre></blockquote>
2255      * @param target the method handle to invoke after the arguments are dropped
2256      * @param valueTypes the type(s) of the argument(s) to drop
2257      * @param pos position of first argument to drop (zero for the leftmost)
2258      * @return a method handle which drops arguments of the given types,
2259      *         before calling the original method handle
2260      * @throws NullPointerException if the target is null,
2261      *                              or if the {@code valueTypes} list or any of its elements is null
2262      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
2263      *                  or if {@code pos} is negative or greater than the arity of the target,
2264      *                  or if the new method handle's type would have too many parameters
2265      */
2266     public static
2267     MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
2268         MethodType oldType = target.type();  // get NPE
2269         int dropped = valueTypes.size();
2270         MethodType.checkSlotCount(dropped);
2271         if (dropped == 0)  return target;
2272         int outargs = oldType.parameterCount();
2273         int inargs  = outargs + dropped;
2274         if (pos < 0 || pos >= inargs)
2275             throw newIllegalArgumentException("no argument type to remove");
2276         ArrayList<Class<?>> ptypes = new ArrayList<>(oldType.parameterList());
2277         ptypes.addAll(pos, valueTypes);
2278         if (ptypes.size() != inargs)  throw newIllegalArgumentException("valueTypes");
2279         MethodType newType = MethodType.methodType(oldType.returnType(), ptypes);
2280         return target.dropArguments(newType, pos, dropped);
2281     }
2282 
2283     /**
2284      * Produces a method handle which will discard some dummy arguments
2285      * before calling some other specified <i>target</i> method handle.
2286      * The type of the new method handle will be the same as the target's type,
2287      * except it will also include the dummy argument types,
2288      * at some given position.
2289      * <p>
2290      * The {@code pos} argument may range between zero and <i>N</i>,
2291      * where <i>N</i> is the arity of the target.
2292      * If {@code pos} is zero, the dummy arguments will precede
2293      * the target's real arguments; if {@code pos} is <i>N</i>
2294      * they will come after.
2295      * <p>
2296      * <b>Example:</b>
2297      * <blockquote><pre>{@code
2298 import static java.lang.invoke.MethodHandles.*;
2299 import static java.lang.invoke.MethodType.*;
2300 ...
2301 MethodHandle cat = lookup().findVirtual(String.class,
2302   "concat", methodType(String.class, String.class));
2303 assertEquals("xy", (String) cat.invokeExact("x", "y"));
2304 MethodHandle d0 = dropArguments(cat, 0, String.class);
2305 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
2306 MethodHandle d1 = dropArguments(cat, 1, String.class);
2307 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
2308 MethodHandle d2 = dropArguments(cat, 2, String.class);
2309 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
2310 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
2311 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
2312      * }</pre></blockquote>
2313      * <p>
2314      * This method is also equivalent to the following code:
2315      * <blockquote><pre>
2316      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
2317      * </pre></blockquote>
2318      * @param target the method handle to invoke after the arguments are dropped
2319      * @param valueTypes the type(s) of the argument(s) to drop
2320      * @param pos position of first argument to drop (zero for the leftmost)
2321      * @return a method handle which drops arguments of the given types,
2322      *         before calling the original method handle
2323      * @throws NullPointerException if the target is null,
2324      *                              or if the {@code valueTypes} array or any of its elements is null
2325      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
2326      *                  or if {@code pos} is negative or greater than the arity of the target,
2327      *                  or if the new method handle's type would have
2328      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
2329      */
2330     public static
2331     MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
2332         return dropArguments(target, pos, Arrays.asList(valueTypes));
2333     }
2334 
2335     /**
2336      * Adapts a target method handle by pre-processing
2337      * one or more of its arguments, each with its own unary filter function,
2338      * and then calling the target with each pre-processed argument
2339      * replaced by the result of its corresponding filter function.
2340      * <p>
2341      * The pre-processing is performed by one or more method handles,
2342      * specified in the elements of the {@code filters} array.
2343      * The first element of the filter array corresponds to the {@code pos}
2344      * argument of the target, and so on in sequence.
2345      * <p>
2346      * Null arguments in the array are treated as identity functions,
2347      * and the corresponding arguments left unchanged.
2348      * (If there are no non-null elements in the array, the original target is returned.)
2349      * Each filter is applied to the corresponding argument of the adapter.
2350      * <p>
2351      * If a filter {@code F} applies to the {@code N}th argument of
2352      * the target, then {@code F} must be a method handle which
2353      * takes exactly one argument.  The type of {@code F}'s sole argument
2354      * replaces the corresponding argument type of the target
2355      * in the resulting adapted method handle.
2356      * The return type of {@code F} must be identical to the corresponding
2357      * parameter type of the target.
2358      * <p>
2359      * It is an error if there are elements of {@code filters}
2360      * (null or not)
2361      * which do not correspond to argument positions in the target.
2362      * <p><b>Example:</b>
2363      * <blockquote><pre>{@code
2364 import static java.lang.invoke.MethodHandles.*;
2365 import static java.lang.invoke.MethodType.*;
2366 ...
2367 MethodHandle cat = lookup().findVirtual(String.class,
2368   "concat", methodType(String.class, String.class));
2369 MethodHandle upcase = lookup().findVirtual(String.class,
2370   "toUpperCase", methodType(String.class));
2371 assertEquals("xy", (String) cat.invokeExact("x", "y"));
2372 MethodHandle f0 = filterArguments(cat, 0, upcase);
2373 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
2374 MethodHandle f1 = filterArguments(cat, 1, upcase);
2375 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
2376 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
2377 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
2378      * }</pre></blockquote>
2379      * <p> Here is pseudocode for the resulting adapter:
2380      * <blockquote><pre>{@code
2381      * V target(P... p, A[i]... a[i], B... b);
2382      * A[i] filter[i](V[i]);
2383      * T adapter(P... p, V[i]... v[i], B... b) {
2384      *   return target(p..., f[i](v[i])..., b...);
2385      * }
2386      * }</pre></blockquote>
2387      *
2388      * @param target the method handle to invoke after arguments are filtered
2389      * @param pos the position of the first argument to filter
2390      * @param filters method handles to call initially on filtered arguments
2391      * @return method handle which incorporates the specified argument filtering logic
2392      * @throws NullPointerException if the target is null
2393      *                              or if the {@code filters} array is null
2394      * @throws IllegalArgumentException if a non-null element of {@code filters}
2395      *          does not match a corresponding argument type of target as described above,
2396      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
2397      *          or if the resulting method handle's type would have
2398      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2399      */
2400     public static
2401     MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
2402         MethodType targetType = target.type();
2403         MethodHandle adapter = target;
2404         MethodType adapterType = null;
2405         assert((adapterType = targetType) != null);
2406         int maxPos = targetType.parameterCount();
2407         if (pos + filters.length > maxPos)
2408             throw newIllegalArgumentException("too many filters");
2409         int curPos = pos-1;  // pre-incremented
2410         for (MethodHandle filter : filters) {
2411             curPos += 1;
2412             if (filter == null)  continue;  // ignore null elements of filters
2413             adapter = filterArgument(adapter, curPos, filter);
2414             assert((adapterType = adapterType.changeParameterType(curPos, filter.type().parameterType(0))) != null);
2415         }
2416         assert(adapterType.equals(adapter.type()));
2417         return adapter;
2418     }
2419 
2420     /*non-public*/ static
2421     MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
2422         MethodType targetType = target.type();
2423         MethodType filterType = filter.type();
2424         if (filterType.parameterCount() != 1
2425             || filterType.returnType() != targetType.parameterType(pos))
2426             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
2427         return MethodHandleImpl.makeCollectArguments(target, filter, pos, false);
2428     }
2429 
2430     /**
2431      * Adapts a target method handle by pre-processing
2432      * a sub-sequence of its arguments with a filter (another method handle).
2433      * The pre-processed arguments are replaced by the result (if any) of the
2434      * filter function.
2435      * The target is then called on the modified (usually shortened) argument list.
2436      * <p>
2437      * If the filter returns a value, the target must accept that value as
2438      * its argument in position {@code pos}, preceded and/or followed by
2439      * any arguments not passed to the filter.
2440      * If the filter returns void, the target must accept all arguments
2441      * not passed to the filter.
2442      * No arguments are reordered, and a result returned from the filter
2443      * replaces (in order) the whole subsequence of arguments originally
2444      * passed to the adapter.
2445      * <p>
2446      * The argument types (if any) of the filter
2447      * replace zero or one argument types of the target, at position {@code pos},
2448      * in the resulting adapted method handle.
2449      * The return type of the filter (if any) must be identical to the
2450      * argument type of the target at position {@code pos}, and that target argument
2451      * is supplied by the return value of the filter.
2452      * <p>
2453      * In all cases, {@code pos} must be greater than or equal to zero, and
2454      * {@code pos} must also be less than or equal to the target's arity.
2455      * <p><b>Example:</b>
2456      * <blockquote><pre>{@code
2457 import static java.lang.invoke.MethodHandles.*;
2458 import static java.lang.invoke.MethodType.*;
2459 ...
2460 MethodHandle deepToString = publicLookup()
2461   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
2462 
2463 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
2464 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
2465 
2466 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
2467 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
2468 
2469 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
2470 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
2471 assertEquals("[top, [up, down], strange]",
2472              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
2473 
2474 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
2475 assertEquals("[top, [up, down], [strange]]",
2476              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
2477 
2478 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
2479 assertEquals("[top, [[up, down, strange], charm], bottom]",
2480              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
2481      * }</pre></blockquote>
2482      * <p> Here is pseudocode for the resulting adapter:
2483      * <blockquote><pre>{@code
2484      * T target(A...,V,C...);
2485      * V filter(B...);
2486      * T adapter(A... a,B... b,C... c) {
2487      *   V v = filter(b...);
2488      *   return target(a...,v,c...);
2489      * }
2490      * // and if the filter has no arguments:
2491      * T target2(A...,V,C...);
2492      * V filter2();
2493      * T adapter2(A... a,C... c) {
2494      *   V v = filter2();
2495      *   return target2(a...,v,c...);
2496      * }
2497      * // and if the filter has a void return:
2498      * T target3(A...,C...);
2499      * void filter3(B...);
2500      * void adapter3(A... a,B... b,C... c) {
2501      *   filter3(b...);
2502      *   return target3(a...,c...);
2503      * }
2504      * }</pre></blockquote>
2505      * <p>
2506      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
2507      * one which first "folds" the affected arguments, and then drops them, in separate
2508      * steps as follows:
2509      * <blockquote><pre>{@code
2510      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
2511      * mh = MethodHandles.foldArguments(mh, coll); //step 1
2512      * }</pre></blockquote>
2513      * If the target method handle consumes no arguments besides than the result
2514      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
2515      * is equivalent to {@code filterReturnValue(coll, mh)}.
2516      * If the filter method handle {@code coll} consumes one argument and produces
2517      * a non-void result, then {@code collectArguments(mh, N, coll)}
2518      * is equivalent to {@code filterArguments(mh, N, coll)}.
2519      * Other equivalences are possible but would require argument permutation.
2520      *
2521      * @param target the method handle to invoke after filtering the subsequence of arguments
2522      * @param pos the position of the first adapter argument to pass to the filter,
2523      *            and/or the target argument which receives the result of the filter
2524      * @param filter method handle to call on the subsequence of arguments
2525      * @return method handle which incorporates the specified argument subsequence filtering logic
2526      * @throws NullPointerException if either argument is null
2527      * @throws IllegalArgumentException if the return type of {@code filter}
2528      *          is non-void and is not the same as the {@code pos} argument of the target,
2529      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
2530      *          or if the resulting method handle's type would have
2531      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2532      * @see MethodHandles#foldArguments
2533      * @see MethodHandles#filterArguments
2534      * @see MethodHandles#filterReturnValue
2535      */
2536     public static
2537     MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
2538         MethodType targetType = target.type();
2539         MethodType filterType = filter.type();
2540         if (filterType.returnType() != void.class &&
2541             filterType.returnType() != targetType.parameterType(pos))
2542             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
2543         return MethodHandleImpl.makeCollectArguments(target, filter, pos, false);
2544     }
2545 
2546     /**
2547      * Adapts a target method handle by post-processing
2548      * its return value (if any) with a filter (another method handle).
2549      * The result of the filter is returned from the adapter.
2550      * <p>
2551      * If the target returns a value, the filter must accept that value as
2552      * its only argument.
2553      * If the target returns void, the filter must accept no arguments.
2554      * <p>
2555      * The return type of the filter
2556      * replaces the return type of the target
2557      * in the resulting adapted method handle.
2558      * The argument type of the filter (if any) must be identical to the
2559      * return type of the target.
2560      * <p><b>Example:</b>
2561      * <blockquote><pre>{@code
2562 import static java.lang.invoke.MethodHandles.*;
2563 import static java.lang.invoke.MethodType.*;
2564 ...
2565 MethodHandle cat = lookup().findVirtual(String.class,
2566   "concat", methodType(String.class, String.class));
2567 MethodHandle length = lookup().findVirtual(String.class,
2568   "length", methodType(int.class));
2569 System.out.println((String) cat.invokeExact("x", "y")); // xy
2570 MethodHandle f0 = filterReturnValue(cat, length);
2571 System.out.println((int) f0.invokeExact("x", "y")); // 2
2572      * }</pre></blockquote>
2573      * <p> Here is pseudocode for the resulting adapter:
2574      * <blockquote><pre>{@code
2575      * V target(A...);
2576      * T filter(V);
2577      * T adapter(A... a) {
2578      *   V v = target(a...);
2579      *   return filter(v);
2580      * }
2581      * // and if the target has a void return:
2582      * void target2(A...);
2583      * T filter2();
2584      * T adapter2(A... a) {
2585      *   target2(a...);
2586      *   return filter2();
2587      * }
2588      * // and if the filter has a void return:
2589      * V target3(A...);
2590      * void filter3(V);
2591      * void adapter3(A... a) {
2592      *   V v = target3(a...);
2593      *   filter3(v);
2594      * }
2595      * }</pre></blockquote>
2596      * @param target the method handle to invoke before filtering the return value
2597      * @param filter method handle to call on the return value
2598      * @return method handle which incorporates the specified return value filtering logic
2599      * @throws NullPointerException if either argument is null
2600      * @throws IllegalArgumentException if the argument list of {@code filter}
2601      *          does not match the return type of target as described above
2602      */
2603     public static
2604     MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
2605         MethodType targetType = target.type();
2606         MethodType filterType = filter.type();
2607         Class<?> rtype = targetType.returnType();
2608         int filterValues = filterType.parameterCount();
2609         if (filterValues == 0
2610                 ? (rtype != void.class)
2611                 : (rtype != filterType.parameterType(0)))
2612             throw newIllegalArgumentException("target and filter types do not match", target, filter);
2613         // result = fold( lambda(retval, arg...) { filter(retval) },
2614         //                lambda(        arg...) { target(arg...) } )
2615         return MethodHandleImpl.makeCollectArguments(filter, target, 0, false);
2616     }
2617 
2618     /**
2619      * Adapts a target method handle by pre-processing
2620      * some of its arguments, and then calling the target with
2621      * the result of the pre-processing, inserted into the original
2622      * sequence of arguments.
2623      * <p>
2624      * The pre-processing is performed by {@code combiner}, a second method handle.
2625      * Of the arguments passed to the adapter, the first {@code N} arguments
2626      * are copied to the combiner, which is then called.
2627      * (Here, {@code N} is defined as the parameter count of the combiner.)
2628      * After this, control passes to the target, with any result
2629      * from the combiner inserted before the original {@code N} incoming
2630      * arguments.
2631      * <p>
2632      * If the combiner returns a value, the first parameter type of the target
2633      * must be identical with the return type of the combiner, and the next
2634      * {@code N} parameter types of the target must exactly match the parameters
2635      * of the combiner.
2636      * <p>
2637      * If the combiner has a void return, no result will be inserted,
2638      * and the first {@code N} parameter types of the target
2639      * must exactly match the parameters of the combiner.
2640      * <p>
2641      * The resulting adapter is the same type as the target, except that the
2642      * first parameter type is dropped,
2643      * if it corresponds to the result of the combiner.
2644      * <p>
2645      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
2646      * that either the combiner or the target does not wish to receive.
2647      * If some of the incoming arguments are destined only for the combiner,
2648      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
2649      * arguments will not need to be live on the stack on entry to the
2650      * target.)
2651      * <p><b>Example:</b>
2652      * <blockquote><pre>{@code
2653 import static java.lang.invoke.MethodHandles.*;
2654 import static java.lang.invoke.MethodType.*;
2655 ...
2656 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
2657   "println", methodType(void.class, String.class))
2658     .bindTo(System.out);
2659 MethodHandle cat = lookup().findVirtual(String.class,
2660   "concat", methodType(String.class, String.class));
2661 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
2662 MethodHandle catTrace = foldArguments(cat, trace);
2663 // also prints "boo":
2664 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
2665      * }</pre></blockquote>
2666      * <p> Here is pseudocode for the resulting adapter:
2667      * <blockquote><pre>{@code
2668      * // there are N arguments in A...
2669      * T target(V, A[N]..., B...);
2670      * V combiner(A...);
2671      * T adapter(A... a, B... b) {
2672      *   V v = combiner(a...);
2673      *   return target(v, a..., b...);
2674      * }
2675      * // and if the combiner has a void return:
2676      * T target2(A[N]..., B...);
2677      * void combiner2(A...);
2678      * T adapter2(A... a, B... b) {
2679      *   combiner2(a...);
2680      *   return target2(a..., b...);
2681      * }
2682      * }</pre></blockquote>
2683      * @param target the method handle to invoke after arguments are combined
2684      * @param combiner method handle to call initially on the incoming arguments
2685      * @return method handle which incorporates the specified argument folding logic
2686      * @throws NullPointerException if either argument is null
2687      * @throws IllegalArgumentException if {@code combiner}'s return type
2688      *          is non-void and not the same as the first argument type of
2689      *          the target, or if the initial {@code N} argument types
2690      *          of the target
2691      *          (skipping one matching the {@code combiner}'s return type)
2692      *          are not identical with the argument types of {@code combiner}
2693      */
2694     public static
2695     MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
2696         int pos = 0;
2697         MethodType targetType = target.type();
2698         MethodType combinerType = combiner.type();
2699         int foldPos = pos;
2700         int foldArgs = combinerType.parameterCount();
2701         int foldVals = combinerType.returnType() == void.class ? 0 : 1;
2702         int afterInsertPos = foldPos + foldVals;
2703         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
2704         if (ok && !(combinerType.parameterList()
2705                     .equals(targetType.parameterList().subList(afterInsertPos,
2706                                                                afterInsertPos + foldArgs))))
2707             ok = false;
2708         if (ok && foldVals != 0 && !combinerType.returnType().equals(targetType.parameterType(0)))
2709             ok = false;
2710         if (!ok)
2711             throw misMatchedTypes("target and combiner types", targetType, combinerType);
2712         MethodType newType = targetType.dropParameterTypes(foldPos, afterInsertPos);
2713         return MethodHandleImpl.makeCollectArguments(target, combiner, foldPos, true);
2714     }
2715 
2716     /**
2717      * Makes a method handle which adapts a target method handle,
2718      * by guarding it with a test, a boolean-valued method handle.
2719      * If the guard fails, a fallback handle is called instead.
2720      * All three method handles must have the same corresponding
2721      * argument and return types, except that the return type
2722      * of the test must be boolean, and the test is allowed
2723      * to have fewer arguments than the other two method handles.
2724      * <p> Here is pseudocode for the resulting adapter:
2725      * <blockquote><pre>{@code
2726      * boolean test(A...);
2727      * T target(A...,B...);
2728      * T fallback(A...,B...);
2729      * T adapter(A... a,B... b) {
2730      *   if (test(a...))
2731      *     return target(a..., b...);
2732      *   else
2733      *     return fallback(a..., b...);
2734      * }
2735      * }</pre></blockquote>
2736      * Note that the test arguments ({@code a...} in the pseudocode) cannot
2737      * be modified by execution of the test, and so are passed unchanged
2738      * from the caller to the target or fallback as appropriate.
2739      * @param test method handle used for test, must return boolean
2740      * @param target method handle to call if test passes
2741      * @param fallback method handle to call if test fails
2742      * @return method handle which incorporates the specified if/then/else logic
2743      * @throws NullPointerException if any argument is null
2744      * @throws IllegalArgumentException if {@code test} does not return boolean,
2745      *          or if all three method types do not match (with the return
2746      *          type of {@code test} changed to match that of the target).
2747      */
2748     public static
2749     MethodHandle guardWithTest(MethodHandle test,
2750                                MethodHandle target,
2751                                MethodHandle fallback) {
2752         MethodType gtype = test.type();
2753         MethodType ttype = target.type();
2754         MethodType ftype = fallback.type();
2755         if (!ttype.equals(ftype))
2756             throw misMatchedTypes("target and fallback types", ttype, ftype);
2757         if (gtype.returnType() != boolean.class)
2758             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
2759         List<Class<?>> targs = ttype.parameterList();
2760         List<Class<?>> gargs = gtype.parameterList();
2761         if (!targs.equals(gargs)) {
2762             int gpc = gargs.size(), tpc = targs.size();
2763             if (gpc >= tpc || !targs.subList(0, gpc).equals(gargs))
2764                 throw misMatchedTypes("target and test types", ttype, gtype);
2765             test = dropArguments(test, gpc, targs.subList(gpc, tpc));
2766             gtype = test.type();
2767         }
2768         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
2769     }
2770 
2771     static RuntimeException misMatchedTypes(String what, MethodType t1, MethodType t2) {
2772         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
2773     }
2774 
2775     /**
2776      * Makes a method handle which adapts a target method handle,
2777      * by running it inside an exception handler.
2778      * If the target returns normally, the adapter returns that value.
2779      * If an exception matching the specified type is thrown, the fallback
2780      * handle is called instead on the exception, plus the original arguments.
2781      * <p>
2782      * The target and handler must have the same corresponding
2783      * argument and return types, except that handler may omit trailing arguments
2784      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
2785      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
2786      * <p> Here is pseudocode for the resulting adapter:
2787      * <blockquote><pre>{@code
2788      * T target(A..., B...);
2789      * T handler(ExType, A...);
2790      * T adapter(A... a, B... b) {
2791      *   try {
2792      *     return target(a..., b...);
2793      *   } catch (ExType ex) {
2794      *     return handler(ex, a...);
2795      *   }
2796      * }
2797      * }</pre></blockquote>
2798      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
2799      * be modified by execution of the target, and so are passed unchanged
2800      * from the caller to the handler, if the handler is invoked.
2801      * <p>
2802      * The target and handler must return the same type, even if the handler
2803      * always throws.  (This might happen, for instance, because the handler
2804      * is simulating a {@code finally} clause).
2805      * To create such a throwing handler, compose the handler creation logic
2806      * with {@link #throwException throwException},
2807      * in order to create a method handle of the correct return type.
2808      * @param target method handle to call
2809      * @param exType the type of exception which the handler will catch
2810      * @param handler method handle to call if a matching exception is thrown
2811      * @return method handle which incorporates the specified try/catch logic
2812      * @throws NullPointerException if any argument is null
2813      * @throws IllegalArgumentException if {@code handler} does not accept
2814      *          the given exception type, or if the method handle types do
2815      *          not match in their return types and their
2816      *          corresponding parameters
2817      */
2818     public static
2819     MethodHandle catchException(MethodHandle target,
2820                                 Class<? extends Throwable> exType,
2821                                 MethodHandle handler) {
2822         MethodType ttype = target.type();
2823         MethodType htype = handler.type();
2824         if (htype.parameterCount() < 1 ||
2825             !htype.parameterType(0).isAssignableFrom(exType))
2826             throw newIllegalArgumentException("handler does not accept exception type "+exType);
2827         if (htype.returnType() != ttype.returnType())
2828             throw misMatchedTypes("target and handler return types", ttype, htype);
2829         List<Class<?>> targs = ttype.parameterList();
2830         List<Class<?>> hargs = htype.parameterList();
2831         hargs = hargs.subList(1, hargs.size());  // omit leading parameter from handler
2832         if (!targs.equals(hargs)) {
2833             int hpc = hargs.size(), tpc = targs.size();
2834             if (hpc >= tpc || !targs.subList(0, hpc).equals(hargs))
2835                 throw misMatchedTypes("target and handler types", ttype, htype);
2836             handler = dropArguments(handler, 1+hpc, targs.subList(hpc, tpc));
2837             htype = handler.type();
2838         }
2839         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
2840     }
2841 
2842     /**
2843      * Produces a method handle which will throw exceptions of the given {@code exType}.
2844      * The method handle will accept a single argument of {@code exType},
2845      * and immediately throw it as an exception.
2846      * The method type will nominally specify a return of {@code returnType}.
2847      * The return type may be anything convenient:  It doesn't matter to the
2848      * method handle's behavior, since it will never return normally.
2849      * @param returnType the return type of the desired method handle
2850      * @param exType the parameter type of the desired method handle
2851      * @return method handle which can throw the given exceptions
2852      * @throws NullPointerException if either argument is null
2853      */
2854     public static
2855     MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
2856         if (!Throwable.class.isAssignableFrom(exType))
2857             throw new ClassCastException(exType.getName());
2858         return MethodHandleImpl.throwException(MethodType.methodType(returnType, exType));
2859     }
2860 }